code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-16-1.js * @description Function.prototype.bind, [[Extensible]] of the bound fn is true */ function testcase() { function foo() { } var o = {}; var bf = foo.bind(o); var ex = Object.isExtensible(bf); if (ex === true) { return true; } } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-16-1.js
JavaScript
bsd-3-clause
396
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-10-6.js * @description Array.prototype.reduce - subclassed array when initialvalue provided */ function testcase() { foo.prototype = [1,2,3,4]; function foo() {} var f = new foo(); function cb(prevVal, curVal, idx, obj){return prevVal + curVal;} if(f.reduce(cb,-1) === 9) return true; } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-10-6.js
JavaScript
bsd-3-clause
448
// META: title=NativeIO API: Interface is not exposed in untrustworthy origin. // META: global=window,dedicatedworker 'use strict'; test(testCase => { var present = (typeof storageFoundation !== 'undefined'); assert_false(present); }, 'NativeIO should not be accessible from an untrustworthy origin');
nwjs/chromium.src
third_party/blink/web_tests/external/wpt/native-io/trustworthy_origin_failure.tentative.http.any.js
JavaScript
bsd-3-clause
308
import jsonpatch from 'jsonpatch'; import {localHooks} from '../../mixins/localHooks'; import {mixin} from '../../helpers/object'; import {cleanPatches} from './utils'; /** * @class DataObserver * @plugin ObserveChanges * @dependencies jsonpatch */ class DataObserver { constructor(observedData) { /** * Observed source data. * * @type {Array} */ this.observedData = null; /** * JsonPatch observer. * * @type {Object} */ this.observer = null; /** * Flag which determines if observer is paused or not. Paused observer doesn't emit `change` hooks. * * @type {Boolean} * @default false */ this.paused = false; this.setObservedData(observedData); } /** * Set data to observe. * * @param {*} observedData */ setObservedData(observedData) { if (this.observer) { jsonpatch.unobserve(this.observedData, this.observer); } this.observedData = observedData; this.observer = jsonpatch.observe(this.observedData, (patches) => this.onChange(patches)); } /** * Check if observer was paused. * * @returns {Boolean} */ isPaused() { return this.paused; } /** * Pause observer (stop emitting all detected changes). */ pause() { this.paused = true; } /** * Resume observer (emit all detected changes). */ resume() { this.paused = false; } /** * JsonPatch on change listener. * * @private * @param {Array} patches An array of object passed from jsonpatch. */ onChange(patches) { this.runLocalHooks('change', cleanPatches(patches)); } /** * Destroy observer instance. */ destroy() { jsonpatch.unobserve(this.observedData, this.observer); this.observedData = null; this.observer = null; } } mixin(DataObserver, localHooks); export {DataObserver};
stevemoore113/ch_web_-
資源/CCEI/handsontable/src/plugins/observeChanges/dataObserver.js
JavaScript
mit
1,878
// YUI3 File Picker module for moodle // Author: Dongsheng Cai <dongsheng@moodle.com> /** * * File Picker UI * ===== * this.fpnode, contains reference to filepicker Node, non-empty if and only if rendered * this.api, stores the URL to make ajax request * this.mainui, YUI Panel * this.selectnode, contains reference to select-file Node * this.selectui, YUI Panel for selecting particular file * this.msg_dlg, YUI Panel for error or info message * this.process_dlg, YUI Panel for processing existing filename * this.treeview, YUI Treeview * this.viewmode, store current view mode * this.pathbar, reference to the Node with path bar * this.pathnode, a Node element representing one folder in a path bar (not attached anywhere, just used for template) * this.currentpath, the current path in the repository (or last requested path) * * Filepicker options: * ===== * this.options.client_id, the instance id * this.options.contextid * this.options.itemid * this.options.repositories, stores all repositories displayed in file picker * this.options.formcallback * * Active repository options * ===== * this.active_repo.id * this.active_repo.defaultreturntype * this.active_repo.nosearch * this.active_repo.norefresh * this.active_repo.nologin * this.active_repo.help * this.active_repo.manage * * Server responses * ===== * this.filelist, cached filelist * this.pages * this.page * this.filepath, current path (each element of the array is a part of the breadcrumb) * this.logindata, cached login form */ YUI.add('moodle-core_filepicker', function(Y) { /** help function to extract width/height style as a number, not as a string */ Y.Node.prototype.getStylePx = function(attr) { var style = this.getStyle(attr); if (''+style == '0' || ''+style == '0px') { return 0; } var matches = style.match(/^([\d\.]+)px$/) if (matches && parseFloat(matches[1])) { return parseFloat(matches[1]); } return null; } /** if condition is met, the class is added to the node, otherwise - removed */ Y.Node.prototype.addClassIf = function(className, condition) { if (condition) { this.addClass(className); } else { this.removeClass(className); } return this; } /** sets the width(height) of the node considering existing minWidth(minHeight) */ Y.Node.prototype.setStyleAdv = function(stylename, value) { var stylenameCap = stylename.substr(0,1).toUpperCase() + stylename.substr(1, stylename.length-1).toLowerCase(); this.setStyle(stylename, '' + Math.max(value, this.getStylePx('min'+stylenameCap)) + 'px') return this; } /** set image source to src, if there is preview, remember it in lazyloading. * If there is a preview and it was already loaded, use it. */ Y.Node.prototype.setImgSrc = function(src, realsrc, lazyloading) { if (realsrc) { if (M.core_filepicker.loadedpreviews[realsrc]) { this.set('src', realsrc).addClass('realpreview'); return this; } else { if (!this.get('id')) { this.generateID(); } lazyloading[this.get('id')] = realsrc; } } this.set('src', src); return this; } /** * Replaces the image source with preview. If the image is inside the treeview, we need * also to update the html property of corresponding YAHOO.widget.HTMLNode * @param array lazyloading array containing associations of imgnodeid->realsrc */ Y.Node.prototype.setImgRealSrc = function(lazyloading) { if (this.get('id') && lazyloading[this.get('id')]) { var newsrc = lazyloading[this.get('id')]; M.core_filepicker.loadedpreviews[newsrc] = true; this.set('src', newsrc).addClass('realpreview'); delete lazyloading[this.get('id')]; var treenode = this.ancestor('.fp-treeview') if (treenode && treenode.get('parentNode').treeview) { treenode.get('parentNode').treeview.getRoot().refreshPreviews(this.get('id'), newsrc); } } return this; } /** scan TreeView to find which node contains image with id=imgid and replace it's html * with the new image source. */ Y.YUI2.widget.Node.prototype.refreshPreviews = function(imgid, newsrc, regex) { if (!regex) { regex = new RegExp("<img\\s[^>]*id=\""+imgid+"\"[^>]*?(/?)>", "im"); } if (this.expanded || this.isLeaf) { var html = this.getContentHtml(); if (html && this.setHtml && regex.test(html)) { var newhtml = this.html.replace(regex, "<img id=\""+imgid+"\" src=\""+newsrc+"\" class=\"realpreview\"$1>", html); this.setHtml(newhtml); return true; } if (!this.isLeaf && this.children) { for(var c in this.children) { if (this.children[c].refreshPreviews(imgid, newsrc, regex)) { return true; } } } } return false; } /** * Displays a list of files (used by filepicker, filemanager) inside the Node * * @param array options * viewmode : 1 - icons, 2 - tree, 3 - table * appendonly : whether fileslist need to be appended instead of replacing the existing content * filenode : Node element that contains template for displaying one file * callback : On click callback. The element of the fileslist array will be passed as argument * rightclickcallback : On right click callback (optional). * callbackcontext : context where callbacks are executed * sortable : whether content may be sortable (in table mode) * dynload : allow dynamic load for tree view * filepath : for pre-building of tree view - the path to the current directory in filepicker format * treeview_dynload : callback to function to dynamically load the folder in tree view * classnamecallback : callback to function that returns the class name for an element * @param array fileslist array of files to show, each array element may have attributes: * title or fullname : file name * shorttitle (optional) : display file name * thumbnail : url of image * icon : url of icon image * thumbnail_width : width of thumbnail, default 90 * thumbnail_height : height of thumbnail, default 90 * thumbnail_alt : TODO not needed! * description or thumbnail_title : alt text * @param array lazyloading : reference to the array with lazy loading images */ Y.Node.prototype.fp_display_filelist = function(options, fileslist, lazyloading) { var viewmodeclassnames = {1:'fp-iconview', 2:'fp-treeview', 3:'fp-tableview'}; var classname = viewmodeclassnames[options.viewmode]; var scope = this; /** return whether file is a folder (different attributes in FileManager and FilePicker) */ var file_is_folder = function(node) { if (node.children) {return true;} if (node.type && node.type == 'folder') {return true;} return false; }; /** return the name of the file (different attributes in FileManager and FilePicker) */ var file_get_filename = function(node) { return node.title ? node.title : node.fullname; }; /** return display name of the file (different attributes in FileManager and FilePicker) */ var file_get_displayname = function(node) { var displayname = node.shorttitle ? node.shorttitle : file_get_filename(node); return Y.Escape.html(displayname); }; /** return file description (different attributes in FileManager and FilePicker) */ var file_get_description = function(node) { var description = ''; if (node.description) { description = node.description; } else if (node.thumbnail_title) { description = node.thumbnail_title; } else { description = file_get_filename(node); } return Y.Escape.html(description); }; /** help funciton for tree view */ var build_tree = function(node, level) { // prepare file name with icon var el = Y.Node.create('<div/>'); el.appendChild(options.filenode.cloneNode(true)); el.one('.fp-filename').setContent(file_get_displayname(node)); // TODO add tooltip with node.title or node.thumbnail_title var tmpnodedata = {className:options.classnamecallback(node)}; el.get('children').addClass(tmpnodedata.className); if (node.icon) { el.one('.fp-icon').appendChild(Y.Node.create('<img/>')); el.one('.fp-icon img').setImgSrc(node.icon, node.realicon, lazyloading); } // create node tmpnodedata.html = el.getContent(); var tmpNode = new Y.YUI2.widget.HTMLNode(tmpnodedata, level, false); if (node.dynamicLoadComplete) { tmpNode.dynamicLoadComplete = true; } tmpNode.fileinfo = node; tmpNode.isLeaf = !file_is_folder(node); if (!tmpNode.isLeaf) { if(node.expanded) { tmpNode.expand(); } tmpNode.path = node.path ? node.path : (node.filepath ? node.filepath : ''); for(var c in node.children) { build_tree(node.children[c], tmpNode); } } }; /** initialize tree view */ var initialize_tree_view = function() { var parentid = scope.one('.'+classname).get('id'); // TODO MDL-32736 use YUI3 gallery TreeView scope.treeview = new Y.YUI2.widget.TreeView(parentid); if (options.dynload) { scope.treeview.setDynamicLoad(Y.bind(options.treeview_dynload, options.callbackcontext), 1); } scope.treeview.singleNodeHighlight = true; if (options.filepath && options.filepath.length) { // we just jumped from icon/details view, we need to show all parents // we extract as much information as possible from filepath and filelist // and send additional requests to retrieve siblings for parent folders var mytree = {}; var mytreeel = null; for (var i in options.filepath) { if (mytreeel == null) { mytreeel = mytree; } else { mytreeel.children = [{}]; mytreeel = mytreeel.children[0]; } var pathelement = options.filepath[i]; mytreeel.path = pathelement.path; mytreeel.title = pathelement.name; mytreeel.icon = pathelement.icon; mytreeel.dynamicLoadComplete = true; // we will call it manually mytreeel.expanded = true; } mytreeel.children = fileslist; build_tree(mytree, scope.treeview.getRoot()); // manually call dynload for parent elements in the tree so we can load other siblings if (options.dynload) { var root = scope.treeview.getRoot(); // Whether search results are currently displayed in the active repository in the filepicker. // We do not want to load siblings of parent elements when displaying search tree results. var isSearchResult = typeof options.callbackcontext.active_repo !== 'undefined' && options.callbackcontext.active_repo.issearchresult; while (root && root.children && root.children.length) { root = root.children[0]; if (root.path == mytreeel.path) { root.origpath = options.filepath; root.origlist = fileslist; } else if (!root.isLeaf && root.expanded && !isSearchResult) { Y.bind(options.treeview_dynload, options.callbackcontext)(root, null); } } } } else { // there is no path information, just display all elements as a list, without hierarchy for(k in fileslist) { build_tree(fileslist[k], scope.treeview.getRoot()); } } scope.treeview.subscribe('clickEvent', function(e){ e.node.highlight(false); var callback = options.callback; if (options.rightclickcallback && e.event.target && Y.Node(e.event.target).ancestor('.fp-treeview .fp-contextmenu', true)) { callback = options.rightclickcallback; } Y.bind(callback, options.callbackcontext)(e, e.node.fileinfo); Y.YUI2.util.Event.stopEvent(e.event) }); // TODO MDL-32736 support right click /*if (options.rightclickcallback) { scope.treeview.subscribe('dblClickEvent', function(e){ e.node.highlight(false); Y.bind(options.rightclickcallback, options.callbackcontext)(e, e.node.fileinfo); }); }*/ scope.treeview.draw(); }; /** formatting function for table view */ var formatValue = function (o){ if (o.data[''+o.column.key+'_f_s']) {return o.data[''+o.column.key+'_f_s'];} else if (o.data[''+o.column.key+'_f']) {return o.data[''+o.column.key+'_f'];} else if (o.value) {return o.value;} else {return '';} }; /** formatting function for table view */ var formatTitle = function(o) { var el = Y.Node.create('<div/>'); el.appendChild(options.filenode.cloneNode(true)); // TODO not node but string! el.get('children').addClass(o.data['classname']); el.one('.fp-filename').setContent(o.value); if (o.data['icon']) { el.one('.fp-icon').appendChild(Y.Node.create('<img/>')); el.one('.fp-icon img').setImgSrc(o.data['icon'], o.data['realicon'], lazyloading); } if (options.rightclickcallback) { el.get('children').addClass('fp-hascontextmenu'); } // TODO add tooltip with o.data['title'] (o.value) or o.data['thumbnail_title'] return el.getContent(); } /** * Generate slave checkboxes based on toggleall's specification * @param {object} o An object reprsenting the record for the current row. * @return {html} The checkbox html */ var formatCheckbox = function(o) { var el = Y.Node.create('<div/>'); var checkbox = Y.Node.create('<input/>') .setAttribute('type', 'checkbox') .setAttribute('data-fieldtype', 'checkbox') .setAttribute('data-fullname', o.data.fullname) .setAttribute('data-action', 'toggle') .setAttribute('data-toggle', 'slave') .setAttribute('data-togglegroup', 'file-selections') .setAttribute('data-toggle-selectall', M.util.get_string('selectall', 'moodle')) .setAttribute('data-toggle-deselectall', M.util.get_string('deselectall', 'moodle')); var checkboxLabel = Y.Node.create('<label>') .setHTML("Select file '" + o.data.fullname + "'") .addClass('sr-only') .setAttrs({ for: checkbox.generateID(), }); el.appendChild(checkbox); el.appendChild(checkboxLabel); return el.getContent(); }; /** sorting function for table view */ var sortFoldersFirst = function(a, b, desc) { if (a.get('isfolder') && !b.get('isfolder')) { return -1; } if (!a.get('isfolder') && b.get('isfolder')) { return 1; } var aa = a.get(this.key), bb = b.get(this.key), dir = desc ? -1 : 1; return (aa > bb) ? dir : ((aa < bb) ? -dir : 0); } /** initialize table view */ var initialize_table_view = function() { var cols = [ {key: "displayname", label: M.util.get_string('name', 'moodle'), allowHTML: true, formatter: formatTitle, sortable: true, sortFn: sortFoldersFirst}, {key: "datemodified", label: M.util.get_string('lastmodified', 'moodle'), allowHTML: true, formatter: formatValue, sortable: true, sortFn: sortFoldersFirst}, {key: "size", label: M.util.get_string('size', 'repository'), allowHTML: true, formatter: formatValue, sortable: true, sortFn: sortFoldersFirst}, {key: "mimetype", label: M.util.get_string('type', 'repository'), allowHTML: true, sortable: true, sortFn: sortFoldersFirst} ]; // Generate a checkbox based on toggleall's specification var div = Y.Node.create('<div/>'); var checkbox = Y.Node.create('<input/>') .setAttribute('type', 'checkbox') // .setAttribute('title', M.util.get_string('selectallornone', 'form')) .setAttribute('data-action', 'toggle') .setAttribute('data-toggle', 'master') .setAttribute('data-togglegroup', 'file-selections'); var checkboxLabel = Y.Node.create('<label>') .setHTML(M.util.get_string('selectallornone', 'form')) .addClass('sr-only') .setAttrs({ for: checkbox.generateID(), }); div.appendChild(checkboxLabel); div.appendChild(checkbox); // Define the selector for the click event handler. var clickEventSelector = 'tr'; // Enable the selectable checkboxes if (options.disablecheckboxes != undefined && !options.disablecheckboxes) { clickEventSelector = 'tr td:not(:first-child)'; cols.unshift({ key: "", label: div.getContent(), allowHTML: true, formatter: formatCheckbox, sortable: false }); } scope.tableview = new Y.DataTable({columns: cols, data: fileslist}); scope.tableview.delegate('click', function (e, tableview) { var record = tableview.getRecord(e.currentTarget.get('id')); if (record) { var callback = options.callback; if (options.rightclickcallback && e.target.ancestor('.fp-tableview .fp-contextmenu', true)) { callback = options.rightclickcallback; } Y.bind(callback, this)(e, record.getAttrs()); } }, clickEventSelector, options.callbackcontext, scope.tableview); if (options.rightclickcallback) { scope.tableview.delegate('contextmenu', function (e, tableview) { var record = tableview.getRecord(e.currentTarget.get('id')); if (record) { Y.bind(options.rightclickcallback, this)(e, record.getAttrs()); } }, 'tr', options.callbackcontext, scope.tableview); } } /** append items in table view mode */ var append_files_table = function() { if (options.appendonly) { fileslist.forEach(function(el) { this.tableview.data.add(el); },scope); } scope.tableview.render(scope.one('.'+classname)); scope.tableview.sortable = options.sortable ? true : false; }; /** append items in tree view mode */ var append_files_tree = function() { if (options.appendonly) { var parentnode = scope.treeview.getRoot(); if (scope.treeview.getHighlightedNode()) { parentnode = scope.treeview.getHighlightedNode(); if (parentnode.isLeaf) {parentnode = parentnode.parent;} } for (var k in fileslist) { build_tree(fileslist[k], parentnode); } scope.treeview.draw(); } else { // otherwise files were already added in initialize_tree_view() } } /** append items in icon view mode */ var append_files_icons = function() { parent = scope.one('.'+classname); for (var k in fileslist) { var node = fileslist[k]; var element = options.filenode.cloneNode(true); parent.appendChild(element); element.addClass(options.classnamecallback(node)); var filenamediv = element.one('.fp-filename'); filenamediv.setContent(file_get_displayname(node)); var imgdiv = element.one('.fp-thumbnail'), width, height, src; if (node.thumbnail) { width = node.thumbnail_width ? node.thumbnail_width : 90; height = node.thumbnail_height ? node.thumbnail_height : 90; src = node.thumbnail; } else { width = 16; height = 16; src = node.icon; } filenamediv.setStyleAdv('width', width); imgdiv.setStyleAdv('width', width).setStyleAdv('height', height); var img = Y.Node.create('<img/>').setAttrs({ title: file_get_description(node), alt: Y.Escape.html(node.thumbnail_alt ? node.thumbnail_alt : file_get_filename(node))}). setStyle('maxWidth', ''+width+'px'). setStyle('maxHeight', ''+height+'px'); img.setImgSrc(src, node.realthumbnail, lazyloading); imgdiv.appendChild(img); element.on('click', function(e, nd) { if (options.rightclickcallback && e.target.ancestor('.fp-iconview .fp-contextmenu', true)) { Y.bind(options.rightclickcallback, this)(e, nd); } else { Y.bind(options.callback, this)(e, nd); } }, options.callbackcontext, node); if (options.rightclickcallback) { element.on('contextmenu', options.rightclickcallback, options.callbackcontext, node); } } } // Notify the user if any of the files has a problem status. var problemFiles = []; fileslist.forEach(function(file) { if (!file_is_folder(file) && file.hasOwnProperty('status') && file.status != 0) { problemFiles.push(file); } }); if (problemFiles.length > 0) { require(["core/notification", "core/str"], function(Notification, Str) { problemFiles.forEach(function(problemFile) { Str.get_string('storedfilecannotreadfile', 'error', problemFile.fullname).then(function(string) { Notification.addNotification({ message: string, type: "error" }); return; }).catch(Notification.exception); }); }); } // If table view, need some additional properties // before passing fileslist to the YUI tableview if (options.viewmode == 3) { fileslist.forEach(function(el) { el.displayname = file_get_displayname(el); el.isfolder = file_is_folder(el); el.classname = options.classnamecallback(el); }, scope); } // initialize files view if (!options.appendonly) { var parent = Y.Node.create('<div/>').addClass(classname); this.setContent('').appendChild(parent); parent.generateID(); if (options.viewmode == 2) { initialize_tree_view(); } else if (options.viewmode == 3) { initialize_table_view(); } else { // nothing to initialize for icon view } } // append files to the list if (options.viewmode == 2) { append_files_tree(); } else if (options.viewmode == 3) { append_files_table(); } else { append_files_icons(); } } }, '@VERSION@', { requires:['base', 'node', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort'] }); M.core_filepicker = M.core_filepicker || {}; /** * instances of file pickers used on page */ M.core_filepicker.instances = M.core_filepicker.instances || {}; M.core_filepicker.active_filepicker = null; /** * HTML Templates to use in FilePicker */ M.core_filepicker.templates = M.core_filepicker.templates || {}; /** * Array of image sources for real previews (realicon or realthumbnail) that are already loaded */ M.core_filepicker.loadedpreviews = M.core_filepicker.loadedpreviews || {}; /** * Set selected file info * * @param object file info */ M.core_filepicker.select_file = function(file) { M.core_filepicker.active_filepicker.select_file(file); } /** * Init and show file picker */ M.core_filepicker.show = function(Y, options) { if (!M.core_filepicker.instances[options.client_id]) { M.core_filepicker.init(Y, options); } M.core_filepicker.instances[options.client_id].options.formcallback = options.formcallback; M.core_filepicker.instances[options.client_id].show(); }; M.core_filepicker.set_templates = function(Y, templates) { for (var templid in templates) { M.core_filepicker.templates[templid] = templates[templid]; } } /** * Add new file picker to current instances */ M.core_filepicker.init = function(Y, options) { var FilePickerHelper = function(options) { FilePickerHelper.superclass.constructor.apply(this, arguments); }; FilePickerHelper.NAME = "FilePickerHelper"; FilePickerHelper.ATTRS = { options: {}, lang: {} }; Y.extend(FilePickerHelper, Y.Base, { api: M.cfg.wwwroot+'/repository/repository_ajax.php', cached_responses: {}, waitinterval : null, // When the loading template is being displayed and its animation is running this will be an interval instance. initializer: function(options) { this.options = options; if (!this.options.savepath) { this.options.savepath = '/'; } }, destructor: function() { }, request: function(args, redraw) { var api = (args.api ? args.api : this.api) + '?action='+args.action; var params = {}; var scope = args['scope'] ? args['scope'] : this; params['repo_id']=args.repository_id; params['p'] = args.path?args.path:''; params['page'] = args.page?args.page:''; params['env']=this.options.env; // the form element only accept certain file types params['accepted_types']=this.options.accepted_types; params['sesskey'] = M.cfg.sesskey; params['client_id'] = args.client_id; params['itemid'] = this.options.itemid?this.options.itemid:0; params['maxbytes'] = this.options.maxbytes?this.options.maxbytes:-1; // The unlimited value of areamaxbytes is -1, it is defined by FILE_AREA_MAX_BYTES_UNLIMITED. params['areamaxbytes'] = this.options.areamaxbytes ? this.options.areamaxbytes : -1; if (this.options.context && this.options.context.id) { params['ctx_id'] = this.options.context.id; } if (args['params']) { for (i in args['params']) { params[i] = args['params'][i]; } } if (args.action == 'upload') { var list = []; for(var k in params) { var value = params[k]; if(value instanceof Array) { for(var i in value) { list.push(k+'[]='+value[i]); } } else { list.push(k+'='+value); } } params = list.join('&'); } else { params = build_querystring(params); } var cfg = { method: 'POST', on: { complete: function(id,o,p) { var data = null; try { data = Y.JSON.parse(o.responseText); } catch(e) { if (o && o.status && o.status > 0) { Y.use('moodle-core-notification-exception', function() { return new M.core.exception(e); }); return; } } // error checking if (data && data.error) { Y.use('moodle-core-notification-ajaxexception', function () { return new M.core.ajaxException(data); }); this.fpnode.one('.fp-content').setContent(''); return; } else { if (data.msg) { scope.print_msg(data.msg, 'info'); } // cache result if applicable if (args.action != 'upload' && data.allowcaching) { scope.cached_responses[params] = data; } // invoke callback args.callback(id,data,p); } } }, arguments: { scope: scope }, headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, data: params, context: this }; if (args.form) { cfg.form = args.form; } // check if result of the same request has been already cached. If not, request it // (never applicable in case of form submission and/or upload action): if (!args.form && args.action != 'upload' && scope.cached_responses[params]) { args.callback(null, scope.cached_responses[params], {scope: scope}) } else { Y.io(api, cfg); if (redraw) { this.wait(); } } }, /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/ process_existing_file: function(data) { var scope = this; var handleOverwrite = function(e) { // overwrite e.preventDefault(); var data = this.process_dlg.dialogdata; var params = {} params['existingfilename'] = data.existingfile.filename; params['existingfilepath'] = data.existingfile.filepath; params['newfilename'] = data.newfile.filename; params['newfilepath'] = data.newfile.filepath; this.hide_header(); this.request({ 'params': params, 'scope': this, 'action':'overwrite', 'path': '', 'client_id': this.options.client_id, 'repository_id': this.active_repo.id, 'callback': function(id, o, args) { scope.hide(); // Add an arbitrary parameter to the URL to force browsers to re-load the new image even // if the file name has not changed. var urlimage = data.existingfile.url + "?time=" + (new Date()).getTime(); if (scope.options.editor_target && scope.options.env == 'editor') { // editor needs to update url scope.options.editor_target.value = urlimage; scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true}); } var fileinfo = {'client_id':scope.options.client_id, 'url': urlimage, 'file': data.existingfile.filename}; var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope; scope.options.formcallback.apply(formcallback_scope, [fileinfo]); } }, true); } var handleRename = function(e) { // inserts file with the new name e.preventDefault(); var scope = this; var data = this.process_dlg.dialogdata; if (scope.options.editor_target && scope.options.env == 'editor') { scope.options.editor_target.value = data.newfile.url; scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true}); } scope.hide(); var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope; var fileinfo = {'client_id':scope.options.client_id, 'url':data.newfile.url, 'file':data.newfile.filename}; scope.options.formcallback.apply(formcallback_scope, [fileinfo]); } var handleCancel = function(e) { // Delete tmp file e.preventDefault(); var params = {}; params['newfilename'] = this.process_dlg.dialogdata.newfile.filename; params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath; this.request({ 'params': params, 'scope': this, 'action':'deletetmpfile', 'path': '', 'client_id': this.options.client_id, 'repository_id': this.active_repo.id, 'callback': function(id, o, args) { // let it be in background, from user point of view nothing is happenning } }, false); this.process_dlg.hide(); this.selectui.hide(); } if (!this.process_dlg) { this.process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfile); var node = this.process_dlg_node; node.generateID(); this.process_dlg = new M.core.dialogue({ draggable : true, bodyContent : node, headerContent: M.util.get_string('fileexistsdialogheader', 'repository'), centered : true, modal : true, visible : false, zIndex : this.options.zIndex }); node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this); node.one('.fp-dlg-butrename').on('click', handleRename, this); node.one('.fp-dlg-butcancel').on('click', handleCancel, this); if (this.options.env == 'editor') { node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_editor', 'repository')); } else { node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_filemanager', 'repository')); } } this.selectnode.removeClass('loading'); this.process_dlg.dialogdata = data; this.process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename)); this.process_dlg.show(); }, /** displays error instead of filepicker contents */ display_error: function(errortext, errorcode) { this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error); this.fpnode.one('.fp-content .fp-error'). addClass(errorcode). setContent(Y.Escape.html(errortext)); }, /** displays message in a popup */ print_msg: function(msg, type) { var header = M.util.get_string('error', 'moodle'); if (type != 'error') { type = 'info'; // one of only two types excepted header = M.util.get_string('info', 'moodle'); } if (!this.msg_dlg) { this.msg_dlg_node = Y.Node.create(M.core_filepicker.templates.message); this.msg_dlg_node.generateID(); this.msg_dlg = new M.core.dialogue({ draggable : true, bodyContent : this.msg_dlg_node, centered : true, modal : true, visible : false, zIndex : this.options.zIndex }); this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) { e.preventDefault(); this.msg_dlg.hide(); }, this); } this.msg_dlg.set('headerContent', header); this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type) this.msg_dlg_node.one('.fp-msg-text').setContent(Y.Escape.html(msg)); this.msg_dlg.show(); }, view_files: function(appenditems) { this.viewbar_set_enabled(true); this.print_path(); /*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) { // TODO do it via classes and adjust for each view mode! // If there are no items and no next page, just display status message and quit this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable'); return; }*/ if (this.viewmode == 2) { this.view_as_list(appenditems); } else if (this.viewmode == 3) { this.view_as_table(appenditems); } else { this.view_as_icons(appenditems); } this.fpnode.one('.fp-content').setAttribute('tabindex', '0'); this.fpnode.one('.fp-content').focus(); // display/hide the link for requesting next page if (!appenditems && this.active_repo.hasmorepages) { if (!this.fpnode.one('.fp-content .fp-nextpage')) { this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage); } this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) { e.preventDefault(); this.fpnode.one('.fp-content .fp-nextpage').addClass('loading'); this.request_next_page(); }, this); } if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) { this.fpnode.one('.fp-content .fp-nextpage').remove(); } if (this.fpnode.one('.fp-content .fp-nextpage')) { this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading'); } this.content_scrolled(); }, content_scrolled: function(e) { setTimeout(Y.bind(function() { if (this.processingimages) { return; } this.processingimages = true; var scope = this, fpcontent = this.fpnode.one('.fp-content'), fpcontenty = fpcontent.getY(), fpcontentheight = fpcontent.getStylePx('height'), nextpage = fpcontent.one('.fp-nextpage'), is_node_visible = function(node) { var offset = node.getY()-fpcontenty; if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) { return true; } return false; }; // automatically load next page when 'more' link becomes visible if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) { nextpage.one('a,button').simulate('click'); } // replace src for visible images that need to be lazy-loaded if (scope.lazyloading) { fpcontent.all('img').each( function(node) { if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) { node.setImgRealSrc(scope.lazyloading); } }); } this.processingimages = false; }, this), 200) }, treeview_dynload: function(node, cb) { var retrieved_children = {}; if (node.children) { for (var i in node.children) { retrieved_children[node.children[i].path] = node.children[i]; } } this.request({ action:'list', client_id: this.options.client_id, repository_id: this.active_repo.id, path:node.path?node.path:'', page:node.page?args.page:'', scope:this, callback: function(id, obj, args) { var list = obj.list; var scope = args.scope; // check that user did not leave the view mode before recieving this response if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) { return; } if (cb != null) { // (in manual mode do not update current path) scope.viewbar_set_enabled(true); scope.parse_repository_options(obj); } node.highlight(false); node.origlist = obj.list ? obj.list : null; node.origpath = obj.path ? obj.path : null; node.children = []; for(k in list) { if (list[k].children && retrieved_children[list[k].path]) { // if this child is a folder and has already been retrieved node.children[node.children.length] = retrieved_children[list[k].path]; } else { // append new file to the list scope.view_as_list([list[k]]); } } if (cb == null) { node.refresh(); } else { // invoke callback requested by TreeView component cb(); } scope.content_scrolled(); } }, false); }, classnamecallback : function(node) { var classname = ''; if (node.children) { classname = classname + ' fp-folder'; } if (node.isref) { classname = classname + ' fp-isreference'; } if (node.iscontrolledlink) { classname = classname + ' fp-iscontrolledlink'; } if (node.refcount) { classname = classname + ' fp-hasreferences'; } if (node.originalmissing) { classname = classname + ' fp-originalmissing'; } return Y.Lang.trim(classname); }, /** displays list of files in tree (list) view mode. If param appenditems is specified, * appends those items to the end of the list. Otherwise (default behaviour) * clears the contents and displays the items from this.filelist */ view_as_list: function(appenditems) { var list = (appenditems != null) ? appenditems : this.filelist; this.viewmode = 2; if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) { this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable'); return; } var element_template = Y.Node.create(M.core_filepicker.templates.listfilename); var options = { viewmode : this.viewmode, appendonly : (appenditems != null), filenode : element_template, callbackcontext : this, callback : function(e, node) { // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node' if (!node.children) { if (e.node.parent && e.node.parent.origpath) { // set the current path this.filepath = e.node.parent.origpath; this.filelist = e.node.parent.origlist; this.print_path(); } this.select_file(node); } else { // save current path and filelist (in case we want to jump to other viewmode) this.filepath = e.node.origpath; this.filelist = e.node.origlist; this.currentpath = e.node.path; this.print_path(); this.content_scrolled(); } }, classnamecallback : this.classnamecallback, dynload : this.active_repo.dynload, filepath : this.filepath, treeview_dynload : this.treeview_dynload }; this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading); }, /** displays list of files in icon view mode. If param appenditems is specified, * appends those items to the end of the list. Otherwise (default behaviour) * clears the contents and displays the items from this.filelist */ view_as_icons: function(appenditems) { this.viewmode = 1; var list = (appenditems != null) ? appenditems : this.filelist; var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename); if ((appenditems == null) && (!this.filelist || !this.filelist.length)) { this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable'); return; } var options = { viewmode : this.viewmode, appendonly : (appenditems != null), filenode : element_template, callbackcontext : this, callback : function(e, node) { if (e.preventDefault) { e.preventDefault(); } if(node.children) { if (this.active_repo.dynload) { this.list({'path':node.path}); } else { this.filelist = node.children; this.view_files(); } } else { this.select_file(node); } }, classnamecallback : this.classnamecallback }; this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading); }, /** displays list of files in table view mode. If param appenditems is specified, * appends those items to the end of the list. Otherwise (default behaviour) * clears the contents and displays the items from this.filelist */ view_as_table: function(appenditems) { this.viewmode = 3; var list = (appenditems != null) ? appenditems : this.filelist; if (!appenditems && (!this.filelist || this.filelist.length==0) && !this.active_repo.hasmorepages) { this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable'); return; } var element_template = Y.Node.create(M.core_filepicker.templates.listfilename); var options = { viewmode : this.viewmode, appendonly : (appenditems != null), filenode : element_template, callbackcontext : this, sortable : !this.active_repo.hasmorepages, callback : function(e, node) { if (e.preventDefault) {e.preventDefault();} if (node.children) { if (this.active_repo.dynload) { this.list({'path':node.path}); } else { this.filelist = node.children; this.view_files(); } } else { this.select_file(node); } }, classnamecallback : this.classnamecallback }; this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading); }, /** If more than one page available, requests and displays the files from the next page */ request_next_page: function() { if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) { // nothing to load return; } this.active_repo.nextpagerequested = true; var nextpage = this.active_repo.page+1; var args = { page: nextpage, repo_id: this.active_repo.id }; var action = this.active_repo.issearchresult ? 'search' : 'list'; this.request({ path: this.currentpath, scope: this, action: action, client_id: this.options.client_id, repository_id: args.repo_id, params: args, callback: function(id, obj, args) { var scope = args.scope; // Check that we are still in the same repository and are expecting this page. We have no way // to compare the requested page and the one returned, so we assume that if the last chunk // of the breadcrumb is similar, then we probably are on the same page. var samepage = true; if (obj.path && scope.filepath) { var pathbefore = scope.filepath[scope.filepath.length-1]; var pathafter = obj.path[obj.path.length-1]; if (pathbefore.path != pathafter.path) { samepage = false; } } if (scope.active_repo.hasmorepages && obj.list && obj.page && obj.repo_id == scope.active_repo.id && obj.page == scope.active_repo.page+1 && samepage) { scope.parse_repository_options(obj, true); scope.view_files(obj.list) } } }, false); }, select_file: function(args) { var argstitle = args.shorttitle ? args.shorttitle : args.title; // Limit the string length so it fits nicely on mobile devices var titlelength = 30; if (argstitle.length > titlelength) { argstitle = argstitle.substring(0, titlelength) + '...'; } Y.one('#fp-file_label_'+this.options.client_id).setContent(Y.Escape.html(M.util.get_string('select', 'repository')+' '+argstitle)); this.selectui.show(); Y.one('#'+this.selectnode.get('id')).focus(); var client_id = this.options.client_id; var selectnode = this.selectnode; var return_types = this.options.repositories[this.active_repo.id].return_types; selectnode.removeClass('loading'); selectnode.one('.fp-saveas input').set('value', args.title); var imgnode = Y.Node.create('<img/>'). set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail). setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px'). setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px'); selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode); // filelink is the array of file-link-types available for this repository in this env var filelinktypes = [2/*FILE_INTERNAL*/,1/*FILE_EXTERNAL*/,4/*FILE_REFERENCE*/,8/*FILE_CONTROLLED_LINK*/]; var filelink = {}, firstfilelink = null, filelinkcount = 0; for (var i in filelinktypes) { var allowed = (return_types & filelinktypes[i]) && (this.options.return_types & filelinktypes[i]); if (filelinktypes[i] == 1/*FILE_EXTERNAL*/ && !this.options.externallink && this.options.env == 'editor') { // special configuration setting 'repositoryallowexternallinks' may prevent // using external links in editor environment allowed = false; } filelink[filelinktypes[i]] = allowed; firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink; filelinkcount += allowed ? 1 : 0; } var defaultreturntype = this.options.repositories[this.active_repo.id].defaultreturntype; if (defaultreturntype) { if (filelink[defaultreturntype]) { firstfilelink = defaultreturntype; } } // make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option // check the first available file-link-type option for (var linktype in filelink) { var el = selectnode.one('.fp-linktype-'+linktype); el.addClassIf('uneditable', !(filelink[linktype] && filelinkcount>1)); el.one('input').set('checked', (firstfilelink == linktype) ? 'checked' : '').simulate('change'); } // TODO MDL-32532: attributes 'hasauthor' and 'haslicense' need to be obsolete, selectnode.one('.fp-setauthor input').set('value', args.author ? args.author : this.options.author); this.populateLicensesSelect(selectnode.one('.fp-setlicense select'), args); selectnode.one('form #filesource-'+client_id).set('value', args.source); selectnode.one('form #filesourcekey-'+client_id).set('value', args.sourcekey); // display static information about a file (when known) var attrs = ['datemodified','datecreated','size','license','author','dimensions']; for (var i in attrs) { if (selectnode.one('.fp-'+attrs[i])) { var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : ''); selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '') .one('.fp-value').setContent(Y.Escape.html(value)); } } }, setup_select_file: function() { var client_id = this.options.client_id; var selectnode = this.selectnode; var getfile = selectnode.one('.fp-select-confirm'); // bind labels with corresponding inputs selectnode.all('.fp-saveas,.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,fp-linktype-8,.fp-setauthor,.fp-setlicense').each(function (node) { node.all('label').set('for', node.one('input,select').generateID()); }); selectnode.one('.fp-linktype-2 input').setAttrs({value: 2, name: 'linktype'}); selectnode.one('.fp-linktype-1 input').setAttrs({value: 1, name: 'linktype'}); selectnode.one('.fp-linktype-4 input').setAttrs({value: 4, name: 'linktype'}); selectnode.one('.fp-linktype-8 input').setAttrs({value: 8, name: 'linktype'}); var changelinktype = function(e) { if (e.currentTarget.get('checked')) { var allowinputs = e.currentTarget.get('value') != 1/*FILE_EXTERNAL*/; selectnode.all('.fp-setauthor,.fp-setlicense,.fp-saveas').each(function(node){ node.addClassIf('uneditable', !allowinputs); node.all('input,select').set('disabled', allowinputs?'':'disabled'); }); } }; selectnode.all('.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,.fp-linktype-8').each(function (node) { node.one('input').on('change', changelinktype, this); }); // register event on clicking submit button getfile.on('click', function(e) { e.preventDefault(); var client_id = this.options.client_id; var scope = this; var repository_id = this.active_repo.id; var title = selectnode.one('.fp-saveas input').get('value'); var filesource = selectnode.one('form #filesource-'+client_id).get('value'); var filesourcekey = selectnode.one('form #filesourcekey-'+client_id).get('value'); var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath, sourcekey: filesourcekey}; var license = selectnode.one('.fp-setlicense select'); if (license) { params['license'] = license.get('value'); var origlicense = selectnode.one('.fp-license .fp-value'); if (origlicense) { origlicense = origlicense.getContent(); } if (this.options.rememberuserlicensepref) { this.set_preference('recentlicense', license.get('value')); } } params['author'] = selectnode.one('.fp-setauthor input').get('value'); var return_types = this.options.repositories[this.active_repo.id].return_types; if (this.options.env == 'editor') { // in editor, images are stored in '/' only params.savepath = '/'; } if ((this.options.externallink || this.options.env != 'editor') && (return_types & 1/*FILE_EXTERNAL*/) && (this.options.return_types & 1/*FILE_EXTERNAL*/) && selectnode.one('.fp-linktype-1 input').get('checked')) { params['linkexternal'] = 'yes'; } else if ((return_types & 4/*FILE_REFERENCE*/) && (this.options.return_types & 4/*FILE_REFERENCE*/) && selectnode.one('.fp-linktype-4 input').get('checked')) { params['usefilereference'] = '1'; } else if ((return_types & 8/*FILE_CONTROLLED_LINK*/) && (this.options.return_types & 8/*FILE_CONTROLLED_LINK*/) && selectnode.one('.fp-linktype-8 input').get('checked')) { params['usecontrolledlink'] = '1'; } selectnode.addClass('loading'); this.request({ action:'download', client_id: client_id, repository_id: repository_id, 'params': params, onerror: function(id, obj, args) { selectnode.removeClass('loading'); scope.selectui.hide(); }, callback: function(id, obj, args) { selectnode.removeClass('loading'); if (obj.event == 'fileexists') { scope.process_existing_file(obj); return; } if (scope.options.editor_target && scope.options.env=='editor') { scope.options.editor_target.value=obj.url; scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true}); } scope.hide(); obj.client_id = client_id; var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope; scope.options.formcallback.apply(formcallback_scope, [obj]); } }, false); }, this); var elform = selectnode.one('form'); elform.appendChild(Y.Node.create('<input/>'). setAttrs({type:'hidden',id:'filesource-'+client_id})); elform.appendChild(Y.Node.create('<input/>'). setAttrs({type:'hidden',id:'filesourcekey-'+client_id})); elform.on('keydown', function(e) { if (e.keyCode == 13) { getfile.simulate('click'); e.preventDefault(); } }, this); var cancel = selectnode.one('.fp-select-cancel'); cancel.on('click', function(e) { e.preventDefault(); this.selectui.hide(); }, this); }, wait: function() { // First check there isn't already an interval in play, and if there is kill it now. if (this.waitinterval != null) { clearInterval(this.waitinterval); } // Prepare the root node we will set content for and the loading template we want to display as a YUI node. var root = this.fpnode.one('.fp-content'); var content = Y.Node.create(M.core_filepicker.templates.loading).addClass('fp-content-hidden').setStyle('opacity', 0); var count = 0; // Initiate an interval, we will have a count which will increment every 100 milliseconds. // Count 0 - the loading icon will have visibility set to hidden (invisible) and have an opacity of 0 (invisible also) // Count 5 - the visiblity will be switched to visible but opacity will still be at 0 (inivisible) // Counts 6 - 15 opacity will be increased by 0.1 making the loading icon visible over the period of a second // Count 16 - The interval will be cancelled. var interval = setInterval(function(){ if (!content || !root.contains(content) || count >= 15) { clearInterval(interval); return true; } if (count == 5) { content.removeClass('fp-content-hidden'); } else if (count > 5) { var opacity = parseFloat(content.getStyle('opacity')); content.setStyle('opacity', opacity + 0.1); } count++; return false; }, 100); // Store the wait interval so that we can check it in the future. this.waitinterval = interval; // Set the content to the loading template. root.setContent(content); }, viewbar_set_enabled: function(mode) { var viewbar = this.fpnode.one('.fp-viewbar') if (viewbar) { if (mode) { viewbar.addClass('enabled').removeClass('disabled'); this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "false"); this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", ""); } else { viewbar.removeClass('enabled').addClass('disabled'); this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "true"); this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "-1"); } } this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked'); var modes = {1:'icons', 2:'tree', 3:'details'}; this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked'); }, viewbar_clicked: function(e) { e.preventDefault(); var viewbar = this.fpnode.one('.fp-viewbar') if (!viewbar || !viewbar.hasClass('disabled')) { if (e.currentTarget.hasClass('fp-vb-tree')) { this.viewmode = 2; } else if (e.currentTarget.hasClass('fp-vb-details')) { this.viewmode = 3; } else { this.viewmode = 1; } this.viewbar_set_enabled(true) this.view_files(); this.set_preference('recentviewmode', this.viewmode); } }, render: function() { var client_id = this.options.client_id; var fpid = "filepicker-"+ client_id; var labelid = 'fp-dialog-label_'+ client_id; var width = 873; var draggable = true; this.fpnode = Y.Node.create(M.core_filepicker.templates.generallayout). set('id', 'filepicker-'+client_id).set('aria-labelledby', labelid); if (this.in_iframe()) { width = Math.floor(window.innerWidth * 0.95); draggable = false; } this.mainui = new M.core.dialogue({ extraClasses : ['filepicker'], draggable : draggable, bodyContent : this.fpnode, headerContent: '<h3 id="'+ labelid +'">'+ M.util.get_string('filepicker', 'repository') +'</h3>', centered : true, modal : true, visible : false, width : width+'px', responsiveWidth : 768, height : '558px', zIndex : this.options.zIndex, focusOnPreviousTargetAfterHide: true, focusAfterHide: this.options.previousActiveElement }); // create panel for selecting a file (initially hidden) this.selectnode = Y.Node.create(M.core_filepicker.templates.selectlayout). set('id', 'filepicker-select-'+client_id). set('aria-live', 'assertive'). set('role', 'dialog'); var fplabel = 'fp-file_label_'+ client_id; this.selectui = new M.core.dialogue({ headerContent: '<h3 id="' + fplabel +'">'+M.util.get_string('select', 'repository')+'</h3>', draggable : true, width : '450px', bodyContent : this.selectnode, centered : true, modal : true, visible : false, zIndex : this.options.zIndex }); Y.one('#'+this.selectnode.get('id')).setAttribute('aria-labelledby', fplabel); // event handler for lazy loading of thumbnails and next page this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this); // save template for one path element and location of path bar if (this.fpnode.one('.fp-path-folder')) { this.pathnode = this.fpnode.one('.fp-path-folder'); this.pathbar = this.pathnode.get('parentNode'); this.pathbar.removeChild(this.pathnode); } // assign callbacks for view mode switch buttons this.fpnode.one('.fp-vb-icons').on('click', this.viewbar_clicked, this); this.fpnode.one('.fp-vb-tree').on('click', this.viewbar_clicked, this); this.fpnode.one('.fp-vb-details').on('click', this.viewbar_clicked, this); // assign callbacks for toolbar links this.setup_toolbar(); this.setup_select_file(); this.hide_header(); // processing repository listing // Resort the repositories by sortorder var sorted_repositories = []; var i; for (i in this.options.repositories) { sorted_repositories[i] = this.options.repositories[i]; } sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder}); // extract one repository template and repeat it for all repositories available, // set name and icon and assign callbacks var reponode = this.fpnode.one('.fp-repo'); if (reponode) { var list = reponode.get('parentNode'); list.removeChild(reponode); for (i in sorted_repositories) { var repository = sorted_repositories[i]; var h = (parseInt(i) == 0) ? parseInt(i) : parseInt(i) - 1, j = (parseInt(i) == Object.keys(sorted_repositories).length - 1) ? parseInt(i) : parseInt(i) + 1; var previousrepository = sorted_repositories[h]; var nextrepository = sorted_repositories[j]; var node = reponode.cloneNode(true); list.appendChild(node); node. set('id', 'fp-repo-'+client_id+'-'+repository.id). on('click', function(e, repository_id) { e.preventDefault(); this.set_preference('recentrepository', repository_id); this.hide_header(); this.list({'repo_id':repository_id}); }, this /*handler running scope*/, repository.id/*second argument of handler*/); node.on('key', function(e, previousrepositoryid, nextrepositoryid, clientid, repositoryid) { this.changeHighlightedRepository(e, clientid, repositoryid, previousrepositoryid, nextrepositoryid); }, 'down:38,40', this, previousrepository.id, nextrepository.id, client_id, repository.id); node.on('key', function(e, repositoryid) { e.preventDefault(); this.set_preference('recentrepository', repositoryid); this.hide_header(); this.list({'repo_id': repositoryid}); }, 'enter', this, repository.id); node.one('.fp-repo-name').setContent(Y.Escape.html(repository.name)); node.one('.fp-repo-icon').set('src', repository.icon); if (i==0) { node.addClass('first'); } if (i==sorted_repositories.length-1) { node.addClass('last'); } if (i%2) { node.addClass('even'); } else { node.addClass('odd'); } } } // display error if no repositories found if (sorted_repositories.length==0) { this.display_error(M.util.get_string('norepositoriesavailable', 'repository'), 'norepositoriesavailable') } // display repository that was used last time this.mainui.show(); this.show_recent_repository(); }, /** * Change the highlighted repository to a new one. * * @param {object} event The key event * @param {integer} clientid The client id to identify the repo class. * @param {integer} oldrepositoryid The repository id that we are removing the highlight for * @param {integer} previousrepositoryid The previous repository id. * @param {integer} nextrepositoryid The next repository id. */ changeHighlightedRepository: function(event, clientid, oldrepositoryid, previousrepositoryid, nextrepositoryid) { event.preventDefault(); var newrepositoryid = (event.keyCode == '40') ? nextrepositoryid : previousrepositoryid; this.fpnode.one('#fp-repo-' + clientid + '-' + oldrepositoryid).setAttribute('tabindex', '-1'); this.fpnode.one('#fp-repo-' + clientid + '-' + newrepositoryid) .setAttribute('tabindex', '0') .focus(); }, parse_repository_options: function(data, appendtolist) { if (appendtolist) { if (data.list) { if (!this.filelist) { this.filelist = []; } for (var i in data.list) { this.filelist[this.filelist.length] = data.list[i]; } } } else { this.filelist = data.list?data.list:null; this.lazyloading = {}; } this.filepath = data.path?data.path:null; this.objecttag = data.object?data.object:null; this.active_repo = {}; this.active_repo.issearchresult = data.issearchresult ? true : false; this.active_repo.defaultreturntype = data.defaultreturntype?data.defaultreturntype:null; this.active_repo.dynload = data.dynload?data.dynload:false; this.active_repo.pages = Number(data.pages?data.pages:null); this.active_repo.page = Number(data.page?data.page:null); this.active_repo.hasmorepages = (this.active_repo.pages && this.active_repo.page && (this.active_repo.page < this.active_repo.pages || this.active_repo.pages == -1)) this.active_repo.id = data.repo_id?data.repo_id:null; this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set this.active_repo.logouttext = data.logouttext?data.logouttext:null; this.active_repo.logouturl = (data.logouturl || ''); this.active_repo.message = (data.message || ''); this.active_repo.help = data.help?data.help:null; this.active_repo.manage = data.manage?data.manage:null; this.print_header(); }, print_login: function(data) { this.parse_repository_options(data); var client_id = this.options.client_id; var repository_id = data.repo_id; var l = this.logindata = data.login; var loginurl = ''; var action = data['login_btn_action'] ? data['login_btn_action'] : 'login'; var form_id = 'fp-form-'+client_id; var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform); loginform_node.one('form').set('id', form_id); this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node); var templates = { 'popup' : loginform_node.one('.fp-login-popup'), 'textarea' : loginform_node.one('.fp-login-textarea'), 'select' : loginform_node.one('.fp-login-select'), 'text' : loginform_node.one('.fp-login-text'), 'radio' : loginform_node.one('.fp-login-radiogroup'), 'checkbox' : loginform_node.one('.fp-login-checkbox'), 'input' : loginform_node.one('.fp-login-input') }; var container; for (var i in templates) { if (templates[i]) { container = templates[i].get('parentNode'); container.removeChild(templates[i]); } } for(var k in l) { if (templates[l[k].type]) { var node = templates[l[k].type].cloneNode(true); } else { node = templates['input'].cloneNode(true); } if (l[k].type == 'popup') { // submit button loginurl = l[k].url; var popupbutton = node.one('button'); popupbutton.on('click', function(e){ M.core_filepicker.active_filepicker = this; window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes'); e.preventDefault(); }, this); loginform_node.one('form').on('keydown', function(e) { if (e.keyCode == 13) { popupbutton.simulate('click'); e.preventDefault(); } }, this); loginform_node.all('.fp-login-submit').remove(); action = 'popup'; } else if(l[k].type=='textarea') { // textarea element if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label); } node.one('textarea').setAttrs({id:l[k].id, name:l[k].name}); } else if(l[k].type=='select') { // select element if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label); } node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent(''); for (i in l[k].options) { node.one('select').appendChild( Y.Node.create('<option/>'). set('value', l[k].options[i].value). setContent(l[k].options[i].label)); } } else if(l[k].type=='radio') { // radio input element node.all('label').setContent(l[k].label); var list = l[k].value.split('|'); var labels = l[k].value_label.split('|'); var radionode = null; for(var item in list) { if (radionode == null) { radionode = node.one('.fp-login-radio'); radionode.one('input').set('checked', 'checked'); } else { var x = radionode.cloneNode(true); radionode.insert(x, 'after'); radionode = x; radionode.one('input').set('checked', ''); } radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name, type:l[k].type, value:list[item]}); radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item) } if (radionode == null) { node.one('.fp-login-radio').remove(); } } else { // input element if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) } node.one('input'). set('type', l[k].type). set('id', l[k].id). set('name', l[k].name). set('value', l[k].value?l[k].value:'') } container.appendChild(node); } // custom label text for submit button if (data['login_btn_label']) { loginform_node.all('.fp-login-submit').setContent(data['login_btn_label']) } // register button action for login and search if (action == 'login' || action == 'search') { loginform_node.one('.fp-login-submit').on('click', function(e){ e.preventDefault(); this.hide_header(); this.request({ 'scope': this, 'action':(action == 'search') ? 'search' : 'signin', 'path': '', 'client_id': client_id, 'repository_id': repository_id, 'form': {id:form_id, upload:false, useDisabled:true}, 'callback': this.display_response }, true); }, this); } // if 'Enter' is pressed in the form, simulate the button click if (loginform_node.one('.fp-login-submit')) { loginform_node.one('form').on('keydown', function(e) { if (e.keyCode == 13) { loginform_node.one('.fp-login-submit').simulate('click') e.preventDefault(); } }, this); } }, display_response: function(id, obj, args) { var scope = args.scope; // highlight the current repository in repositories list scope.fpnode.all('.fp-repo.active') .removeClass('active') .setAttribute('aria-selected', 'false') .setAttribute('tabindex', '-1'); scope.fpnode.all('.nav-link') .removeClass('active') .setAttribute('aria-selected', 'false') .setAttribute('tabindex', '-1'); var activenode = scope.fpnode.one('#fp-repo-' + scope.options.client_id + '-' + obj.repo_id); activenode.addClass('active') .setAttribute('aria-selected', 'true') .setAttribute('tabindex', '0'); activenode.all('.nav-link').addClass('active'); // add class repository_REPTYPE to the filepicker (for repository-specific styles) for (var i in scope.options.repositories) { scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type) } if (obj.repo_id && scope.options.repositories[obj.repo_id]) { scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type) } Y.one('.file-picker .fp-repo-items').focus(); // display response if (obj.login) { scope.viewbar_set_enabled(false); scope.print_login(obj); } else if (obj.upload) { scope.viewbar_set_enabled(false); scope.parse_repository_options(obj); scope.create_upload_form(obj); } else if (obj.object) { M.core_filepicker.active_filepicker = scope; scope.viewbar_set_enabled(false); scope.parse_repository_options(obj); scope.create_object_container(obj.object); } else if (obj.list) { scope.viewbar_set_enabled(true); scope.parse_repository_options(obj); scope.view_files(); } }, list: function(args) { if (!args) { args = {}; } if (!args.repo_id) { args.repo_id = this.active_repo.id; } if (!args.path) { args.path = ''; } this.currentpath = args.path; this.request({ action: 'list', client_id: this.options.client_id, repository_id: args.repo_id, path: args.path, page: args.page, scope: this, callback: this.display_response }, true); }, populateLicensesSelect: function(licensenode, filenode) { if (!licensenode) { return; } licensenode.setContent(''); var selectedlicense = this.options.defaultlicense; if (filenode) { // File has a license already, use it. selectedlicense = filenode.license; } else if (this.options.rememberuserlicensepref && this.get_preference('recentlicense')) { // When 'Remember user licence preference' is enabled use the last license selected by the user, if any. selectedlicense = this.get_preference('recentlicense'); } var licenses = this.options.licenses; for (var i in licenses) { // Include the file's current license, even if not enabled, to prevent displaying // misleading information about which license the file currently has assigned to it. if (licenses[i].enabled == true || (filenode !== undefined && licenses[i].shortname === filenode.license)) { var option = Y.Node.create('<option/>'). set('selected', (licenses[i].shortname == selectedlicense)). set('value', licenses[i].shortname). setContent(Y.Escape.html(licenses[i].fullname)); licensenode.appendChild(option); } } }, create_object_container: function(data) { var content = this.fpnode.one('.fp-content'); content.setContent(''); //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>'; var container = Y.Node.create('<object/>'). setAttrs({data:data.src, type:data.type, id:'container_object'}). addClass('fp-object-container'); content.setContent('').appendChild(container); }, create_upload_form: function(data) { var client_id = this.options.client_id; var id = data.upload.id+'_'+client_id; var content = this.fpnode.one('.fp-content'); var template_name = 'uploadform_'+this.options.repositories[data.repo_id].type; var template = M.core_filepicker.templates[template_name] || M.core_filepicker.templates['uploadform']; content.setContent(template); content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) { node.all('label').set('for', node.one('input,select').generateID()); }); content.one('form').set('id', id); content.one('.fp-file input').set('name', 'repo_upload_file'); if (data.upload.label && content.one('.fp-file label')) { content.one('.fp-file label').setContent(data.upload.label); } content.one('.fp-saveas input').set('name', 'title'); content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author}); content.one('.fp-setlicense select').set('name', 'license'); this.populateLicensesSelect(content.one('.fp-setlicense select')); // append hidden inputs to the upload form content.one('form').appendChild(Y.Node.create('<input/>'). setAttrs({type:'hidden',name:'itemid',value:this.options.itemid})); var types = this.options.accepted_types; for (var i in types) { content.one('form').appendChild(Y.Node.create('<input/>'). setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]})); } var scope = this; content.one('.fp-upload-btn').on('click', function(e) { e.preventDefault(); var license = content.one('.fp-setlicense select'); if (this.options.rememberuserlicensepref) { this.set_preference('recentlicense', license.get('value')); } if (!content.one('.fp-file input').get('value')) { scope.print_msg(M.util.get_string('nofilesattached', 'repository'), 'error'); return false; } this.hide_header(); scope.request({ scope: scope, action:'upload', client_id: client_id, params: {'savepath':scope.options.savepath}, repository_id: scope.active_repo.id, form: {id: id, upload:true}, onerror: function(id, o, args) { scope.create_upload_form(data); }, callback: function(id, o, args) { if (o.event == 'fileexists') { scope.create_upload_form(data); scope.process_existing_file(o); return; } if (scope.options.editor_target&&scope.options.env=='editor') { scope.options.editor_target.value=o.url; scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true}); } scope.hide(); o.client_id = client_id; var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope; scope.options.formcallback.apply(formcallback_scope, [o]); } }, true); }, this); }, /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */ setup_toolbar: function() { var client_id = this.options.client_id; var toolbar = this.fpnode.one('.fp-toolbar'); toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) { e.preventDefault(); if (!this.active_repo.nologin) { this.hide_header(); this.request({ action:'logout', client_id: this.options.client_id, repository_id: this.active_repo.id, path:'', callback: this.display_response }, true); } if (this.active_repo.logouturl) { window.open(this.active_repo.logouturl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes'); } }, this); toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) { e.preventDefault(); if (!this.active_repo.norefresh) { this.list({ path: this.currentpath }); } }, this); toolbar.one('.fp-tb-search form'). set('method', 'POST'). set('id', 'fp-tb-search-'+client_id). on('submit', function(e) { e.preventDefault(); if (!this.active_repo.nosearch) { this.request({ scope: this, action:'search', client_id: this.options.client_id, repository_id: this.active_repo.id, form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true}, callback: this.display_response }, true); } }, this); // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a> // element and use it to open url on click event var managelnk = Y.Node.create('<a/>'). setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}). setStyle('display', 'none'); toolbar.append(managelnk); toolbar.one('.fp-tb-manage').one('a,button'). on('click', function(e) { e.preventDefault(); managelnk.simulate('click') }); // same with .fp-tb-help var helplnk = Y.Node.create('<a/>'). setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}). setStyle('display', 'none'); toolbar.append(helplnk); toolbar.one('.fp-tb-help').one('a,button'). on('click', function(e) { e.preventDefault(); helplnk.simulate('click') }); }, hide_header: function() { if (this.fpnode.one('.fp-toolbar')) { this.fpnode.one('.fp-toolbar').addClass('empty'); } if (this.pathbar) { this.pathbar.setContent('').addClass('empty'); } }, print_header: function() { var r = this.active_repo; var scope = this; var client_id = this.options.client_id; this.hide_header(); this.print_path(); var toolbar = this.fpnode.one('.fp-toolbar'); if (!toolbar) { return; } var enable_tb_control = function(node, enabled) { if (!node) { return; } node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled) if (enabled) { toolbar.removeClass('empty'); } } // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it! enable_tb_control(toolbar.one('.fp-tb-back'), false); // search form enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch); if(!r.nosearch) { var searchform = toolbar.one('.fp-tb-search form'); searchform.setContent(''); this.request({ scope: this, action:'searchform', repository_id: this.active_repo.id, callback: function(id, obj, args) { if (obj.repo_id == scope.active_repo.id && obj.form) { // if we did not jump to another repository meanwhile searchform.setContent(obj.form); // Highlight search text when user click for search. var searchnode = searchform.one('input[name="s"]'); if (searchnode) { searchnode.once('click', function(e) { e.preventDefault(); this.select(); }); } } } }, false); } // refresh button // weather we use cache for this instance, this button will reload listing anyway enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh); // login button enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin); // manage url enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage); Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage); // help url enable_tb_control(toolbar.one('.fp-tb-help'), r.help); Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help); // message enable_tb_control(toolbar.one('.fp-tb-message'), r.message); toolbar.one('.fp-tb-message').setContent(r.message); }, print_path: function() { if (!this.pathbar) { return; } this.pathbar.setContent('').addClass('empty'); var p = this.filepath; if (p && p.length!=0 && this.viewmode != 2) { for(var i = 0; i < p.length; i++) { var el = this.pathnode.cloneNode(true); this.pathbar.appendChild(el); if (i == 0) { el.addClass('first'); } if (i == p.length-1) { el.addClass('last'); } if (i%2) { el.addClass('even'); } else { el.addClass('odd'); } el.all('.fp-path-folder-name').setContent(Y.Escape.html(p[i].name)); el.on('click', function(e, path) { e.preventDefault(); this.list({'path':path}); }, this, p[i].path); } this.pathbar.removeClass('empty'); } }, hide: function() { this.selectui.hide(); if (this.process_dlg) { this.process_dlg.hide(); } if (this.msg_dlg) { this.msg_dlg.hide(); } this.mainui.hide(); }, show: function() { if (this.fpnode) { this.hide(); this.mainui.show(); this.show_recent_repository(); } else { this.launch(); } }, launch: function() { this.render(); }, show_recent_repository: function() { this.hide_header(); this.viewbar_set_enabled(false); var repository_id = this.get_preference('recentrepository'); this.viewmode = this.get_preference('recentviewmode'); if (this.viewmode != 2 && this.viewmode != 3) { this.viewmode = 1; } if (this.options.repositories[repository_id]) { this.list({'repo_id':repository_id}); } }, get_preference: function (name) { if (this.options.userprefs[name]) { return this.options.userprefs[name]; } else { return false; } }, set_preference: function(name, value) { if (this.options.userprefs[name] != value) { M.util.set_user_preference('filepicker_' + name, value); this.options.userprefs[name] = value; } }, in_iframe: function () { // If we're not the top window then we're in an iFrame return window.self !== window.top; } }); var loading = Y.one('#filepicker-loading-'+options.client_id); if (loading) { loading.setStyle('display', 'none'); } M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options); };
bostelm/moodle
repository/filepicker.js
JavaScript
gpl-3.0
102,370
define( ({ redLabel: "r", greenLabel: "g", blueLabel: "b", hueLabel: "n", saturationLabel: "m", valueLabel: "k", /* aka intensity or brightness */ degLabel: "\u00B0", hexLabel: "hex", huePickerTitle: "Nyans", saturationPickerTitle: "Mättnad" }) );
avz-cmf/zaboy-middleware
www/js/dojox/widget/nls/sv/ColorPicker.js
JavaScript
gpl-3.0
249
// NOTE: This method only strips the fragment and is not in accordance to the // recommended draft specification: // https://w3c.github.io/webappsec/specs/referrer-policy/#null // TODO(kristijanburnik): Implement this helper as defined by spec once added // scenarios for URLs containing username/password/etc. function stripUrlForUseAsReferrer(url) { return url.replace(/#.*$/, ""); } function parseUrlQueryString(queryString) { var queries = queryString.replace(/^\?/, "").split("&"); var params = {}; for (var i in queries) { var kvp = queries[i].split("="); params[kvp[0]] = kvp[1]; } return params; }; function appendIframeToBody(url, attributes) { var iframe = document.createElement("iframe"); iframe.src = url; // Extend element with attributes. (E.g. "referrer_policy" or "rel") if (attributes) { for (var attr in attributes) { iframe[attr] = attributes[attr]; } } document.body.appendChild(iframe); return iframe; } function loadImage(src, callback, attributes) { var image = new Image(); image.crossOrigin = "Anonymous"; image.onload = function() { callback(image); } image.src = src; // Extend element with attributes. (E.g. "referrer_policy" or "rel") if (attributes) { for (var attr in attributes) { image[attr] = attributes[attr]; } } document.body.appendChild(image) } function decodeImageData(rgba) { var rgb = new Uint8ClampedArray(rgba.length); // RGBA -> RGB. var rgb_length = 0; for (var i = 0; i < rgba.length; ++i) { // Skip alpha component. if (i % 4 == 3) continue; // Zero is the string terminator. if (rgba[i] == 0) break; rgb[rgb_length++] = rgba[i]; } // Remove trailing nulls from data. rgb = rgb.subarray(0, rgb_length); var string_data = (new TextDecoder("ascii")).decode(rgb); return JSON.parse(string_data); } function decodeImage(url, callback, referrer_policy) { loadImage(url, function(img) { var canvas = document.createElement("canvas"); var context = canvas.getContext('2d'); context.drawImage(img, 0, 0); var imgData = context.getImageData(0, 0, img.clientWidth, img.clientHeight); callback(decodeImageData(imgData.data)) }, referrer_policy); } function normalizePort(targetPort) { var defaultPorts = [80, 443]; var isDefaultPortForProtocol = (defaultPorts.indexOf(targetPort) >= 0); return (targetPort == "" || isDefaultPortForProtocol) ? "" : ":" + targetPort; } function wrapResult(url, server_data) { return { location: url, referrer: server_data.headers.referer, headers: server_data.headers } } function queryIframe(url, callback, referrer_policy) { var iframe = appendIframeToBody(url, referrer_policy); var listener = function(event) { if (event.source != iframe.contentWindow) return; callback(event.data, url); window.removeEventListener("message", listener); } window.addEventListener("message", listener); } function queryImage(url, callback, referrer_policy) { decodeImage(url, function(server_data) { callback(wrapResult(url, server_data), url); }, referrer_policy) } function queryXhr(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.onreadystatechange = function(e) { if (this.readyState == 4 && this.status == 200) { var server_data = JSON.parse(this.responseText); callback(wrapResult(url, server_data), url); } }; xhr.send(); } function queryWorker(url, callback) { var worker = new Worker(url); worker.onmessage = function(event) { var server_data = event.data; callback(wrapResult(url, server_data), url); }; } function queryFetch(url, callback) { fetch(url).then(function(response) { response.json().then(function(server_data) { callback(wrapResult(url, server_data), url); }); } ); } function queryNavigable(element, url, callback, attributes) { var navigable = element navigable.href = url; navigable.target = "helper-iframe"; var helperIframe = document.createElement("iframe") helperIframe.name = "helper-iframe" document.body.appendChild(helperIframe) // Extend element with attributes. (E.g. "referrer_policy" or "rel") if (attributes) { for (var attr in attributes) { navigable[attr] = attributes[attr]; } } var listener = function(event) { if (event.source != helperIframe.contentWindow) return; callback(event.data, url); window.removeEventListener("message", listener); } window.addEventListener("message", listener); navigable.click(); } function queryLink(url, callback, referrer_policy) { var a = document.createElement("a"); a.innerHTML = "Link to subresource"; document.body.appendChild(a); queryNavigable(a, url, callback, referrer_policy) } function queryAreaLink(url, callback, referrer_policy) { var area = document.createElement("area"); // TODO(kristijanburnik): Append to map and add image. document.body.appendChild(area); queryNavigable(area, url, callback, referrer_policy) } function queryScript(url, callback) { var script = document.createElement("script"); script.src = url; var listener = function(event) { var server_data = event.data; callback(wrapResult(url, server_data), url); window.removeEventListener("message", listener); } window.addEventListener("message", listener); document.body.appendChild(script); } // SanityChecker does nothing in release mode. function SanityChecker() {} SanityChecker.prototype.checkScenario = function() {}; SanityChecker.prototype.checkSubresourceResult = function() {}; // TODO(kristijanburnik): document.origin is supported since Chrome 41, // other browsers still don't support it. Remove once they do. document.origin = document.origin || (location.protocol + "//" + location.host);
raviflipsyde/servo
tests/wpt/web-platform-tests/referrer-policy/generic/common.js
JavaScript
mpl-2.0
5,881
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //// PARTICULAR PURPOSE. //// //// Copyright (c) Microsoft Corporation. All rights reserved (function () { "use strict"; var page = WinJS.UI.Pages.define("/html/AdvancedSearch.html", { ready: function (element, options) { document.getElementById("searchFilesUser1").addEventListener("click", AdvancedSearchClicked, false); document.getElementById("searchFilesUser2").addEventListener("click", AdvancedSearchClicked, false); document.getElementById("searchFilesUser3").addEventListener("click", AdvancedSearchClicked, false); document.getElementById("searchFilesUser4").addEventListener("click", AdvancedSearchClicked, false); document.getElementById("searchProgress").style.visibility = "hidden"; initAdvancedSearch(); } }); function AdvancedSearchClicked(sender) { WinJS.log && WinJS.log("", "sample", "status"); document.getElementById("searchProgress").style.visibility = "visible"; var userToSearch = sender.srcElement.innerHTML; var options = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.orderBySearchRank, ["*"]); var outputString = ""; // Try to open the homegroup folder --- wrapped in a try/catch in case something really unexcepted happens, like the user is not joined to a homegroup. try { var hg = Windows.Storage.KnownFolders.homeGroup; hg.getFoldersAsync().done(function (users) { users.forEach(function (user) { if (user.name === userToSearch) { var query = user.createFileQueryWithOptions(options); query.getFilesAsync().done(function (files) { if (files.size === 0) { document.getElementById("searchProgress").style.visibility = "hidden"; outputString = "<b>No files shared by " + userToSearch + "</b>"; } else { document.getElementById("searchProgress").style.visibility = "hidden"; outputString = (files.size === 1) ? (files.size + " file found\n") : (files.size + " files shared by "); outputString = outputString.concat(userToSearch, "\n"); files.forEach(function (file) { outputString = outputString.concat(file.name, "\n"); }); } WinJS.log && WinJS.log(outputString, "sample", "status"); }); } }); }); } catch (e) { document.getElementById("searchProgress").style.visibility = "hidden"; WinJS.log && WinJS.log(e.message, "sample", "errror"); } } // Scenario 4 initialization. Find the homegroup users and their thumbnails and draw them as input options. function initAdvancedSearch() { var idString = ""; // Hide all the buttons until we determine how many users are currently online for (var buttonIndex = 0; buttonIndex < 4; buttonIndex++) { idString = "searchFilesUser" + (buttonIndex + 1); document.getElementById(idString).style.visibility = "hidden"; } try { var hg = Windows.Storage.KnownFolders.homeGroup; // Enumerate the homegroup first-level folders, which represent the homegroup users, and get the thumbnails. hg.getFoldersAsync().done(function (folders) { if (folders) { // Run through all the users and create the buttons for each user. var userCount = (folders.size < 4) ? folders.size : 4; for (var userIndex = 0; userIndex < userCount; userIndex++) { idString = "searchFilesUser" + (userIndex + 1); document.getElementById(idString).innerHTML = folders.getAt(userIndex).name; document.getElementById(idString).style.visibility = "visible"; } } else { id("scenario4Output").innerHTML = "No homegroup users could be found. Make sure you are joined to a homegroup and there is someone sharing"; } }); } catch (e) { WinJS.log && WinJS.log(e.message, "sample", "error"); } } })();
peterpy8/Windows-universal-samples
homegroup/js/js/advancedsearch.js
JavaScript
mit
4,865
// Simplified Chinese lang variables contributed by tom_cat (thomaswangyang@gmail.com) tinyMCE.addToLang('advimage',{ tab_general : 'Ò»°ã', tab_appearance : 'ÏÔʾ', tab_advanced : '¸ß¼¶', general : 'Ò»°ã', title : '±êÌâ', preview : 'Ô¤ÀÀ', constrain_proportions : 'Ô¼ÊøÊôÐÔ', langdir : 'Êéд·½Ïò', langcode : 'ÓïÑÔ±àÂë', long_desc : '³¤ÃèÊöÁ´½Ó', style : '·ç¸ñ', classes : 'Àà', ltr : '´Ó×óÖÁÓÒ', rtl : '´ÓÓÒÖÁ×ó', id : '±íʶ', image_map : 'ͼƬ¶ÔÓ¦', swap_image : 'µ÷»»Í¼Æ¬', alt_image : 'ºòѡͼƬ', mouseover : 'Êó±êÔÚÉÏÃæÊ±', mouseout : 'Êó±êÀ뿪ʱ', misc : 'ÔÓÏî', example_img : 'Appearance&nbsp;preview&nbsp;image', missing_alt : 'ÄúÈ·ÈÏÒªÔÚûÓÐͼƬ˵Ã÷µÄÇé¿öϼÌÐøÂ𣿠ÕâÑùÆäËû¹Ø±ÕͼƬä¯ÀÀµÄÓû§½«ÎÞ·¨×¢Òâµ½ÄãÔÚÕâÀïÓÐͼƬ¡£' });
xavilal/moodle
lib/editor/tinymce/jscripts/tiny_mce/plugins/advimage/langs/zh_cn.js
JavaScript
gpl-3.0
736
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ (function(){CKEDITOR.plugins.add("iframe",{requires:"dialog,fakeobjects",lang:"af,ar,az,bg,bn,bs,ca,cs,cy,da,de,de-ch,el,en,en-au,en-ca,en-gb,eo,es,es-mx,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,oc,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,tt,ug,uk,vi,zh,zh-cn",icons:"iframe",hidpi:!0,onLoad:function(){CKEDITOR.addCss("img.cke_iframe{background-image: url("+CKEDITOR.getUrl(this.path+"images/placeholder.png")+");background-position: center center;background-repeat: no-repeat;border: 1px solid #a9a9a9;width: 80px;height: 80px;}")}, init:function(a){var b=a.lang.iframe,c="iframe[align,longdesc,frameborder,height,name,scrolling,src,title,width]";a.plugins.dialogadvtab&&(c+=";iframe"+a.plugins.dialogadvtab.allowedContent({id:1,classes:1,styles:1}));CKEDITOR.dialog.add("iframe",this.path+"dialogs/iframe.js");a.addCommand("iframe",new CKEDITOR.dialogCommand("iframe",{allowedContent:c,requiredContent:"iframe"}));a.ui.addButton&&a.ui.addButton("Iframe",{label:b.toolbar,command:"iframe",toolbar:"insert,80"});a.on("doubleclick",function(a){var b= a.data.element;b.is("img")&&"iframe"==b.data("cke-real-element-type")&&(a.data.dialog="iframe")});a.addMenuItems&&a.addMenuItems({iframe:{label:b.title,command:"iframe",group:"image"}});a.contextMenu&&a.contextMenu.addListener(function(a){if(a&&a.is("img")&&"iframe"==a.data("cke-real-element-type"))return{iframe:CKEDITOR.TRISTATE_OFF}})},afterInit:function(a){var b=a.dataProcessor;(b=b&&b.dataFilter)&&b.addRules({elements:{iframe:function(b){return a.createFakeParserElement(b,"cke_iframe","iframe", !0)}}})}})})();
gitee2008/glaf
webapps/glaf/static/AdminLTE/bower_components/ckeditor/plugins/iframe/plugin.js
JavaScript
apache-2.0
1,796
//// [paramPropertiesInSignatures.ts] class C1 { constructor(public p1:string); // ERROR constructor(private p2:number); // ERROR constructor(public p3:any) {} // OK } declare class C2 { constructor(public p1:string); // ERROR constructor(private p2:number); // ERROR constructor(public p3:any); // ERROR } //// [paramPropertiesInSignatures.js] var C1 = (function () { function C1(p3) { this.p3 = p3; } // OK return C1; }());
AbubakerB/TypeScript
tests/baselines/reference/paramPropertiesInSignatures.js
JavaScript
apache-2.0
464
'use strict'; /* jshint -W110 */ var Utils = require('../../utils') , DataTypes = require('../../data-types') , AbstractQueryGenerator = require('../abstract/query-generator') , randomBytes = require('crypto').randomBytes , semver = require('semver'); /* istanbul ignore next */ var throwMethodUndefined = function(methodName) { throw new Error('The method "' + methodName + '" is not defined! Please add it to your sql dialect.'); }; var QueryGenerator = { options: {}, dialect: 'mssql', createSchema: function(schema) { return [ 'IF NOT EXISTS (SELECT schema_name', 'FROM information_schema.schemata', 'WHERE schema_name =', wrapSingleQuote(schema), ')', 'BEGIN', "EXEC sp_executesql N'CREATE SCHEMA", this.quoteIdentifier(schema), ";'", 'END;' ].join(' '); }, showSchemasQuery: function() { return [ 'SELECT "name" as "schema_name" FROM sys.schemas as s', 'WHERE "s"."name" NOT IN (', "'INFORMATION_SCHEMA', 'dbo', 'guest', 'sys', 'archive'", ')', 'AND', '"s"."name" NOT LIKE', "'db_%'" ].join(' '); }, versionQuery: function() { // Uses string manipulation to convert the MS Maj.Min.Patch.Build to semver Maj.Min.Patch return [ 'DECLARE @ms_ver NVARCHAR(20);', "SET @ms_ver = REVERSE(CONVERT(NVARCHAR(20), SERVERPROPERTY('ProductVersion')));", "SELECT REVERSE(SUBSTRING(@ms_ver, CHARINDEX('.', @ms_ver)+1, 20)) AS 'version'" ].join(' '); }, createTableQuery: function(tableName, attributes, options) { var query = "IF OBJECT_ID('<%= table %>', 'U') IS NULL CREATE TABLE <%= table %> (<%= attributes %>)" , primaryKeys = [] , foreignKeys = {} , attrStr = [] , self = this; for (var attr in attributes) { if (attributes.hasOwnProperty(attr)) { var dataType = attributes[attr] , match; if (Utils._.includes(dataType, 'PRIMARY KEY')) { primaryKeys.push(attr); if (Utils._.includes(dataType, 'REFERENCES')) { // MSSQL doesn't support inline REFERENCES declarations: move to the end match = dataType.match(/^(.+) (REFERENCES.*)$/); attrStr.push(this.quoteIdentifier(attr) + ' ' + match[1].replace(/PRIMARY KEY/, '')); foreignKeys[attr] = match[2]; } else { attrStr.push(this.quoteIdentifier(attr) + ' ' + dataType.replace(/PRIMARY KEY/, '')); } } else if (Utils._.includes(dataType, 'REFERENCES')) { // MSSQL doesn't support inline REFERENCES declarations: move to the end match = dataType.match(/^(.+) (REFERENCES.*)$/); attrStr.push(this.quoteIdentifier(attr) + ' ' + match[1]); foreignKeys[attr] = match[2]; } else { attrStr.push(this.quoteIdentifier(attr) + ' ' + dataType); } } } var values = { table: this.quoteTable(tableName), attributes: attrStr.join(', '), } , pkString = primaryKeys.map(function(pk) { return this.quoteIdentifier(pk); }.bind(this)).join(', '); if (!!options.uniqueKeys) { Utils._.each(options.uniqueKeys, function(columns, indexName) { if (!Utils._.isString(indexName)) { indexName = 'uniq_' + tableName + '_' + columns.fields.join('_'); } values.attributes += ', CONSTRAINT ' + self.quoteIdentifier(indexName) + ' UNIQUE (' + Utils._.map(columns.fields, self.quoteIdentifier).join(', ') + ')'; }); } if (pkString.length > 0) { values.attributes += ', PRIMARY KEY (' + pkString + ')'; } for (var fkey in foreignKeys) { if (foreignKeys.hasOwnProperty(fkey)) { values.attributes += ', FOREIGN KEY (' + this.quoteIdentifier(fkey) + ') ' + foreignKeys[fkey]; } } return Utils._.template(query)(values).trim() + ';'; }, describeTableQuery: function(tableName, schema) { var sql = [ 'SELECT', "c.COLUMN_NAME AS 'Name',", "c.DATA_TYPE AS 'Type',", "c.CHARACTER_MAXIMUM_LENGTH AS 'Length',", "c.IS_NULLABLE as 'IsNull',", "COLUMN_DEFAULT AS 'Default',", "tc.CONSTRAINT_TYPE AS 'Constraint'", 'FROM', 'INFORMATION_SCHEMA.TABLES t', 'INNER JOIN', 'INFORMATION_SCHEMA.COLUMNS c ON t.TABLE_NAME = c.TABLE_NAME AND t.TABLE_SCHEMA = c.TABLE_SCHEMA', 'LEFT JOIN', 'INFORMATION_SCHEMA.KEY_COLUMN_USAGE cu ON t.TABLE_NAME = cu.TABLE_NAME AND cu.COLUMN_NAME = c.COLUMN_NAME AND t.TABLE_SCHEMA = cu.TABLE_SCHEMA', 'LEFT JOIN', 'INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc ON t.TABLE_NAME = tc.TABLE_NAME AND cu.COLUMN_NAME = c.COLUMN_NAME AND tc.CONSTRAINT_TYPE = \'PRIMARY KEY\'', 'WHERE t.TABLE_NAME =', wrapSingleQuote(tableName) ].join(' '); if (schema) { sql += 'AND t.TABLE_SCHEMA =' + wrapSingleQuote(schema); } return sql; }, renameTableQuery: function(before, after) { var query = 'EXEC sp_rename <%= before %>, <%= after %>;'; return Utils._.template(query)({ before: this.quoteTable(before), after: this.quoteTable(after) }); }, showTablesQuery: function () { return 'SELECT TABLE_NAME, TABLE_SCHEMA FROM INFORMATION_SCHEMA.TABLES;'; }, dropTableQuery: function(tableName) { var query = "IF OBJECT_ID('<%= table %>', 'U') IS NOT NULL DROP TABLE <%= table %>"; var values = { table: this.quoteTable(tableName) }; return Utils._.template(query)(values).trim() + ';'; }, addColumnQuery: function(table, key, dataType) { // FIXME: attributeToSQL SHOULD be using attributes in addColumnQuery // but instead we need to pass the key along as the field here dataType.field = key; var query = 'ALTER TABLE <%= table %> ADD <%= attribute %>;' , attribute = Utils._.template('<%= key %> <%= definition %>')({ key: this.quoteIdentifier(key), definition: this.attributeToSQL(dataType, { context: 'addColumn' }) }); return Utils._.template(query)({ table: this.quoteTable(table), attribute: attribute }); }, removeColumnQuery: function(tableName, attributeName) { var query = 'ALTER TABLE <%= tableName %> DROP COLUMN <%= attributeName %>;'; return Utils._.template(query)({ tableName: this.quoteTable(tableName), attributeName: this.quoteIdentifier(attributeName) }); }, changeColumnQuery: function(tableName, attributes) { var query = 'ALTER TABLE <%= tableName %> <%= query %>;'; var attrString = [], constraintString = []; for (var attributeName in attributes) { var definition = attributes[attributeName]; if (definition.match(/REFERENCES/)) { constraintString.push(Utils._.template('<%= fkName %> FOREIGN KEY (<%= attrName %>) <%= definition %>')({ fkName: this.quoteIdentifier(attributeName + '_foreign_idx'), attrName: this.quoteIdentifier(attributeName), definition: definition.replace(/.+?(?=REFERENCES)/,'') })); } else { attrString.push(Utils._.template('<%= attrName %> <%= definition %>')({ attrName: this.quoteIdentifier(attributeName), definition: definition })); } } var finalQuery = ''; if (attrString.length) { finalQuery += 'ALTER COLUMN ' + attrString.join(', '); finalQuery += constraintString.length ? ' ' : ''; } if (constraintString.length) { finalQuery += 'ADD CONSTRAINT ' + constraintString.join(', '); } return Utils._.template(query)({ tableName: this.quoteTable(tableName), query: finalQuery }); }, renameColumnQuery: function(tableName, attrBefore, attributes) { var query = "EXEC sp_rename '<%= tableName %>.<%= before %>', '<%= after %>', 'COLUMN';" , newName = Object.keys(attributes)[0]; return Utils._.template(query)({ tableName: this.quoteTable(tableName), before: attrBefore, after: newName }); }, bulkInsertQuery: function(tableName, attrValueHashes, options, attributes) { options = options || {}; attributes = attributes || {}; var query = 'INSERT INTO <%= table %> (<%= attributes %>)<%= output %> VALUES <%= tuples %>;' , emptyQuery = 'INSERT INTO <%= table %><%= output %> DEFAULT VALUES' , tuples = [] , allAttributes = [] , needIdentityInsertWrapper = false , allQueries = [] , outputFragment; if (options.returning) { outputFragment = ' OUTPUT INSERTED.*'; } Utils._.forEach(attrValueHashes, function(attrValueHash) { // special case for empty objects with primary keys var fields = Object.keys(attrValueHash); var firstAttr = attributes[fields[0]]; if (fields.length === 1 && firstAttr && firstAttr.autoIncrement && attrValueHash[fields[0]] === null) { allQueries.push(emptyQuery); return; } // normal case Utils._.forOwn(attrValueHash, function(value, key) { if (value !== null && attributes[key] && attributes[key].autoIncrement) { needIdentityInsertWrapper = true; } if (allAttributes.indexOf(key) === -1) { if (value === null && attributes[key].autoIncrement) return; allAttributes.push(key); } }); }); if (allAttributes.length > 0) { Utils._.forEach(attrValueHashes, function(attrValueHash) { tuples.push('(' + allAttributes.map(function(key) { return this.escape(attrValueHash[key]); }.bind(this)).join(',') + ')'); }.bind(this)); allQueries.push(query); } var replacements = { table: this.quoteTable(tableName), attributes: allAttributes.map(function(attr) { return this.quoteIdentifier(attr); }.bind(this)).join(','), tuples: tuples, output: outputFragment }; var generatedQuery = Utils._.template(allQueries.join(';'))(replacements); if (needIdentityInsertWrapper) { generatedQuery = [ 'SET IDENTITY_INSERT', this.quoteTable(tableName), 'ON;', generatedQuery, 'SET IDENTITY_INSERT', this.quoteTable(tableName), 'OFF;', ].join(' '); } return generatedQuery; }, upsertQuery: function(tableName, insertValues, updateValues, where, rawAttributes, options) { var query = 'MERGE INTO <%= tableNameQuoted %> WITH(HOLDLOCK) AS <%= targetTableAlias %> USING (<%= sourceTableQuery %>) AS <%= sourceTableAlias%>(<%=insertKeysQuoted%>) ON <%= joinCondition %>'; query += ' WHEN MATCHED THEN UPDATE SET <%= updateSnippet %> WHEN NOT MATCHED THEN INSERT <%= insertSnippet %> OUTPUT $action, INSERTED.*;'; var targetTableAlias = this.quoteTable(tableName + '_target') , sourceTableAlias = this.quoteTable(tableName + '_source') , primaryKeysAttrs = [] , identityAttrs = [] , uniqueAttrs = [] , tableNameQuoted = this.quoteTable(tableName) , joinCondition , needIdentityInsertWrapper = false; //Obtain primaryKeys, uniquekeys and identity attrs from rawAttributes as model is not passed for (var key in rawAttributes) { if (rawAttributes[key].primaryKey) { primaryKeysAttrs.push(rawAttributes[key].field || key); } if (rawAttributes[key].unique) { uniqueAttrs.push(rawAttributes[key].field || key); } if (rawAttributes[key].autoIncrement) { identityAttrs.push(rawAttributes[key].field || key); } } var updateKeys = Object.keys(updateValues) , insertKeys = Object.keys(insertValues); var insertKeysQuoted = Utils._.map(insertKeys, function(key) { return this.quoteIdentifier(key); }.bind(this)).join(', '); var insertValuesEscaped = Utils._.map(insertKeys, function(key) { return this.escape(insertValues[key]); }.bind(this)).join(', '); var sourceTableQuery = 'VALUES(' + insertValuesEscaped + ')'; //Virtual Table //IDENTITY_INSERT Condition identityAttrs.forEach(function(key) { if (updateValues[key] && updateValues[key] !== null) { needIdentityInsertWrapper = true; /* * IDENTITY_INSERT Column Cannot be updated, only inserted * http://stackoverflow.com/a/30176254/2254360 */ } }); //Filter NULL Clauses var clauses = where.$or.filter(function(clause) { var valid = true; /* * Exclude NULL Composite PK/UK. Partial Composite clauses should also be excluded as it doesn't guarantee a single row */ for (var key in clause) { if (!clause[key]) { valid = false; break; } } return valid; }); /* * Generate ON condition using PK(s). * If not, generate using UK(s). Else throw error */ var getJoinSnippet = function(array) { return Utils._.map(array, function(key) { key = this.quoteIdentifier(key); return targetTableAlias + '.' + key + ' = ' + sourceTableAlias + '.' + key; }.bind(this)); }; if (clauses.length === 0) { throw new Error('Primary Key or Unique key should be passed to upsert query'); } else { // Search for primary key attribute in clauses -- Model can have two separate unique keys for (key in clauses) { var keys = Object.keys(clauses[key]); if (primaryKeysAttrs.indexOf(keys[0]) !== -1) { joinCondition = getJoinSnippet.bind(this)(primaryKeysAttrs).join(' AND '); break; } } if (!joinCondition) { joinCondition = getJoinSnippet.bind(this)(uniqueAttrs).join(' AND '); } } // Remove the IDENTITY_INSERT Column from update var updateSnippet = updateKeys.filter(function(key) { if (identityAttrs.indexOf(key) === -1) { return true; } else { return false; } }); updateSnippet = Utils._.map(updateSnippet, function(key) { var value = this.escape(updateValues[key]); key = this.quoteIdentifier(key); return targetTableAlias + '.' + key + ' = ' + value; }.bind(this)).join(', '); var insertSnippet = '(' + insertKeysQuoted + ') VALUES(' + insertValuesEscaped + ')'; var replacements = { tableNameQuoted: tableNameQuoted, targetTableAlias: targetTableAlias, sourceTableQuery: sourceTableQuery, sourceTableAlias: sourceTableAlias, insertKeysQuoted: insertKeysQuoted, joinCondition: joinCondition, updateSnippet: updateSnippet, insertSnippet: insertSnippet }; query = Utils._.template(query)(replacements); if (needIdentityInsertWrapper) { query = [ 'SET IDENTITY_INSERT', this.quoteTable(tableName), 'ON;', query, 'SET IDENTITY_INSERT', this.quoteTable(tableName), 'OFF;', ].join(' '); } return query; }, deleteQuery: function(tableName, where, options) { options = options || {}; var table = this.quoteTable(tableName); if (options.truncate === true) { // Truncate does not allow LIMIT and WHERE return 'TRUNCATE TABLE ' + table; } where = this.getWhereConditions(where); var limit = '' , query = 'DELETE<%= limit %> FROM <%= table %><%= where %>; ' + 'SELECT @@ROWCOUNT AS AFFECTEDROWS;'; if (Utils._.isUndefined(options.limit)) { options.limit = 1; } if (!!options.limit) { limit = ' TOP(' + this.escape(options.limit) + ')'; } var replacements = { limit: limit, table: table, where: where, }; if (replacements.where) { replacements.where = ' WHERE ' + replacements.where; } return Utils._.template(query)(replacements); }, showIndexesQuery: function(tableName) { var sql = "EXEC sys.sp_helpindex @objname = N'<%= tableName %>';"; return Utils._.template(sql)({ tableName: this.quoteTable(tableName) }); }, removeIndexQuery: function(tableName, indexNameOrAttributes) { var sql = 'DROP INDEX <%= indexName %> ON <%= tableName %>' , indexName = indexNameOrAttributes; if (typeof indexName !== 'string') { indexName = Utils.inflection.underscore(tableName + '_' + indexNameOrAttributes.join('_')); } var values = { tableName: this.quoteIdentifiers(tableName), indexName: indexName }; return Utils._.template(sql)(values); }, attributeToSQL: function(attribute) { if (!Utils._.isPlainObject(attribute)) { attribute = { type: attribute }; } // handle self referential constraints if (attribute.references) { attribute = Utils.formatReferences(attribute); if (attribute.Model && attribute.Model.tableName === attribute.references.model) { this.sequelize.log('MSSQL does not support self referencial constraints, ' + 'we will remove it but we recommend restructuring your query'); attribute.onDelete = ''; attribute.onUpdate = ''; } } var template; if (attribute.type instanceof DataTypes.ENUM) { if (attribute.type.values && !attribute.values) attribute.values = attribute.type.values; // enums are a special case template = attribute.type.toSql(); template += ' CHECK (' + attribute.field + ' IN(' + Utils._.map(attribute.values, function(value) { return this.escape(value); }.bind(this)).join(', ') + '))'; return template; } else { template = attribute.type.toString(); } if (attribute.allowNull === false) { template += ' NOT NULL'; } else if (!attribute.primaryKey && !Utils.defaultValueSchemable(attribute.defaultValue)) { template += ' NULL'; } if (attribute.autoIncrement) { template += ' IDENTITY(1,1)'; } // Blobs/texts cannot have a defaultValue if (attribute.type !== 'TEXT' && attribute.type._binary !== true && Utils.defaultValueSchemable(attribute.defaultValue)) { template += ' DEFAULT ' + this.escape(attribute.defaultValue); } if (attribute.unique === true) { template += ' UNIQUE'; } if (attribute.primaryKey) { template += ' PRIMARY KEY'; } if (attribute.references) { template += ' REFERENCES ' + this.quoteTable(attribute.references.model); if (attribute.references.key) { template += ' (' + this.quoteIdentifier(attribute.references.key) + ')'; } else { template += ' (' + this.quoteIdentifier('id') + ')'; } if (attribute.onDelete) { template += ' ON DELETE ' + attribute.onDelete.toUpperCase(); } if (attribute.onUpdate) { template += ' ON UPDATE ' + attribute.onUpdate.toUpperCase(); } } return template; }, attributesToSQL: function(attributes, options) { var result = {} , key , attribute , existingConstraints = []; for (key in attributes) { attribute = attributes[key]; if (attribute.references) { attribute = Utils.formatReferences(attributes[key]); if (existingConstraints.indexOf(attribute.references.model.toString()) !== -1) { // no cascading constraints to a table more than once attribute.onDelete = ''; attribute.onUpdate = ''; } else { existingConstraints.push(attribute.references.model.toString()); // NOTE: this really just disables cascading updates for all // definitions. Can be made more robust to support the // few cases where MSSQL actually supports them attribute.onUpdate = ''; } } if (key && !attribute.field) attribute.field = key; result[attribute.field || key] = this.attributeToSQL(attribute, options); } return result; }, findAutoIncrementField: function(factory) { var fields = []; for (var name in factory.attributes) { if (factory.attributes.hasOwnProperty(name)) { var definition = factory.attributes[name]; if (definition && definition.autoIncrement) { fields.push(name); } } } return fields; }, createTrigger: function() { throwMethodUndefined('createTrigger'); }, dropTrigger: function() { throwMethodUndefined('dropTrigger'); }, renameTrigger: function() { throwMethodUndefined('renameTrigger'); }, createFunction: function() { throwMethodUndefined('createFunction'); }, dropFunction: function() { throwMethodUndefined('dropFunction'); }, renameFunction: function() { throwMethodUndefined('renameFunction'); }, quoteIdentifier: function(identifier, force) { if (identifier === '*') return identifier; return '[' + identifier.replace(/[\[\]']+/g,'') + ']'; }, getForeignKeysQuery: function(table) { var tableName = table.tableName || table; var sql = [ 'SELECT', 'constraint_name = C.CONSTRAINT_NAME', 'FROM', 'INFORMATION_SCHEMA.TABLE_CONSTRAINTS C', "WHERE C.CONSTRAINT_TYPE = 'FOREIGN KEY'", 'AND C.TABLE_NAME =', wrapSingleQuote(tableName) ].join(' '); if (table.schema) { sql += ' AND C.TABLE_SCHEMA =' + wrapSingleQuote(table.schema); } return sql; }, getForeignKeyQuery: function(table, attributeName) { var tableName = table.tableName || table; var sql = [ 'SELECT', 'constraint_name = TC.CONSTRAINT_NAME', 'FROM', 'INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC', 'JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CCU', 'ON TC.CONSTRAINT_NAME = CCU.CONSTRAINT_NAME', "WHERE TC.CONSTRAINT_TYPE = 'FOREIGN KEY'", 'AND TC.TABLE_NAME =', wrapSingleQuote(tableName), 'AND CCU.COLUMN_NAME =', wrapSingleQuote(attributeName), ].join(' '); if (table.schema) { sql += ' AND TC.TABLE_SCHEMA =' + wrapSingleQuote(table.schema); } return sql; }, getPrimaryKeyConstraintQuery: function(table, attributeName) { var tableName = wrapSingleQuote(table.tableName || table); return [ 'SELECT K.TABLE_NAME AS tableName,', 'K.COLUMN_NAME AS columnName,', 'K.CONSTRAINT_NAME AS constraintName', 'FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C', 'JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K', 'ON C.TABLE_NAME = K.TABLE_NAME', 'AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG', 'AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA', 'AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME', 'WHERE C.CONSTRAINT_TYPE = \'PRIMARY KEY\'', 'AND K.COLUMN_NAME =', wrapSingleQuote(attributeName), 'AND K.TABLE_NAME =', tableName + ';', ].join(' '); }, dropForeignKeyQuery: function(tableName, foreignKey) { return Utils._.template('ALTER TABLE <%= table %> DROP <%= key %>')({ table: this.quoteTable(tableName), key: this.quoteIdentifier(foreignKey) }); }, getDefaultConstraintQuery: function (tableName, attributeName) { var sql = "SELECT name FROM SYS.DEFAULT_CONSTRAINTS " + "WHERE PARENT_OBJECT_ID = OBJECT_ID('<%= table %>', 'U') " + "AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns WHERE NAME = ('<%= column %>') " + "AND object_id = OBJECT_ID('<%= table %>', 'U'));"; return Utils._.template(sql)({ table: this.quoteTable(tableName), column: attributeName }); }, dropConstraintQuery: function (tableName, constraintName) { var sql = 'ALTER TABLE <%= table %> DROP CONSTRAINT <%= constraint %>;'; return Utils._.template(sql)({ table: this.quoteTable(tableName), constraint: this.quoteIdentifier(constraintName) }); }, setAutocommitQuery: function(value) { return ''; // return 'SET IMPLICIT_TRANSACTIONS ' + (!!value ? 'OFF' : 'ON') + ';'; }, setIsolationLevelQuery: function(value, options) { if (options.parent) { return; } return 'SET TRANSACTION ISOLATION LEVEL ' + value + ';'; }, generateTransactionId: function () { return randomBytes(10).toString('hex'); }, startTransactionQuery: function(transaction, options) { if (transaction.parent) { return 'SAVE TRANSACTION ' + this.quoteIdentifier(transaction.name) + ';'; } return 'BEGIN TRANSACTION;'; }, commitTransactionQuery: function(transaction) { if (transaction.parent) { return; } return 'COMMIT TRANSACTION;'; }, rollbackTransactionQuery: function(transaction, options) { if (transaction.parent) { return 'ROLLBACK TRANSACTION ' + this.quoteIdentifier(transaction.name) + ';'; } return 'ROLLBACK TRANSACTION;'; }, selectFromTableFragment: function(options, model, attributes, tables, mainTableAs, where) { var topFragment = ''; var mainFragment = 'SELECT ' + attributes.join(', ') + ' FROM ' + tables; // Handle SQL Server 2008 with TOP instead of LIMIT if (semver.valid(this.sequelize.options.databaseVersion) && semver.lt(this.sequelize.options.databaseVersion, '11.0.0')) { if (options.limit) { topFragment = 'TOP ' + options.limit + ' '; } if (options.offset) { var offset = options.offset || 0 , isSubQuery = options.hasIncludeWhere || options.hasIncludeRequired || options.hasMultiAssociation , orders = { mainQueryOrder: [] }; if (options.order) { orders = this.getQueryOrders(options, model, isSubQuery); } if(!orders.mainQueryOrder.length) { orders.mainQueryOrder.push(this.quoteIdentifier(model.primaryKeyField)); } var tmpTable = (mainTableAs) ? mainTableAs : 'OffsetTable'; var whereFragment = (where) ? ' WHERE ' + where : ''; /* * For earlier versions of SQL server, we need to nest several queries * in order to emulate the OFFSET behavior. * * 1. The outermost query selects all items from the inner query block. * This is due to a limitation in SQL server with the use of computed * columns (e.g. SELECT ROW_NUMBER()...AS x) in WHERE clauses. * 2. The next query handles the LIMIT and OFFSET behavior by getting * the TOP N rows of the query where the row number is > OFFSET * 3. The innermost query is the actual set we want information from */ var fragment = 'SELECT TOP 100 PERCENT ' + attributes.join(', ') + ' FROM ' + '(SELECT ' + topFragment + '*' + ' FROM (SELECT ROW_NUMBER() OVER (ORDER BY ' + orders.mainQueryOrder.join(', ') + ') as row_num, * ' + ' FROM ' + tables + ' AS ' + tmpTable + whereFragment + ')' + ' AS ' + tmpTable + ' WHERE row_num > ' + offset + ')' + ' AS ' + tmpTable; return fragment; } else { mainFragment = 'SELECT ' + topFragment + attributes.join(', ') + ' FROM ' + tables; } } if(mainTableAs) { mainFragment += ' AS ' + mainTableAs; } return mainFragment; }, addLimitAndOffset: function(options, model) { // Skip handling of limit and offset as postfixes for older SQL Server versions if(semver.valid(this.sequelize.options.databaseVersion) && semver.lt(this.sequelize.options.databaseVersion, '11.0.0')) { return ''; } var fragment = ''; var offset = options.offset || 0 , isSubQuery = options.hasIncludeWhere || options.hasIncludeRequired || options.hasMultiAssociation; var orders = {}; if (options.order) { orders = this.getQueryOrders(options, model, isSubQuery); } if (options.limit || options.offset) { if (!options.order || (options.include && !orders.subQueryOrder.length)) { fragment += (options.order && !isSubQuery) ? ', ' : ' ORDER BY '; fragment += this.quoteIdentifier(model.primaryKeyField); } if (options.offset || options.limit) { fragment += ' OFFSET ' + this.escape(offset) + ' ROWS'; } if (options.limit) { fragment += ' FETCH NEXT ' + this.escape(options.limit) + ' ROWS ONLY'; } } return fragment; }, booleanValue: function(value) { return !!value ? 1 : 0; } }; // private methods function wrapSingleQuote(identifier){ return Utils.addTicks(identifier, "'"); } module.exports = Utils._.extend(Utils._.clone(AbstractQueryGenerator), QueryGenerator);
Nasen/feedbackServer
start/node_modules/sequelize/lib/dialects/mssql/query-generator.js
JavaScript
apache-2.0
28,634
Package.describe({ summary: "Weibo OAuth flow", version: '1.1.3' }); Package.onUse(function(api) { api.use('oauth2', ['client', 'server']); api.use('oauth', ['client', 'server']); api.use('http', ['server']); api.use('templating', 'client'); api.use('random', 'client'); api.use('service-configuration', ['client', 'server']); api.export('Weibo'); api.addFiles( ['weibo_configure.html', 'weibo_configure.js'], 'client'); api.addFiles('weibo_server.js', 'server'); api.addFiles('weibo_client.js', 'client'); });
TribeMedia/meteor
packages/weibo/package.js
JavaScript
mit
547
/** * @license * Copyright 2014 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var ts = require("typescript"); var Lint = require("../index"); var utils_1 = require("../language/utils"); var ALLOW_FAST_NULL_CHECKS = "allow-fast-null-checks"; var Rule = (function (_super) { __extends(Rule, _super); function Rule() { return _super !== null && _super.apply(this, arguments) || this; } Rule.prototype.apply = function (sourceFile) { return this.applyWithWalker(new NoUnusedExpressionWalker(sourceFile, this.getOptions())); }; return Rule; }(Lint.Rules.AbstractRule)); /* tslint:disable:object-literal-sort-keys */ Rule.metadata = { ruleName: "no-unused-expression", description: "Disallows unused expression statements.", descriptionDetails: (_a = ["\n Unused expressions are expression statements which are not assignments or function calls\n (and thus usually no-ops)."], _a.raw = ["\n Unused expressions are expression statements which are not assignments or function calls\n (and thus usually no-ops)."], Lint.Utils.dedent(_a)), rationale: (_b = ["\n Detects potential errors where an assignment or function call was intended."], _b.raw = ["\n Detects potential errors where an assignment or function call was intended."], Lint.Utils.dedent(_b)), optionsDescription: (_c = ["\n One argument may be optionally provided:\n\n * `", "` allows to use logical operators to perform fast null checks and perform\n method or function calls for side effects (e.g. `e && e.preventDefault()`)."], _c.raw = ["\n One argument may be optionally provided:\n\n * \\`", "\\` allows to use logical operators to perform fast null checks and perform\n method or function calls for side effects (e.g. \\`e && e.preventDefault()\\`)."], Lint.Utils.dedent(_c, ALLOW_FAST_NULL_CHECKS)), options: { type: "array", items: { type: "string", enum: [ALLOW_FAST_NULL_CHECKS], }, minLength: 0, maxLength: 1, }, optionExamples: ["true", "[true, \"" + ALLOW_FAST_NULL_CHECKS + "\"]"], type: "functionality", typescriptOnly: false, }; /* tslint:enable:object-literal-sort-keys */ Rule.FAILURE_STRING = "expected an assignment or function call"; exports.Rule = Rule; var NoUnusedExpressionWalker = (function (_super) { __extends(NoUnusedExpressionWalker, _super); function NoUnusedExpressionWalker(sourceFile, options) { var _this = _super.call(this, sourceFile, options) || this; _this.expressionIsUnused = true; return _this; } NoUnusedExpressionWalker.isDirective = function (node, checkPreviousSiblings) { if (checkPreviousSiblings === void 0) { checkPreviousSiblings = true; } var parent = node.parent; if (parent === undefined) { return true; } var grandParentKind = parent.parent == null ? null : parent.parent.kind; var isStringExpression = node.kind === ts.SyntaxKind.ExpressionStatement && node.expression.kind === ts.SyntaxKind.StringLiteral; var parentIsSourceFile = parent.kind === ts.SyntaxKind.SourceFile; var parentIsNSBody = parent.kind === ts.SyntaxKind.ModuleBlock; var parentIsFunctionBody = grandParentKind !== null && parent.kind === ts.SyntaxKind.Block && [ ts.SyntaxKind.ArrowFunction, ts.SyntaxKind.FunctionExpression, ts.SyntaxKind.FunctionDeclaration, ts.SyntaxKind.MethodDeclaration, ts.SyntaxKind.Constructor, ts.SyntaxKind.GetAccessor, ts.SyntaxKind.SetAccessor, ].indexOf(grandParentKind) > -1; if (!(parentIsSourceFile || parentIsFunctionBody || parentIsNSBody) || !isStringExpression) { return false; } if (checkPreviousSiblings) { var siblings_1 = []; ts.forEachChild(parent, function (child) { siblings_1.push(child); }); return siblings_1.slice(0, siblings_1.indexOf(node)).every(function (n) { return NoUnusedExpressionWalker.isDirective(n, false); }); } else { return true; } }; NoUnusedExpressionWalker.prototype.visitExpressionStatement = function (node) { this.expressionIsUnused = true; _super.prototype.visitExpressionStatement.call(this, node); this.checkExpressionUsage(node); }; NoUnusedExpressionWalker.prototype.visitBinaryExpression = function (node) { _super.prototype.visitBinaryExpression.call(this, node); switch (node.operatorToken.kind) { case ts.SyntaxKind.EqualsToken: case ts.SyntaxKind.PlusEqualsToken: case ts.SyntaxKind.MinusEqualsToken: case ts.SyntaxKind.AsteriskEqualsToken: case ts.SyntaxKind.SlashEqualsToken: case ts.SyntaxKind.PercentEqualsToken: case ts.SyntaxKind.AmpersandEqualsToken: case ts.SyntaxKind.CaretEqualsToken: case ts.SyntaxKind.BarEqualsToken: case ts.SyntaxKind.LessThanLessThanEqualsToken: case ts.SyntaxKind.GreaterThanGreaterThanEqualsToken: case ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: this.expressionIsUnused = false; break; case ts.SyntaxKind.AmpersandAmpersandToken: case ts.SyntaxKind.BarBarToken: if (this.hasOption(ALLOW_FAST_NULL_CHECKS) && isTopLevelExpression(node)) { this.expressionIsUnused = !hasCallExpression(node.right); break; } else { this.expressionIsUnused = true; break; } default: this.expressionIsUnused = true; } }; NoUnusedExpressionWalker.prototype.visitPrefixUnaryExpression = function (node) { _super.prototype.visitPrefixUnaryExpression.call(this, node); switch (node.operator) { case ts.SyntaxKind.PlusPlusToken: case ts.SyntaxKind.MinusMinusToken: this.expressionIsUnused = false; break; default: this.expressionIsUnused = true; } }; NoUnusedExpressionWalker.prototype.visitPostfixUnaryExpression = function (node) { _super.prototype.visitPostfixUnaryExpression.call(this, node); this.expressionIsUnused = false; // the only kinds of postfix expressions are postincrement and postdecrement }; NoUnusedExpressionWalker.prototype.visitBlock = function (node) { _super.prototype.visitBlock.call(this, node); this.expressionIsUnused = true; }; NoUnusedExpressionWalker.prototype.visitArrowFunction = function (node) { _super.prototype.visitArrowFunction.call(this, node); this.expressionIsUnused = true; }; NoUnusedExpressionWalker.prototype.visitCallExpression = function (node) { _super.prototype.visitCallExpression.call(this, node); this.expressionIsUnused = false; }; NoUnusedExpressionWalker.prototype.visitNewExpression = function (node) { _super.prototype.visitNewExpression.call(this, node); this.expressionIsUnused = false; }; NoUnusedExpressionWalker.prototype.visitConditionalExpression = function (node) { this.visitNode(node.condition); this.expressionIsUnused = true; this.visitNode(node.whenTrue); var firstExpressionIsUnused = this.expressionIsUnused; this.expressionIsUnused = true; this.visitNode(node.whenFalse); var secondExpressionIsUnused = this.expressionIsUnused; // if either expression is unused, then that expression's branch is a no-op unless it's // being assigned to something or passed to a function, so consider the entire expression unused this.expressionIsUnused = firstExpressionIsUnused || secondExpressionIsUnused; }; NoUnusedExpressionWalker.prototype.checkExpressionUsage = function (node) { if (this.expressionIsUnused) { var expression = node.expression; var kind = expression.kind; var isValidStandaloneExpression = kind === ts.SyntaxKind.DeleteExpression || kind === ts.SyntaxKind.YieldExpression || kind === ts.SyntaxKind.AwaitExpression; if (!isValidStandaloneExpression && !NoUnusedExpressionWalker.isDirective(node)) { this.addFailureAtNode(node, Rule.FAILURE_STRING); } } }; return NoUnusedExpressionWalker; }(Lint.RuleWalker)); exports.NoUnusedExpressionWalker = NoUnusedExpressionWalker; function hasCallExpression(node) { var nodeToCheck = utils_1.unwrapParentheses(node); if (nodeToCheck.kind === ts.SyntaxKind.CallExpression) { return true; } if (nodeToCheck.kind === ts.SyntaxKind.BinaryExpression) { var operatorToken = nodeToCheck.operatorToken; if (operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken || operatorToken.kind === ts.SyntaxKind.BarBarToken) { return hasCallExpression(nodeToCheck.right); } } return false; } function isTopLevelExpression(node) { var nodeToCheck = node.parent; while (nodeToCheck.kind === ts.SyntaxKind.ParenthesizedExpression) { nodeToCheck = nodeToCheck.parent; } return nodeToCheck.kind === ts.SyntaxKind.ExpressionStatement; } var _a, _b, _c;
mo-norant/FinHeartBel
website/node_modules/tslint/lib/rules/noUnusedExpressionRule.js
JavaScript
gpl-3.0
10,775
/*! Summernote v0.8.4 | (c) 2013- Alan Hong and other contributors | MIT license */ !function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof module&&module.exports?module.exports=a(require("jquery")):a(window.jQuery)}(function(a){a.extend(a.summernote.plugins,{hello:function(b){var c=this,d=a.summernote.ui;b.memo("button.hello",function(){return d.button({contents:'<i class="fa fa-child"/> Hello',tooltip:"hello",click:function(){c.$panel.show(),c.$panel.hide(500),b.invoke("editor.insertText","hello")}}).render()}),this.events={"summernote.init":function(a,b){console.log("summernote initialized",a,b)},"summernote.keyup":function(a,b){console.log("summernote keyup",a,b)}},this.initialize=function(){this.$panel=a('<div class="hello-panel"/>').css({position:"absolute",width:100,height:100,left:"50%",top:"50%",background:"red"}).hide(),this.$panel.appendTo("body")},this.destroy=function(){this.$panel.remove(),this.$panel=null}}})});
vicnroll/GTI
vistas/js/summernote/plugin/hello/summernote-ext-hello.min.js
JavaScript
mit
974
YUI.add('series-bar', function (Y, NAME) { /** * Provides functionality for creating a bar series. * * @module charts * @submodule series-bar */ /** * The BarSeries class renders bars positioned vertically along a category or time axis. The bars' * lengths are proportional to the values they represent along a horizontal axis. * and the relevant data points. * * @class BarSeries * @extends MarkerSeries * @uses Histogram * @constructor * @param {Object} config (optional) Configuration parameters. * @submodule series-bar */ Y.BarSeries = Y.Base.create("barSeries", Y.MarkerSeries, [Y.Histogram], { /** * Helper method for calculating the size of markers. * * @method _getMarkerDimensions * @param {Number} xcoord The x-coordinate representing the data point for the marker. * @param {Number} ycoord The y-coordinate representing the data point for the marker. * @param {Number} calculatedSize The calculated size for the marker. For a `BarSeries` is it the width. For a `ColumnSeries` it is the height. * @param {Number} offset Distance of position offset dictated by other marker series in the same graph. * @return Object * @private */ _getMarkerDimensions: function(xcoord, ycoord, calculatedSize, offset) { var config = { top: ycoord + offset }; if(xcoord >= this._leftOrigin) { config.left = this._leftOrigin; config.calculatedSize = xcoord - config.left; } else { config.left = xcoord; config.calculatedSize = this._leftOrigin - xcoord; } return config; }, /** * Resizes and positions markers based on a mouse interaction. * * @method updateMarkerState * @param {String} type state of the marker * @param {Number} i index of the marker * @protected */ updateMarkerState: function(type, i) { if(this._markers && this._markers[i]) { var styles = this._copyObject(this.get("styles").marker), markerStyles, state = this._getState(type), xcoords = this.get("xcoords"), ycoords = this.get("ycoords"), marker = this._markers[i], markers, seriesCollection = this.get("seriesTypeCollection"), seriesLen = seriesCollection ? seriesCollection.length : 0, seriesStyles, seriesSize = 0, offset = 0, renderer, n = 0, ys = [], order = this.get("order"), config; markerStyles = state === "off" || !styles[state] ? styles : styles[state]; markerStyles.fill.color = this._getItemColor(markerStyles.fill.color, i); markerStyles.border.color = this._getItemColor(markerStyles.border.color, i); config = this._getMarkerDimensions(xcoords[i], ycoords[i], styles.height, offset); markerStyles.width = config.calculatedSize; markerStyles.height = Math.min(this._maxSize, markerStyles.height); marker.set(markerStyles); for(; n < seriesLen; ++n) { ys[n] = ycoords[i] + seriesSize; seriesStyles = seriesCollection[n].get("styles").marker; seriesSize += Math.min(this._maxSize, seriesStyles.height); if(order > n) { offset = seriesSize; } offset -= seriesSize/2; } for(n = 0; n < seriesLen; ++n) { markers = seriesCollection[n].get("markers"); if(markers) { renderer = markers[i]; if(renderer && renderer !== undefined) { renderer.set("y", (ys[n] - seriesSize/2)); } } } } } }, { ATTRS: { /** * Read-only attribute indicating the type of series. * * @attribute type * @type String * @default bar */ type: { value: "bar" }, /** * Indicates the direction of the category axis that the bars are plotted against. * * @attribute direction * @type String */ direction: { value: "vertical" } /** * Style properties used for drawing markers. This attribute is inherited from `MarkerSeries`. Below are the default values: * <dl> * <dt>fill</dt><dd>A hash containing the following values: * <dl> * <dt>color</dt><dd>Color of the fill. The default value is determined by the order of the series on the graph. The color * will be retrieved from the below array:<br/> * `["#66007f", "#a86f41", "#295454", "#996ab2", "#e8cdb7", "#90bdbd","#000000","#c3b8ca", "#968373", "#678585"]` * </dd> * <dt>alpha</dt><dd>Number from 0 to 1 indicating the opacity of the marker fill. The default value is 1.</dd> * </dl> * </dd> * <dt>border</dt><dd>A hash containing the following values: * <dl> * <dt>color</dt><dd>Color of the border. The default value is determined by the order of the series on the graph. The color * will be retrieved from the below array:<br/> * `["#205096", "#b38206", "#000000", "#94001e", "#9d6fa0", "#e55b00", "#5e85c9", "#adab9e", "#6ac291", "#006457"]` * <dt>alpha</dt><dd>Number from 0 to 1 indicating the opacity of the marker border. The default value is 1.</dd> * <dt>weight</dt><dd>Number indicating the width of the border. The default value is 1.</dd> * </dl> * </dd> * <dt>height</dt><dd>indicates the width of the marker. The default value is 12.</dd> * <dt>over</dt><dd>hash containing styles for markers when highlighted by a `mouseover` event. The default * values for each style is null. When an over style is not set, the non-over value will be used. For example, * the default value for `marker.over.fill.color` is equivalent to `marker.fill.color`.</dd> * </dl> * * @attribute styles * @type Object */ } }); }, '3.18.1', {"requires": ["series-marker", "series-histogram-base"]});
Badacadabra/Harmoneezer
node_modules/yuidocjs/node_modules/yui/series-bar/series-bar.js
JavaScript
mit
6,757
"use strict"; /** * This is the plugin for syncing location * @type {string} */ var EVENT_NAME = "location"; exports.canEmitEvents = true; /** * @param {BrowserSync} bs */ exports.init = function (bs) { bs.socket.on(EVENT_NAME, exports.socketEvent()); }; /** * Respond to socket event */ exports.socketEvent = function () { return function (data) { window.location = data.url; }; };
fernandoguirao/evita-un-error
wp-content/themes/node_modules/browser-sync/node_modules/browser-sync-client/lib/ghostmode.location.js
JavaScript
gpl-2.0
412
'use strict'; describe('$$cookieWriter', function() { var $$cookieWriter, document; function deleteAllCookies() { var cookies = document.cookie.split(';'); var path = window.location.pathname; for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i]; var eqPos = cookie.indexOf('='); var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie; var parts = path.split('/'); while (parts.length) { document.cookie = name + '=;path=' + (parts.join('/') || '/') + ';expires=Thu, 01 Jan 1970 00:00:00 GMT'; parts.pop(); } } } beforeEach(function() { document = window.document; deleteAllCookies(); expect(document.cookie).toEqual(''); module('ngCookies'); inject(function(_$$cookieWriter_) { $$cookieWriter = _$$cookieWriter_; }); }); afterEach(function() { deleteAllCookies(); expect(document.cookie).toEqual(''); }); describe('remove via $$cookieWriter(cookieName, undefined)', function() { it('should remove a cookie when it is present', function() { document.cookie = 'foo=bar;path=/'; $$cookieWriter('foo', undefined); expect(document.cookie).toEqual(''); }); it('should do nothing when an nonexisting cookie is being removed', function() { $$cookieWriter('doesntexist', undefined); expect(document.cookie).toEqual(''); }); }); describe('put via $$cookieWriter(cookieName, string)', function() { it('should create and store a cookie', function() { $$cookieWriter('cookieName', 'cookie=Value'); expect(document.cookie).toMatch(/cookieName=cookie%3DValue;? ?/); }); it('should overwrite an existing unsynced cookie', function() { document.cookie = 'cookie=new;path=/'; var oldVal = $$cookieWriter('cookie', 'newer'); expect(document.cookie).toEqual('cookie=newer'); expect(oldVal).not.toBeDefined(); }); it('should encode both name and value', function() { $$cookieWriter('cookie1=', 'val;ue'); $$cookieWriter('cookie2=bar;baz', 'val=ue'); var rawCookies = document.cookie.split('; '); //order is not guaranteed, so we need to parse expect(rawCookies.length).toEqual(2); expect(rawCookies).toContain('cookie1%3D=val%3Bue'); expect(rawCookies).toContain('cookie2%3Dbar%3Bbaz=val%3Due'); }); it('should log warnings when 4kb per cookie storage limit is reached', inject(function($log) { var i, longVal = '', cookieStr; for (i = 0; i < 4083; i++) { longVal += 'x'; } cookieStr = document.cookie; $$cookieWriter('x', longVal); //total size 4093-4096, so it should go through expect(document.cookie).not.toEqual(cookieStr); expect(document.cookie).toEqual('x=' + longVal); expect($log.warn.logs).toEqual([]); $$cookieWriter('x', longVal + 'xxxx'); //total size 4097-4099, a warning should be logged expect($log.warn.logs).toEqual( [['Cookie \'x\' possibly not set or overflowed because it was too large (4097 > 4096 ' + 'bytes)!']]); //force browser to dropped a cookie and make sure that the cache is not out of sync $$cookieWriter('x', 'shortVal'); expect(document.cookie).toEqual('x=shortVal'); //needed to prime the cache cookieStr = document.cookie; $$cookieWriter('x', longVal + longVal + longVal); //should be too long for all browsers if (document.cookie !== cookieStr) { this.fail(new Error('browser didn\'t drop long cookie when it was expected. make the ' + 'cookie in this test longer')); } expect(document.cookie).toEqual('x=shortVal'); $log.reset(); })); }); describe('put via $$cookieWriter(cookieName, string), if no <base href> ', function() { beforeEach(inject(function($browser) { $browser.$$baseHref = undefined; })); it('should default path in cookie to "" (empty string)', function() { $$cookieWriter('cookie', 'bender'); // This only fails in Safari and IE when cookiePath returns undefined // Where it now succeeds since baseHref return '' instead of undefined expect(document.cookie).toEqual('cookie=bender'); }); }); }); describe('cookie options', function() { var fakeDocument, $$cookieWriter; function getLastCookieAssignment(key) { return fakeDocument[0].cookie .split(';') .reduce(function(prev, value) { var pair = value.split('=', 2); if (pair[0] === key) { if (isUndefined(prev)) { return isUndefined(pair[1]) ? true : pair[1]; } else { throw new Error('duplicate key in cookie string'); } } else { return prev; } }, undefined); } beforeEach(function() { fakeDocument = [{cookie: ''}]; module('ngCookies', {$document: fakeDocument}); inject(function($browser) { $browser.$$baseHref = '/a/b'; }); inject(function(_$$cookieWriter_) { $$cookieWriter = _$$cookieWriter_; }); }); it('should use baseHref as default path', function() { $$cookieWriter('name', 'value'); expect(getLastCookieAssignment('path')).toBe('/a/b'); }); it('should accept path option', function() { $$cookieWriter('name', 'value', {path: '/c/d'}); expect(getLastCookieAssignment('path')).toBe('/c/d'); }); it('should accept domain option', function() { $$cookieWriter('name', 'value', {domain: '.example.com'}); expect(getLastCookieAssignment('domain')).toBe('.example.com'); }); it('should accept secure option', function() { $$cookieWriter('name', 'value', {secure: true}); expect(getLastCookieAssignment('secure')).toBe(true); }); it('should accept expires option on set', function() { $$cookieWriter('name', 'value', {expires: 'Fri, 19 Dec 2014 00:00:00 GMT'}); expect(getLastCookieAssignment('expires')).toMatch(/^Fri, 19 Dec 2014 00:00:00 (UTC|GMT)$/); }); it('should always use epoch time as expire time on remove', function() { $$cookieWriter('name', undefined, {expires: 'Fri, 19 Dec 2014 00:00:00 GMT'}); expect(getLastCookieAssignment('expires')).toMatch(/^Thu, 0?1 Jan 1970 00:00:00 (UTC|GMT)$/); }); it('should accept date object as expires option', function() { $$cookieWriter('name', 'value', {expires: new Date(Date.UTC(1981, 11, 27))}); expect(getLastCookieAssignment('expires')).toMatch(/^Sun, 27 Dec 1981 00:00:00 (UTC|GMT)$/); }); });
Teremok/angular.js
test/ngCookies/cookieWriterSpec.js
JavaScript
mit
6,640
import warning from 'warning'; const CALLED_ONCE = 'muiPrepared'; export default function callOnce() { if (process.env.NODE_ENV !== 'production') { return (style) => { if (style[CALLED_ONCE]) { warning(false, 'You cannot call prepareStyles() on the same style object more than once.'); } style[CALLED_ONCE] = true; return style; }; } }
matthewoates/material-ui
src/utils/callOnce.js
JavaScript
mit
382
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/STIX-Web/Main/Bold/Main.js * * Copyright (c) 2013-2017 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXMathJax_Main-bold'] = { directory: 'Main/Bold', family: 'STIXMathJax_Main', weight: 'bold', testString: '\u00A0\u00A3\u00A5\u00A7\u00A8\u00AC\u00AE\u00AF\u00B0\u00B1\u00B4\u00B5\u00B7\u00D7\u00F0', 0x20: [0,0,250,0,0], 0x21: [691,13,333,81,251], 0x22: [691,-404,555,83,472], 0x23: [700,0,500,5,495], 0x24: [750,99,500,29,472], 0x25: [706,29,749,61,688], 0x26: [691,16,833,62,789], 0x27: [691,-404,278,75,204], 0x28: [694,168,333,46,306], 0x29: [694,168,333,27,287], 0x2A: [691,-255,500,56,448], 0x2B: [563,57,750,65,685], 0x2C: [155,180,250,39,223], 0x2D: [287,-171,333,44,287], 0x2E: [156,13,250,41,210], 0x2F: [691,19,278,-24,302], 0x30: [688,13,500,24,476], 0x31: [688,0,500,65,441], 0x32: [688,0,500,17,478], 0x33: [688,14,500,16,468], 0x34: [688,0,500,19,476], 0x35: [676,8,500,22,470], 0x36: [688,13,500,28,475], 0x37: [676,0,500,17,477], 0x38: [688,13,500,28,472], 0x39: [688,13,500,26,473], 0x3A: [472,13,333,82,251], 0x3B: [472,180,333,82,266], 0x3C: [534,24,750,80,670], 0x3D: [399,-107,750,68,682], 0x3E: [534,24,750,80,670], 0x3F: [689,13,500,57,445], 0x40: [691,19,930,108,822], 0x41: [690,0,722,9,689], 0x42: [676,0,667,16,619], 0x43: [691,19,722,49,687], 0x44: [676,0,722,14,690], 0x45: [676,0,667,16,641], 0x46: [676,0,611,16,583], 0x47: [691,19,778,37,755], 0x48: [676,0,778,21,759], 0x49: [676,0,389,20,370], 0x4A: [676,96,500,3,478], 0x4B: [676,0,778,30,769], 0x4C: [677,0,667,19,638], 0x4D: [676,0,944,14,921], 0x4E: [676,18,722,16,701], 0x4F: [691,19,778,35,743], 0x50: [676,0,611,16,600], 0x51: [691,176,778,35,743], 0x52: [676,0,722,26,716], 0x53: [692,19,556,35,513], 0x54: [676,0,667,31,636], 0x55: [676,19,722,16,701], 0x56: [676,18,722,16,701], 0x57: [676,15,1000,19,981], 0x58: [676,0,722,16,699], 0x59: [676,0,722,15,699], 0x5A: [676,0,667,28,634], 0x5B: [678,149,333,67,301], 0x5C: [691,19,278,-25,303], 0x5D: [678,149,333,32,266], 0x5E: [676,-311,581,73,509], 0x5F: [-75,125,500,0,500], 0x60: [713,-528,333,8,246], 0x61: [473,14,500,25,488], 0x62: [676,14,556,17,521], 0x63: [473,14,444,25,430], 0x64: [676,14,556,25,534], 0x65: [473,14,444,25,427], 0x66: [691,0,333,14,389], 0x67: [473,206,500,28,483], 0x68: [676,0,556,15,534], 0x69: [691,0,278,15,256], 0x6A: [691,203,333,-57,263], 0x6B: [676,0,556,22,543], 0x6C: [676,0,278,15,256], 0x6D: [473,0,833,15,814], 0x6E: [473,0,556,21,539], 0x6F: [473,14,500,25,476], 0x70: [473,205,556,19,524], 0x71: [473,205,556,34,536], 0x72: [473,0,444,28,434], 0x73: [473,14,389,25,361], 0x74: [630,12,333,19,332], 0x75: [461,14,556,16,538], 0x76: [461,14,500,21,485], 0x77: [461,14,722,23,707], 0x78: [461,0,500,12,484], 0x79: [461,205,500,16,482], 0x7A: [461,0,444,21,420], 0x7B: [698,175,394,22,340], 0x7C: [691,19,220,66,154], 0x7D: [698,175,394,54,372], 0x7E: [333,-173,520,29,491], 0xA0: [0,0,250,0,0], 0xA3: [684,16,500,21,477], 0xA5: [676,0,500,-64,547], 0xA7: [691,132,500,57,443], 0xA8: [666,-537,333,-2,337], 0xAC: [399,-108,750,65,685], 0xAE: [691,19,747,26,721], 0xAF: [637,-565,333,1,331], 0xB0: [688,-402,400,57,343], 0xB1: [518,151,770,65,685], 0xB4: [713,-528,333,86,324], 0xB5: [461,206,556,33,536], 0xB7: [417,-248,250,41,210], 0xD7: [538,33,702,66,636], 0xF0: [691,14,500,25,476], 0xF7: [537,31,570,33,537], 0x127: [676,0,556,15,534], 0x131: [461,0,278,15,256], 0x237: [461,203,333,-57,260], 0x2C6: [704,-528,333,-2,335], 0x2C7: [704,-528,333,-2,335], 0x2C9: [637,-565,370,20,350], 0x2CA: [713,-528,266,20,258], 0x2CB: [713,-528,266,20,258], 0x2D8: [691,-528,333,15,318], 0x2D9: [666,-537,333,102,231], 0x2DA: [750,-537,333,60,273], 0x2DC: [674,-547,333,-16,349], 0x300: [713,-528,0,-369,-131], 0x301: [713,-528,0,-369,-131], 0x302: [704,-528,0,-418,-81], 0x303: [674,-547,0,-432,-67], 0x304: [637,-565,0,-415,-85], 0x306: [691,-528,0,-401,-98], 0x307: [666,-537,0,-314,-185], 0x308: [666,-537,0,-419,-80], 0x30A: [750,-537,0,-356,-143], 0x30B: [713,-528,0,-469,-31], 0x30C: [704,-528,0,-418,-81], 0x338: [662,156,0,-410,31], 0x391: [690,0,722,9,689], 0x392: [676,0,667,16,619], 0x393: [676,0,620,16,593], 0x394: [690,0,722,33,673], 0x395: [676,0,667,16,641], 0x396: [676,0,667,28,634], 0x397: [676,0,778,21,759], 0x398: [692,18,778,35,743], 0x399: [676,0,389,20,370], 0x39A: [676,0,778,30,769], 0x39B: [690,0,707,9,674], 0x39C: [676,0,944,14,921], 0x39D: [676,18,722,16,701], 0x39E: [676,0,647,40,607], 0x39F: [691,19,778,35,743], 0x3A0: [676,0,778,21,759], 0x3A1: [676,0,611,16,600], 0x3A3: [676,0,671,28,641], 0x3A4: [676,0,667,31,636], 0x3A5: [692,0,703,7,693], 0x3A6: [676,0,836,18,818], 0x3A7: [676,0,722,16,699], 0x3A8: [692,0,808,15,797], 0x3A9: [692,0,768,28,740], 0x3B1: [473,14,644,25,618], 0x3B2: [692,205,556,45,524], 0x3B3: [473,205,518,12,501], 0x3B4: [692,14,502,26,477], 0x3B5: [473,14,444,28,429], 0x3B6: [692,205,459,23,437], 0x3B7: [473,205,585,12,545], 0x3B8: [692,14,501,25,476], 0x3B9: [461,14,326,15,304], 0x3BA: [473,0,581,21,559], 0x3BB: [692,18,547,19,527], 0x3BC: [461,205,610,45,588], 0x3BD: [473,14,518,15,495], 0x3BE: [692,205,468,23,439], 0x3BF: [473,14,500,25,476], 0x3C0: [461,18,631,20,609], 0x3C1: [473,205,547,45,515], 0x3C2: [473,203,464,23,444], 0x3C3: [461,14,568,25,529], 0x3C4: [461,14,492,18,457], 0x3C5: [473,14,576,12,551], 0x3C6: [473,205,653,24,629], 0x3C7: [473,205,612,21,586], 0x3C8: [473,205,763,12,751], 0x3C9: [473,14,733,26,708], 0x3D0: [697,10,500,54,462], 0x3D1: [692,14,647,12,620], 0x3D2: [692,0,743,7,733], 0x3D5: [676,205,653,24,629], 0x3D6: [461,14,864,9,851], 0x3D8: [691,205,778,35,743], 0x3D9: [473,205,500,25,476], 0x3DA: [691,211,680,45,645], 0x3DB: [503,203,504,23,483], 0x3DC: [676,0,620,16,593], 0x3DD: [461,205,491,45,458], 0x3DE: [797,14,757,35,715], 0x3DF: [692,0,485,29,453], 0x3E0: [692,205,839,33,801], 0x3E1: [639,205,611,29,583], 0x3F0: [473,19,563,12,546], 0x3F1: [473,205,511,25,486], 0x3F4: [691,19,778,35,743], 0x3F5: [473,14,444,25,430], 0x3F6: [473,14,444,14,419], 0x2013: [271,-181,500,0,500], 0x2014: [271,-181,1000,0,1000], 0x2018: [691,-356,333,70,254], 0x2019: [691,-356,333,79,263], 0x201C: [691,-356,500,32,486], 0x201D: [691,-356,500,14,468], 0x2020: [691,134,500,47,453], 0x2021: [691,132,500,45,456], 0x2026: [156,13,1000,82,917], 0x2032: [713,-438,310,75,235], 0x2033: [713,-438,467,75,392], 0x2034: [713,-438,625,75,550], 0x2035: [713,-438,310,75,235], 0x203E: [838,-766,500,0,500], 0x2044: [688,12,183,-168,345], 0x2057: [713,-438,783,75,708], 0x20D7: [846,-508,0,-470,14], 0x210F: [685,10,576,50,543], 0x2111: [701,25,790,54,735], 0x2113: [699,14,500,43,632], 0x2118: [541,219,850,55,822], 0x211C: [701,25,884,50,841], 0x2127: [674,18,758,35,723], 0x2132: [676,0,616,48,546], 0x2135: [694,34,766,76,690], 0x2136: [694,34,703,60,659], 0x2137: [694,34,562,71,493], 0x2138: [694,34,599,40,559], 0x2190: [451,-55,977,68,909], 0x2191: [676,170,584,94,490], 0x2192: [451,-55,977,68,909], 0x2193: [676,170,584,94,490], 0x2194: [451,-55,977,30,948], 0x2195: [736,230,584,94,490], 0x2196: [676,170,977,68,911], 0x2197: [676,170,977,68,911], 0x2198: [676,170,977,68,911], 0x2199: [676,170,977,68,911], 0x219A: [451,-55,977,68,909], 0x219B: [451,-55,977,68,909], 0x219E: [451,-55,977,68,909], 0x21A0: [451,-55,977,68,909], 0x21A2: [451,-55,977,68,909], 0x21A3: [451,-55,977,68,909], 0x21A6: [451,-55,977,68,909], 0x21A9: [539,-55,966,66,900], 0x21AA: [539,-55,966,66,900], 0x21AB: [540,6,966,66,900], 0x21AC: [540,6,966,66,900], 0x21AD: [451,-55,1297,55,1242], 0x21AE: [451,-55,977,30,948], 0x21B0: [686,170,584,45,503], 0x21B1: [686,170,584,81,539], 0x21B6: [524,0,971,66,905], 0x21B7: [524,0,971,66,905], 0x21BA: [693,127,974,105,869], 0x21BB: [693,127,974,105,869], 0x21BC: [501,-209,977,66,910], 0x21BD: [297,-5,977,65,909], 0x21BE: [694,162,552,239,481], 0x21BF: [694,162,352,71,313], 0x21C0: [501,-209,977,66,910], 0x21C1: [297,-5,977,66,910], 0x21C2: [694,162,552,239,481], 0x21C3: [694,162,552,71,313], 0x21C4: [618,114,977,68,909], 0x21C6: [618,114,977,68,909], 0x21C7: [618,114,977,68,909], 0x21C8: [676,165,864,66,798], 0x21C9: [618,114,977,68,909], 0x21CA: [676,165,864,66,798], 0x21CB: [571,21,977,66,910], 0x21CC: [571,21,977,66,910], 0x21CD: [570,64,977,68,909], 0x21CE: [570,64,1240,50,1190], 0x21CF: [570,64,977,68,909], 0x21D0: [570,64,977,68,909], 0x21D1: [676,170,714,40,674], 0x21D2: [570,64,977,68,909], 0x21D3: [676,170,714,40,674], 0x21D4: [570,64,1240,50,1190], 0x21D5: [736,230,714,40,674], 0x21DD: [451,-55,977,62,914], 0x2200: [676,0,599,5,594], 0x2201: [785,29,539,63,476], 0x2202: [686,10,559,44,559], 0x2203: [676,0,599,76,523], 0x2204: [803,127,599,76,523], 0x2205: [594,90,787,50,737], 0x2207: [676,0,681,23,658], 0x2208: [547,13,750,82,668], 0x2209: [680,146,750,82,668], 0x220B: [547,13,750,82,668], 0x220D: [499,-35,500,60,440], 0x2212: [297,-209,750,66,685], 0x2213: [657,12,770,65,685], 0x2214: [793,57,750,65,685], 0x2215: [732,193,584,78,506], 0x2216: [411,-93,452,25,427], 0x2217: [502,-34,585,82,503], 0x2218: [409,-95,394,40,354], 0x2219: [414,-91,493,85,408], 0x221A: [946,259,965,130,1016], 0x221D: [450,0,772,80,692], 0x221E: [450,0,964,80,884], 0x2220: [569,0,792,50,708], 0x2221: [569,74,792,50,708], 0x2222: [534,26,695,27,667], 0x2223: [690,189,288,100,188], 0x2224: [690,189,411,23,388], 0x2225: [690,189,487,100,387], 0x2226: [690,189,617,23,594], 0x2227: [536,28,640,52,588], 0x2228: [536,28,640,52,588], 0x2229: [541,33,650,66,584], 0x222A: [541,33,650,66,584], 0x222B: [824,320,553,32,733], 0x2234: [575,41,750,66,685], 0x2235: [575,41,750,66,685], 0x223C: [374,-132,750,67,682], 0x223D: [374,-132,750,67,682], 0x2240: [575,40,348,53,295], 0x2241: [444,-62,750,67,682], 0x2242: [463,-45,750,68,683], 0x2243: [463,-45,750,68,683], 0x2245: [568,60,750,68,683], 0x2246: [568,150,750,68,683], 0x2248: [508,-26,750,68,683], 0x224A: [568,75,750,68,683], 0x224D: [518,13,750,68,683], 0x224E: [484,-22,750,68,683], 0x224F: [484,-107,750,68,683], 0x2250: [667,-107,750,68,682], 0x2251: [667,161,750,68,682], 0x2252: [667,161,750,68,682], 0x2253: [667,161,750,68,682], 0x2256: [471,-63,750,68,682], 0x2257: [809,-107,750,68,682], 0x225C: [844,-107,750,68,682], 0x2260: [662,156,750,68,682], 0x2261: [507,-27,750,68,682], 0x2264: [627,121,750,80,670], 0x2265: [627,120,750,80,670], 0x2266: [729,222,750,80,670], 0x2267: [729,222,750,80,670], 0x2268: [729,294,750,80,670], 0x2269: [729,294,750,80,670], 0x226A: [534,24,1000,38,961], 0x226B: [534,24,1000,38,961], 0x226C: [732,193,417,46,371], 0x226E: [625,115,750,80,670], 0x226F: [625,115,750,80,670], 0x2270: [717,235,750,80,670], 0x2271: [717,235,750,80,670], 0x2272: [690,182,750,67,682], 0x2273: [690,182,750,67,682], 0x2276: [734,226,750,80,670], 0x2277: [734,226,750,80,670], 0x227A: [531,23,750,80,670], 0x227B: [531,23,750,80,670], 0x227C: [645,138,750,80,670], 0x227D: [645,138,750,80,670], 0x227E: [676,169,750,67,682], 0x227F: [676,169,750,67,682], 0x2280: [625,115,750,80,670], 0x2281: [625,115,750,80,670], 0x2282: [547,13,750,82,668], 0x2283: [547,13,750,82,668], 0x2286: [647,101,750,82,668], 0x2287: [647,101,750,82,668], 0x2288: [747,201,750,82,668], 0x2289: [747,201,750,82,668], 0x228A: [734,200,750,82,668], 0x228B: [734,200,750,82,668], 0x228E: [541,33,650,66,584], 0x228F: [532,27,750,87,663], 0x2290: [532,27,750,87,663], 0x2291: [644,93,750,87,663], 0x2292: [644,93,750,87,663], 0x2293: [541,33,650,66,584], 0x2294: [541,33,650,66,584], 0x2295: [634,130,864,50,814], 0x2296: [634,130,864,50,814], 0x2297: [634,130,864,50,814], 0x2298: [634,130,864,50,814], 0x2299: [594,90,784,50,734], 0x229A: [634,130,842,39,803], 0x229B: [634,130,864,50,814], 0x229D: [634,130,864,50,814], 0x229E: [661,158,910,45,865], 0x229F: [661,158,910,45,865], 0x22A0: [661,158,910,45,865], 0x22A1: [661,158,910,45,865], 0x22A2: [676,0,750,91,659], 0x22A3: [676,0,750,91,659], 0x22A4: [676,0,750,91,659], 0x22A5: [676,0,750,91,659], 0x22A8: [676,0,750,91,659], 0x22A9: [676,0,972,91,882], 0x22AA: [676,0,944,91,856], 0x22AC: [676,0,913,21,822], 0x22AD: [676,0,912,21,822], 0x22AE: [676,0,1096,21,1024], 0x22AF: [676,0,1104,21,1016], 0x22B2: [534,24,750,81,669], 0x22B3: [534,24,750,81,669], 0x22B4: [621,113,750,81,669], 0x22B5: [621,113,750,81,669], 0x22B8: [436,-96,884,50,834], 0x22BA: [461,216,498,74,424], 0x22BB: [536,189,640,52,588], 0x22BC: [697,28,640,52,588], 0x22C4: [515,-17,584,43,541], 0x22C8: [604,72,870,67,803], 0x22C9: [604,72,870,57,817], 0x22CA: [604,72,870,53,813], 0x22CB: [604,72,870,97,773], 0x22CC: [604,72,870,97,773], 0x22CD: [463,-45,750,68,683], 0x22CE: [536,28,640,41,599], 0x22CF: [536,28,640,41,599], 0x22D0: [600,67,750,63,687], 0x22D1: [600,67,750,63,687], 0x22D2: [541,33,750,65,685], 0x22D3: [541,33,750,65,685], 0x22D4: [643,33,650,66,584], 0x22D6: [534,24,750,80,670], 0x22D7: [534,24,750,80,670], 0x22D8: [534,24,1336,40,1296], 0x22D9: [534,24,1336,40,1296], 0x22DA: [916,408,750,80,670], 0x22DB: [916,408,750,80,670], 0x22DE: [645,138,750,80,670], 0x22DF: [645,138,750,80,670], 0x22E0: [735,199,750,80,670], 0x22E1: [735,199,750,80,670], 0x22E6: [690,200,750,67,682], 0x22E7: [690,200,750,67,682], 0x22E8: [676,187,750,67,682], 0x22E9: [676,187,750,67,682], 0x22EA: [625,115,750,81,669], 0x22EB: [625,115,750,81,669], 0x22EC: [711,228,750,81,669], 0x22ED: [711,228,750,81,669], 0x22EE: [678,174,584,205,375], 0x22EF: [351,-181,977,62,914], 0x22F1: [579,75,977,162,815], 0x2308: [731,193,469,164,459], 0x2309: [731,193,469,10,305], 0x230A: [732,193,469,164,459], 0x230B: [732,193,469,10,305], 0x2322: [378,-129,1026,37,990], 0x2323: [378,-129,1026,37,990], 0x24C8: [690,19,695,0,695], 0x25B3: [811,127,1145,35,1110], 0x25BD: [811,127,1145,35,1110], 0x25CA: [795,289,790,45,745], 0x266D: [740,5,437,86,389], 0x266E: [818,210,490,97,393], 0x266F: [818,210,490,52,438], 0x27E8: [732,193,445,69,399], 0x27E9: [732,193,445,46,376], 0x2A3F: [676,0,734,27,707], 0x2A5E: [887,28,640,52,588], 0x2A7D: [648,140,750,80,670], 0x2A7E: [648,140,750,80,670], 0x2A87: [646,213,750,80,670], 0x2A88: [646,213,750,80,670], 0x2A89: [792,305,750,67,682], 0x2A8A: [792,305,750,67,682], 0x2A95: [648,140,750,80,670], 0x2A96: [648,140,750,80,670], 0x2AAF: [619,111,750,80,670], 0x2AB0: [619,111,750,80,670], 0x2AC5: [730,222,750,80,670], 0x2AC6: [730,222,750,80,670] }; MathJax.Callback.Queue( ["initFont",MathJax.OutputJax["HTML-CSS"],"STIXMathJax_Main-bold"], ["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Main/Bold/Main.js"] );
benjaminvialle/Markus
vendor/assets/javascripts/MathJax_lib/jax/output/HTML-CSS/fonts/STIX-Web/Main/Bold/Main.js
JavaScript
mit
16,017
(function($) { $(function() { try { if (typeof _wpcf7 == 'undefined' || _wpcf7 === null) _wpcf7 = {}; _wpcf7 = $.extend({ cached: 0 }, _wpcf7); $('div.wpcf7 > form').ajaxForm({ beforeSubmit: function(formData, jqForm, options) { jqForm.wpcf7ClearResponseOutput(); jqForm.find('img.ajax-loader').css({ visibility: 'visible' }); return true; }, beforeSerialize: function(jqForm, options) { jqForm.find('.wpcf7-use-title-as-watermark.watermark').each(function(i, n) { $(n).val(''); }); return true; }, data: { '_wpcf7_is_ajax_call': 1 }, dataType: 'json', success: function(data) { var ro = $(data.into).find('div.wpcf7-response-output'); $(data.into).wpcf7ClearResponseOutput(); if (data.invalids) { $.each(data.invalids, function(i, n) { $(data.into).find(n.into).wpcf7NotValidTip(n.message); $(data.into).find(n.into).find('.wpcf7-form-control').addClass('wpcf7-not-valid'); }); ro.addClass('wpcf7-validation-errors'); } if (data.captcha) $(data.into).wpcf7RefillCaptcha(data.captcha); if (data.quiz) $(data.into).wpcf7RefillQuiz(data.quiz); if (1 == data.spam) ro.addClass('wpcf7-spam-blocked'); if (1 == data.mailSent) { ro.addClass('wpcf7-mail-sent-ok'); if (data.onSentOk) $.each(data.onSentOk, function(i, n) { eval(n) }); } else { ro.addClass('wpcf7-mail-sent-ng'); } if (data.onSubmit) $.each(data.onSubmit, function(i, n) { eval(n) }); if (1 == data.mailSent) $(data.into).find('form').resetForm().clearForm(); $(data.into).find('.wpcf7-use-title-as-watermark.watermark').each(function(i, n) { $(n).val($(n).attr('title')); }); $(data.into).wpcf7FillResponseOutput(data.message); } }); $('div.wpcf7 > form').each(function(i, n) { if (_wpcf7.cached) $(n).wpcf7OnloadRefill(); $(n).wpcf7ToggleSubmit(); $(n).find('.wpcf7-submit').wpcf7AjaxLoader(); $(n).find('.wpcf7-acceptance').click(function() { $(n).wpcf7ToggleSubmit(); }); $(n).find('.wpcf7-exclusive-checkbox').each(function(i, n) { $(n).find('input:checkbox').click(function() { $(n).find('input:checkbox').not(this).removeAttr('checked'); }); }); $(n).find('.wpcf7-use-title-as-watermark').each(function(i, n) { var input = $(n); input.val(input.attr('title')); input.addClass('watermark'); input.focus(function() { if ($(this).hasClass('watermark')) $(this).val('').removeClass('watermark'); }); input.blur(function() { if ('' == $(this).val()) $(this).val($(this).attr('title')).addClass('watermark'); }); }); }); } catch (e) { } }); $.fn.wpcf7AjaxLoader = function() { return this.each(function() { var loader = $('<img class="ajax-loader" />') .attr({ src: _wpcf7.loaderUrl, alt: _wpcf7.sending }) .css('visibility', 'hidden'); $(this).after(loader); }); }; $.fn.wpcf7ToggleSubmit = function() { return this.each(function() { var form = $(this); if (this.tagName.toLowerCase() != 'form') form = $(this).find('form').first(); if (form.hasClass('wpcf7-acceptance-as-validation')) return; var submit = form.find('input:submit'); if (! submit.length) return; var acceptances = form.find('input:checkbox.wpcf7-acceptance'); if (! acceptances.length) return; submit.removeAttr('disabled'); acceptances.each(function(i, n) { n = $(n); if (n.hasClass('wpcf7-invert') && n.is(':checked') || ! n.hasClass('wpcf7-invert') && ! n.is(':checked')) submit.attr('disabled', 'disabled'); }); }); }; $.fn.wpcf7NotValidTip = function(message) { return this.each(function() { var into = $(this); into.append('<span class="wpcf7-not-valid-tip">' + message + '</span>'); $('span.wpcf7-not-valid-tip').mouseover(function() { $(this).fadeOut('fast'); }); into.find(':input').mouseover(function() { into.find('.wpcf7-not-valid-tip').not(':hidden').fadeOut('fast'); }); into.find(':input').focus(function() { into.find('.wpcf7-not-valid-tip').not(':hidden').fadeOut('fast'); }); }); }; $.fn.wpcf7OnloadRefill = function() { return this.each(function() { var url = $(this).attr('action'); if (0 < url.indexOf('#')) url = url.substr(0, url.indexOf('#')); var id = $(this).find('input[name="_wpcf7"]').val(); var unitTag = $(this).find('input[name="_wpcf7_unit_tag"]').val(); $.getJSON(url, { _wpcf7_is_ajax_call: 1, _wpcf7: id }, function(data) { if (data && data.captcha) $('#' + unitTag).wpcf7RefillCaptcha(data.captcha); if (data && data.quiz) $('#' + unitTag).wpcf7RefillQuiz(data.quiz); } ); }); }; $.fn.wpcf7RefillCaptcha = function(captcha) { return this.each(function() { var form = $(this); $.each(captcha, function(i, n) { form.find(':input[name="' + i + '"]').clearFields(); form.find('img.wpcf7-captcha-' + i).attr('src', n); var match = /([0-9]+)\.(png|gif|jpeg)$/.exec(n); form.find('input:hidden[name="_wpcf7_captcha_challenge_' + i + '"]').attr('value', match[1]); }); }); }; $.fn.wpcf7RefillQuiz = function(quiz) { return this.each(function() { var form = $(this); $.each(quiz, function(i, n) { form.find(':input[name="' + i + '"]').clearFields(); form.find(':input[name="' + i + '"]').siblings('span.wpcf7-quiz-label').text(n[0]); form.find('input:hidden[name="_wpcf7_quiz_answer_' + i + '"]').attr('value', n[1]); }); }); }; $.fn.wpcf7ClearResponseOutput = function() { return this.each(function() { $(this).find('div.wpcf7-response-output').hide().empty().removeClass('wpcf7-mail-sent-ok wpcf7-mail-sent-ng wpcf7-validation-errors wpcf7-spam-blocked'); $(this).find('span.wpcf7-not-valid-tip').remove(); $(this).find('img.ajax-loader').css({ visibility: 'hidden' }); }); }; $.fn.wpcf7FillResponseOutput = function(message) { return this.each(function() { $(this).find('div.wpcf7-response-output').append(message).slideDown('fast'); }); }; })(jQuery);
MichaelFBA/mercerbell
wp-content/themes/mercerbell/js/scripts.js
JavaScript
gpl-2.0
6,208
loadjs = (function () { /** * Global dependencies. * @global {Object} document - DOM */ var devnull = function() {}, bundleIdCache = {}, bundleResultCache = {}, bundleCallbackQueue = {}; /** * Subscribe to bundle load event. * @param {string[]} bundleIds - Bundle ids * @param {Function} callbackFn - The callback function */ function subscribe(bundleIds, callbackFn) { // listify bundleIds = bundleIds.push ? bundleIds : [bundleIds]; var depsNotFound = [], i = bundleIds.length, numWaiting = i, fn, bundleId, r, q; // define callback function fn = function(bundleId, pathsNotFound) { if (pathsNotFound.length) depsNotFound.push(bundleId); numWaiting--; if (!numWaiting) callbackFn(depsNotFound); }; // register callback while (i--) { bundleId = bundleIds[i]; // execute callback if in result cache r = bundleResultCache[bundleId]; if (r) { fn(bundleId, r); continue; } // add to callback queue q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || []; q.push(fn); } } /** * Publish bundle load event. * @param {string} bundleId - Bundle id * @param {string[]} pathsNotFound - List of files not found */ function publish(bundleId, pathsNotFound) { // exit if id isn't defined if (!bundleId) return; var q = bundleCallbackQueue[bundleId]; // cache result bundleResultCache[bundleId] = pathsNotFound; // exit if queue is empty if (!q) return; // empty callback queue while (q.length) { q[0](bundleId, pathsNotFound); q.splice(0, 1); } } /** * Load individual file. * @param {string} path - The file path * @param {Function} callbackFn - The callback function */ function loadFile(path, callbackFn, args, numTries) { var doc = document, async = args.async, maxTries = args.numTries || 1, isCss, e; numTries = numTries || 0; if (/\.css$/.test(path)) { isCss = true; // css e = doc.createElement('link'); e.rel = 'stylesheet'; e.href = path; } else { // javascript e = doc.createElement('script'); e.src = path; e.async = (async === undefined) ? true : async; } e.onload = e.onerror = e.onbeforeload = function(ev) { var result = ev.type[0]; // Note: The following code isolates IE using `hideFocus` and treats empty // stylesheets as failures to get around lack of onerror support if (isCss && 'hideFocus' in e) { try { if (!e.sheet.cssText.length) result = 'e'; } catch (x) { // sheets objects created from load errors don't allow access to // `cssText` result = 'e'; } } // handle retries in case of load failure if (result == 'e') { // increment counter numTries += 1; // exit function and try again if (numTries < maxTries) { return loadFile(path, callbackFn, args, numTries); } } // execute callback callbackFn(path, result, ev.defaultPrevented); }; // add to document doc.head.appendChild(e); } /** * Load multiple files. * @param {string[]} paths - The file paths * @param {Function} callbackFn - The callback function */ function loadFiles(paths, callbackFn, args) { // listify paths paths = paths.push ? paths : [paths]; var numWaiting = paths.length, x = numWaiting, pathsNotFound = [], fn, i; // define callback function fn = function(path, result, defaultPrevented) { // handle error if (result == 'e') pathsNotFound.push(path); // handle beforeload event. If defaultPrevented then that means the load // will be blocked (ex. Ghostery/ABP on Safari) if (result == 'b') { if (defaultPrevented) pathsNotFound.push(path); else return; } numWaiting--; if (!numWaiting) callbackFn(pathsNotFound); }; // load scripts for (i=0; i < x; i++) loadFile(paths[i], fn, args); } /** * Initiate script load and register bundle. * @param {(string|string[])} paths - The file paths * @param {(string|Function)} [arg1] - The bundleId or success callback * @param {Function} [arg2] - The success or error callback * @param {Function} [arg3] - The error callback */ function loadjs(paths, arg1, arg2) { var bundleId, args; // bundleId (if string) if (arg1 && arg1.trim) bundleId = arg1; // args (default is {}) args = (bundleId ? arg2 : arg1) || {}; // throw error if bundle is already defined if (bundleId) { if (bundleId in bundleIdCache) { throw new Error("LoadJS"); } else { bundleIdCache[bundleId] = true; } } // load scripts loadFiles(paths, function(pathsNotFound) { // success and error callbacks if (pathsNotFound.length) (args.error || devnull)(pathsNotFound); else (args.success || devnull)(); // publish bundle load event publish(bundleId, pathsNotFound); }, args); } /** * Execute callbacks when dependencies have been satisfied. * @param {(string|string[])} deps - List of bundle ids * @param {Object} args - success/error arguments */ loadjs.ready = function (deps, args) { // subscribe to bundle load event subscribe(deps, function(depsNotFound) { // execute callbacks if (depsNotFound.length) (args.error || devnull)(depsNotFound); else (args.success || devnull)(); }); return loadjs; }; /** * Manually satisfy bundle dependencies. * @param {string} bundleId - The bundle id */ loadjs.done = function done(bundleId) { publish(bundleId, []); }; // export return loadjs; })();
Piicksarn/cdnjs
ajax/libs/loadjs/3.0.1/loadjs.js
JavaScript
mit
5,601
/** * (c) 2013 Jexcel Plugin v1.2.1 | Bossanova UI * http://www.github.com/paulhodel/jexcel * * @author: Paul Hodel <paul.hodel@gmail.com> * @description: Create light embedded spreadsheets on your webpages * * ROADMAP: * Online collaboration * Merged cells * Custom renderer * Big data (partial table loading) * Pagination */ (function( $ ){ var methods = { /** * Innitialization, configuration and loading * * @param {Object} options configuration * @return void */ init : function( options ) { // Loading default configuration var defaults = { colHeaders:[], colWidths:[], colAlignments:[], columns:[], minSpareRows:0, minSpareCols:0, minDimensions:[0,0], contextMenu:null, columnSorting:true, columnResize:true, rowDrag:true, editable:true, allowInsertRow:true, allowInsertColumn:true, allowDeleteRow:true, allowDeleteColumn:true, about:'jExcel Spreadsheet\\nVersion 1.2.1\\nAuthor: Paul Hodel <paul.hodel@gmail.com>\\nWebsite: http://bossanova.uk/jexcel' }; // Configuration holder var options = $.extend(defaults, options); // Compatibility if (options.manualColumnResize != undefined) { options.columnResize = options.manualColumnResize; } if (options.manualRowMove != undefined) { options.rowDrag = options.manualRowMove; } // Id var id = $(this).prop('id'); // Main object var main = $(this); // Create prepareTable = function () { // Register options if (! $.fn.jexcel.defaults) { $.fn.jexcel.defaults = new Array(); } $.fn.jexcel.defaults[id] = options; // Create history track array $.fn.jexcel.defaults[id].history = []; $.fn.jexcel.defaults[id].historyIndex = -1; // Loading initial data from remote sources var results = []; // Data holder cannot be blank if (! options.data) { options.data = []; } // Length if (! $.fn.jexcel.defaults[id].data.length) { $.fn.jexcel.defaults[id].data = [[]]; } // Number of columns size = options.colHeaders.length; if (options.data[0].length > size) { size = options.data[0].length; } // Minimal dimensions if ($.fn.jexcel.defaults[id].minDimensions[0] > size) { size = $.fn.jexcel.defaults[id].minDimensions[0]; } // Preparations for (i = 0; i < size; i++) { // Default headers if (! options.colHeaders[i]) { options.colHeaders[i] = $.fn.jexcel('getColumnName', i); } // Default column description if (! options.columns[i]) { options.columns[i] = { type:'text' }; } else if (! options.columns[i]) { options.columns[i].type = 'text'; } if (! options.columns[i].source) { $.fn.jexcel.defaults[id].columns[i].source = []; } if (! options.columns[i].options) { $.fn.jexcel.defaults[id].columns[i].options = []; } if (! options.columns[i].editor) { options.columns[i].editor = null; } if (! options.colAlignments[i]) { options.colAlignments[i] = 'center'; } if (! options.colWidths[i]) { options.colWidths[i] = '50'; } // Pre-load initial source for json autocomplete if (options.columns[i].type == 'autocomplete' || options.columns[i].type == 'dropdown') { // if remote content if (options.columns[i].url) { results.push($.ajax({ url: options.columns[i].url, index: i, dataType:'json', success: function (result) { // Create the dynamic sources $.fn.jexcel.defaults[id].columns[this.index].source = result; } })); } } else if (options.columns[i].type == 'calendar') { // Default format for date columns if (! $.fn.jexcel.defaults[id].columns[i].options.format) { $.fn.jexcel.defaults[id].columns[i].options.format = 'DD/MM/YYYY'; } } } // In case there are external json to be loaded before create the table if (results.length > 0) { // Waiting all external data is loaded $.when.apply(this, results).done(function() { // Create the table $(main).jexcel('createTable'); }); } else { // No external data to be loaded, just created the table $(main).jexcel('createTable'); } } // Load the table data based on an CSV file if (options.csv) { if (! $.csv) { // Required lib not present console.error('Jexcel error: jquery-csv library not loaded'); } else { // Comma as default options.delimiter = options.delimiter || ','; // Load CSV file $.ajax({ url: options.csv, success: function (result) { var i = 0; // Convert data var data = $.csv.toArrays(result); // Headers if (options.csvHeaders == true) { options.colHeaders = data.shift(); } // Data options.data = data; // Prepare table prepareTable(); } }); } } else if (options.url) { // Load json external file $.ajax({ url: options.url, dataType:'json', success: function (result) { // Data options.data = (result.data) ? result.data : result; // Prepare table prepareTable(); } }); } else { // Prepare table prepareTable(); } }, /** * Create the table * * @return void */ createTable : function() { // Id var id = $(this).prop('id'); // Var options var options = $.fn.jexcel.defaults[id]; // Create main table object var table = document.createElement('table'); $(table).prop('class', 'jexcel bossanova-ui'); $(table).prop('cellpadding', '0'); $(table).prop('cellspacing', '0'); // Unselectable properties $(table).prop('unselectable', 'yes'); $(table).prop('onselectstart', 'return false'); $(table).prop('draggable', 'false'); // Create header and body tags var thead = document.createElement('thead'); var tbody = document.createElement('tbody'); // Header $(thead).prop('class', 'jexcel_label'); // Create headers var tr = '<td width="30" class="jexcel_label"></td>'; for (i = 0; i < options.colHeaders.length; i++) { // Default header cell properties width = options.colWidths[i]; align = options.colAlignments[i]; header = options.colHeaders[i]; // Column type hidden if (options.columns[i].type == 'hidden') { // TODO: when it is first check the whole selection not include tr += '<td id="col-' + i + '" style="display:none;">' + options.colHeaders[i] + '</td>'; } else { // Other column types tr += '<td id="col-' + i + '" width="' + width + '" align="' + align +'">' + header + '</td>'; } } // Populate header $(thead).html('<tr>' + tr + '</tr>'); // TODO: filter row //<tr><td></td><td><input type="text"></td></tr> // Append content $(table).append(thead); $(table).append(tbody); // Prevent dragging $(table).on('dragstart', function () { return false; }); // Main object $(this).html(table); // Add the corner square and textarea one time onlly if (! $('.jexcel_corner').length) { // Corner one for all sheets in a page var corner = document.createElement('div'); $(corner).prop('class', 'jexcel_corner'); $(corner).prop('id', 'corner'); // Hidden textarea copy and paste helper var textarea = document.createElement('textarea'); $(textarea).prop('class', 'jexcel_textarea'); $(textarea).prop('id', 'textarea'); // Contextmenu container var contextMenu = document.createElement('div'); $(contextMenu).css('display', 'none'); $(contextMenu).prop('class', 'jexcel_contextmenu'); $(contextMenu).prop('id', 'jexcel_contextmenu'); // Powered by var ads = document.createElement('div'); $(ads).css('display', 'none'); $(ads).html('<a href="http://github.com/paulhodel/jexcel">jExcel Spreadsheet</a>'); // Append elements $('body').append(corner); $('body').append(textarea); $('body').append(contextMenu); $('body').append(ads); // Prevent dragging on the corner object $(corner).on('dragstart', function () { return false; }); // Corner persistence and other helpers $.fn.jexcel.selectedCorner = false; $.fn.jexcel.selectedHeader = null; $.fn.jexcel.resizeColumn = null; // Jexcel context menu $(document).on("contextmenu", function (e) { // Check if the click was in an jexcel element var table = $(e.target).parent().parent().parent(); // Table found if ($(table).is('.jexcel')) { var o = $(e.target).prop('id'); if (o) { o = o.split('-'); contextMenuContent = ''; // Custom context menu if (typeof(options.contextMenu) == 'function') { contextMenuContent = options.contextMenu(o[0], o[1]); } else { if ($(e.target).parent().parent().is('thead')) { contextMenuContent += "<a onclick=\"$('#" + $.fn.jexcel.current + "').jexcel('orderBy', " + o[1] + ", 0)\">Order ascending <span></span></a>"; contextMenuContent += "<a onclick=\"$('#" + $.fn.jexcel.current + "').jexcel('orderBy', " + o[1] + ", 1)\">Order descending <span></span></a><hr>"; if ($.fn.jexcel.defaults[$.fn.jexcel.current].allowInsertColumn == true) { contextMenuContent += "<a onclick=\"$('#" + $.fn.jexcel.current + "').jexcel('insertColumn', 1, null, " + o[1] + ")\">Insert a new column<span></span></a>"; } if ($.fn.jexcel.defaults[$.fn.jexcel.current].allowInsertRow == true) { contextMenuContent += "<a onclick=\"$('#" + $.fn.jexcel.current + "').jexcel('insertRow', 1, " + o[1] + ")\">Insert a new row<span></span></a><hr>"; } if ($.fn.jexcel.defaults[$.fn.jexcel.current].allowDeleteColumn == true) { //contextMenuContent += "<a onclick=\"$('#" + $.fn.jexcel.current + "').jexcel('deleteColumn'," + o[1] + ")\">Delete this row<span></span></a><hr>"; } contextMenuContent += "<a onclick=\"$('#" + $.fn.jexcel.current + "').jexcel('download')\">Save as...<span>Ctrl + S</span></a>"; contextMenuContent += "<a onclick=\"alert('" + options.about + "')\">About<span></span></a>"; } else if ($(e.target).parent().parent().is('tbody')) { if ($.fn.jexcel.defaults[$.fn.jexcel.current].allowInsertColumn == true) { contextMenuContent += "<a onclick=\"$('#" + $.fn.jexcel.current + "').jexcel('insertColumn', 1, null, " + o[1] + ")\">Insert a new column<span></span></a>"; } if ($.fn.jexcel.defaults[$.fn.jexcel.current].allowInsertRow == true) { contextMenuContent += "<a onclick=\"$('#" + $.fn.jexcel.current + "').jexcel('insertRow', 1, " + o[1] + ")\">Insert a new row<span></span></a><hr>"; } if ($.fn.jexcel.defaults[$.fn.jexcel.current].allowDeleteRow == true) { contextMenuContent += "<a onclick=\"$('#" + $.fn.jexcel.current + "').jexcel('deleteRow'," + o[1] + ")\">Delete this row<span></span></a><hr>"; } contextMenuContent += "<a onclick=\"$('#" + $.fn.jexcel.current + "').jexcel('download')\">Save as...<span>Ctrl + S</span></a>"; contextMenuContent += "<a onclick=\"alert('" + options.about + "')\">About<span></span></a>"; } } if (contextMenuContent) { // Contextmenu content $("#jexcel_contextmenu").html(contextMenuContent); // Show jexcel context menu $("#jexcel_contextmenu").css({ display:'block', top: event.pageY + "px", left: event.pageX + "px" }); // Avoid the real one e.preventDefault(); } } } }); $(document).on('mousewheel', function (e) { // Hide context menu $(".jexcel_contextmenu").css('display', 'none'); }); // Global mouse click down controles $(document).on('mousedown', function (e) { // Click on corner icon if (e.target.id == 'corner') { if ($.fn.jexcel.defaults[$.fn.jexcel.current].editable == true) { $.fn.jexcel.selectedCorner = true; } } else { // Check if the click was in an jexcel element var table = $(e.target).parent().parent().parent(); // Table found if ($(table).is('.jexcel')) { // Get id var current = $(table).parent().prop('id'); // Remove selection from any other jexcel if applicable if ($.fn.jexcel.current) { if ($.fn.jexcel.current != current) { $('#' + $.fn.jexcel.current).find('td').removeClass('selected highlight highlight-top highlight-left highlight-right highlight-bottom'); } } // Mark as current $.fn.jexcel.current = current; // Header found if ($(e.target).parent().parent().is('thead')) { var o = $(e.target).prop('id'); if (o) { o = o.split('-'); if ($.fn.jexcel.selectedHeader && (e.shiftKey || e.ctrlKey)) { var d = $($.fn.jexcel.selectedHeader).prop('id').split('-'); } else { // Update selection single column var d = $(e.target).prop('id').split('-'); // Keep track of which header was selected first $.fn.jexcel.selectedHeader = $(e.target); } // Update cursor if ($(e.target).outerWidth() - e.offsetX < 8) { if ($.fn.jexcel.defaults[$.fn.jexcel.current].columnResize == true) { // Resize helper $.fn.jexcel.resizeColumn = { mousePosition: e.pageX, column:o[1], width:parseInt($(e.target).css('width')), } // Border indication $(table).parent().find('.c' + o[1]).addClass('resizing'); $(table).parent().find('#col-' + o[1]).addClass('resizing'); // Remove selected cells $('#' + $.fn.jexcel.current).jexcel('updateSelection'); $('.jexcel_corner').css('left', '-200px'); } } else { // Get cell objects var o1 = $('#' + $.fn.jexcel.current).find('#' + o[1] + '-0'); var o2 = $('#' + $.fn.jexcel.current).find('#' + d[1] + '-' + parseInt($.fn.jexcel.defaults[$.fn.jexcel.current].data.length - 1)); // Update selection $('#' + $.fn.jexcel.current).jexcel('updateSelection', o1, o2, false, 1); } } } else { $.fn.jexcel.selectedHeader = false; } // Body found if ($(e.target).parent().parent().is('tbody')) { // Update row label selection if ($(e.target).is('.jexcel_label')) { if ($.fn.jexcel.defaults[$.fn.jexcel.current].rowDrag == true && $(e.target).outerWidth() - e.offsetX < 8) { // Reset selection $('#' + $.fn.jexcel.current).find('td').removeClass('selected highlight highlight-top highlight-left highlight-right highlight-bottom'); // Hide corner $(corner).css('top', '-200px'); $(corner).css('left', '-200px'); // Reset controls $.fn.jexcel.selectedRow = null; $.fn.jexcel.selectedCell = null; $.fn.jexcel.selectedHeader = null; // Mark which row we are dragging $.fn.jexcel.dragRowFrom = $(e.target).prop('id'); $.fn.jexcel.dragRowOver = $(e.target).prop('id'); // Visual row we are dragging $(e.target).parent().find('td').css('background-color', 'rgba(0,0,0,0.1)'); } else { var o = $(e.target).prop('id').split('-'); if ($.fn.jexcel.selectedRow && (e.shiftKey || e.ctrlKey)) { // Updade selection multi columns var d = $($.fn.jexcel.selectedRow).prop('id').split('-'); } else { // Update selection single column var d = $(e.target).prop('id').split('-'); // Keep track of which header was selected first $.fn.jexcel.selectedRow = $(e.target); } // Get cell objects var o1 = $('#' + $.fn.jexcel.current).find('#0-' + o[1]); var o2 = $('#' + $.fn.jexcel.current).find('#' + parseInt($.fn.jexcel.defaults[$.fn.jexcel.current].columns.length - 1) + '-' + d[1]); $('#' + $.fn.jexcel.current).jexcel('updateSelection', o1, o2); } } else { // Update cell selection if (! $($.fn.jexcel.selectedCell).hasClass('edition')) { if (! $.fn.jexcel.selectedCell || ! e.shiftKey) { $.fn.jexcel.selectedCell = $(e.target); } $('#' + $.fn.jexcel.current).jexcel('updateSelection', $.fn.jexcel.selectedCell, $(e.target)); } else { if ($(e.target) != $.fn.jexcel.selectedCell) { $.fn.jexcel.selectedCell = $(e.target); $('#' + $.fn.jexcel.current).jexcel('updateSelection', $.fn.jexcel.selectedCell, $(e.target)); } } // No full row selected $.fn.jexcel.selectedRow = null; } } } else { // Check if the object is in the jexcel domain if (! $(e.target).parents('.jexcel').length) { // Remove selection from any other jexcel if applicable if ($.fn.jexcel.current) { $('#' + $.fn.jexcel.current).find('td').removeClass('selected highlight highlight-top highlight-left highlight-right highlight-bottom'); } // Hide corner $(corner).css('top', '-200px'); $(corner).css('left', '-200px'); // Reset controls $.fn.jexcel.current = null; $.fn.jexcel.selectedRow = null; $.fn.jexcel.selectedCell = null; $.fn.jexcel.selectedHeader = null; } } } }); // Global mouse click up controles $(document).on('mouseup', function (e) { if (e.target.id == 'jexcel_arrow') { if (! $.fn.jexcel.current) { $.fn.jexcel.current = $(e.target).parents('.jexcel').parent().prop('id'); } $.fn.jexcel.selectedCell = $(e.target).parent().parent(); $('#' + $.fn.jexcel.current).jexcel('updateSelection', $.fn.jexcel.selectedCell, $.fn.jexcel.selectedCell); // Open editor $('#' + $.fn.jexcel.current).jexcel('openEditor', $.fn.jexcel.selectedCell); } else { // Hide context menu $("#jexcel_contextmenu").css('display', 'none'); // Cancel any corner selection $.fn.jexcel.selectedCorner = false; // Cancel resizing if ($.fn.jexcel.resizeColumn) { // Remove resizing border indication $('#' + $.fn.jexcel.current).find('thead td').removeClass('resizing'); $('#' + $.fn.jexcel.current).find('tbody td').removeClass('resizing'); // Reset resizing helper $.fn.jexcel.resizeColumn = null; } // Data to be copied var selection = $('#' + $.fn.jexcel.current).find('tbody td.selection'); if ($(selection).length > 0) { // First and last cells var o = $(selection[0]).prop('id').split('-'); var d = $(selection[selection.length - 1]).prop('id').split('-'); // Copy data $('#' + $.fn.jexcel.current).jexcel('copyData', o, d); // Remove selection $(selection).removeClass('selection selection-left selection-right selection-top selection-bottom'); } selection = $('#' + $.fn.jexcel.current).find('tbody td.highlight'); if ($(selection).length > 0) { // First and last cells o = $(selection[0]); d = $(selection[selection.length - 1]); // Events if (typeof($.fn.jexcel.defaults[id].onselection) == 'function') { $.fn.jexcel.defaults[id].onselection($('#' + $.fn.jexcel.current), o, d); } } } // Execute the final move if ($.fn.jexcel.dragRowFrom) { if ($.fn.jexcel.dragRowFrom != $.fn.jexcel.dragRowOver) { // Get ids o = $.fn.jexcel.dragRowFrom.split('-'); d = $.fn.jexcel.dragRowOver.split('-'); // Change data order $.fn.jexcel.defaults[$.fn.jexcel.current].data.splice(d[1], 0, $.fn.jexcel.defaults[$.fn.jexcel.current].data.splice(o[1], 1)[0]); // Reset data in a new order $('#' + $.fn.jexcel.current).jexcel('setData', $.fn.jexcel.defaults[$.fn.jexcel.current].data); } // Remove style $('#' + $.fn.jexcel.dragRowFrom).css('cursor', ''); $('#' + $.fn.jexcel.dragRowOver).css('cursor', ''); $('#' + $.fn.jexcel.dragRowOver).parent().find('td').css('background-color', ''); } $.fn.jexcel.dragRowFrom = null; $.fn.jexcel.dragRowOver = null; }); // Double click $(document).on('dblclick', function (e) { // Jexcel is selected if ($.fn.jexcel.current) { if ($.fn.jexcel.defaults[$.fn.jexcel.current].editable == true) { // Corner action if (e.target.id == 'corner') { var selection = $('#' + $.fn.jexcel.current).find('tbody td.highlight'); // Any selected cells if (typeof(selection) == 'object') { // Get selected cells var o = $(selection[0]).prop('id').split('-'); var d = $(selection[selection.length - 1]).prop('id').split('-'); // Double click copy o[1] = parseInt(d[1]) + 1; d[1] = parseInt($.fn.jexcel.defaults[$.fn.jexcel.current].data.length); // Do copy $('#' + $.fn.jexcel.current).jexcel('copyData', o, d); } } // Open editor action if ($(e.target).is('.highlight')) { $('#' + $.fn.jexcel.current).jexcel('openEditor', $(e.target)); } } if ($.fn.jexcel.defaults[$.fn.jexcel.current].columnSorting == true) { // Header found if ($(e.target).parent().parent().is('thead')) { var o = $(e.target).prop('id'); if (o) { o = $(e.target).prop('id').split('-'); // Update order $('#' + $.fn.jexcel.current).jexcel('orderBy', o[1]); } } } } }); $(document).on('mousemove', function (e) { if ($.fn.jexcel.current) { if ($.fn.jexcel.defaults[$.fn.jexcel.current].columnResize == true) { // Resizing is ongoing if ($.fn.jexcel.resizeColumn) { var width = e.pageX - $.fn.jexcel.resizeColumn.mousePosition; if ($.fn.jexcel.resizeColumn.width + width > 0) { $('#' + $.fn.jexcel.current).jexcel('setWidth', $.fn.jexcel.resizeColumn.column, $.fn.jexcel.resizeColumn.width + width); } } else { // Header found if ($(e.target).parent().parent().is('thead')) { // Update cursor if ($(e.target).outerWidth() - e.offsetX < 8 && $(e.target).prop('id') != '') { $(e.target).css('cursor', 'col-resize'); } else { $(e.target).css('cursor', ''); } } } } // Body found if ($.fn.jexcel.defaults[$.fn.jexcel.current].rowDrag == true) { if ($(e.target).parent().parent().is('tbody')) { // Update row label selection if ($(e.target).is('.jexcel_label')) { if ($(e.target).outerWidth() - e.offsetX < 8) { $(e.target).css('cursor', 'all-scroll'); } else { $(e.target).css('cursor', ''); } } } } } else { } // Keeping visual indication if ($.fn.jexcel.dragRowFrom) { $('body').css('cursor', 'all-scroll'); } else { $('body').css('cursor', ''); } }); $(document).on('mouseover', function (e) { // No resizing is ongoing if (! $.fn.jexcel.resizeColumn) { // Get jexcel table var table = $(e.target).closest('.jexcel'); // If the user is in the current table if ($.fn.jexcel.current == $(table).parent().prop('id')) { // Header found if ($(e.target).parent().parent().is('thead')) { if ($.fn.jexcel.selectedHeader) { // Updade selection if (e.buttons) { var o = $($.fn.jexcel.selectedHeader).prop('id'); var d = $(e.target).prop('id'); if (o && d) { o = o.split('-'); d = d.split('-'); // Get cell objects var o1 = $('#' + $.fn.jexcel.current).find('#' + o[1] + '-0'); var o2 = $('#' + $.fn.jexcel.current).find('#' + d[1] + '-' + parseInt($.fn.jexcel.defaults[$.fn.jexcel.current].data.length - 1)); // Update selection $('#' + $.fn.jexcel.current).jexcel('updateSelection', o1, o2); } } } } // Body found if ($(e.target).parent().parent().is('tbody')) { // Update row label selection if ($(e.target).is('.jexcel_label')) { if ($.fn.jexcel.selectedRow) { // Updade selection if (e.buttons) { var o = $($.fn.jexcel.selectedRow).prop('id'); var d = $(e.target).prop('id'); if (o && d) { o = o.split('-'); d = d.split('-'); // Get cell objects var o1 = $('#' + $.fn.jexcel.current).find('#0-' + o[1]); var o2 = $('#' + $.fn.jexcel.current).find('#' + parseInt($.fn.jexcel.defaults[$.fn.jexcel.current].columns.length - 1) + '-' + d[1]); // Update selection $('#' + $.fn.jexcel.current).jexcel('updateSelection', o1, o2); } } } else if ($.fn.jexcel.dragRowFrom) { // Remove previous row visual background $('#' + $.fn.jexcel.dragRowOver).parent().find('td').css('background-color', ''); // Add new row visual background $(e.target).parent().find('td').css('background-color', 'rgba(0,0,0,0.1)'); // Keep over reference $.fn.jexcel.dragRowOver = $(e.target).prop('id'); } } else { if ($.fn.jexcel.selectedCell) { if (! $($.fn.jexcel.selectedCell).hasClass('edition')) { if ($.fn.jexcel.selectedCorner == true) { // Copy option $('#' + $.fn.jexcel.current).jexcel('updateCornerSelection', $(e.target)); } else { // Updade selection if (e.buttons) { $('#' + $.fn.jexcel.current).jexcel('updateSelection', $.fn.jexcel.selectedCell, $(e.target)); } } } } } } } } }); // Fixed headers /*$(document).bind("scroll", function() { if ($.fn.jexcel.current) { // Positions var offset = $(this).scrollTop(); var tableOffset = $('#' + $.fn.jexcel.current).position().top; var tableHeight = $('#' + $.fn.jexcel.current).height(); // New cloned thead var theadClose = $('#' + $.fn.jexcel.current + ' thead.jexcel_thead_clone'); if (offset < tableOffset + tableHeight) { // Cloned headers if ($(theadClose).length == 0) { var tclone = $('#' + $.fn.jexcel.current + ' thead').clone(); $(tclone).addClass('jexcel_thead_clone'); $(tclone).css('display', 'none'); $(tclone).css('width', $('#' + $.fn.jexcel.current + ' thead').css('width')); $(tclone).css('left', $('#' + $.fn.jexcel.current + ' thead').css('left')); $('#' + $.fn.jexcel.current + ' thead').after(tclone); } if (offset >= tableOffset && $(theadClose).css('display') == 'none') { if ($(theadClose).css('display') == 'none') { $(theadClose).css('display', ''); } if ($(theadClose).css('width') < $('#' + $.fn.jexcel.current + ' thead').css('width')) { $(theadClose).css('width', $('#' + $.fn.jexcel.current + ' thead').width()); } } else if (offset < tableOffset) { $(theadClose).remove(); } } else { // Remove in case exists if ($(theadClose).length) { $(theadClose).remove(); } } } });*/ // IE Compatibility $(document).on('paste', function (e) { if (e.originalEvent) { if ($.fn.jexcel.defaults[$.fn.jexcel.current].editable == true) { $('#' + $.fn.jexcel.current).jexcel('paste', $.fn.jexcel.selectedCell, e.originalEvent.clipboardData.getData('text')); } e.preventDefault(); } }); // Keyboard controls var keyBoardCell = null; $(document).keydown(function(e) { if ($.fn.jexcel.current) { // Support variables var cell = null; // Get current cell if ($.fn.jexcel.selectedCell) { columnId = $($.fn.jexcel.selectedCell).prop('id').split('-'); // Which key if (e.which == 37) { // Left arrow if (! $($.fn.jexcel.selectedCell).hasClass('edition')) { if (e.ctrlKey) { cell = $($.fn.jexcel.selectedCell).parent().find('td').not('.jexcel_label').first(); } else { cell = $($.fn.jexcel.selectedCell).prev(); } e.preventDefault(); } } else if (e.which == 39) { // Right arrow if (! $($.fn.jexcel.selectedCell).hasClass('edition')) { if (e.ctrlKey) { cell = $($.fn.jexcel.selectedCell).parent().find('td').last(); } else { cell = $($.fn.jexcel.selectedCell).next(); } e.preventDefault(); } } else if (e.which == 38) { // Top arrow if (! $($.fn.jexcel.selectedCell).hasClass('edition')) { if (e.ctrlKey) { cell = $($.fn.jexcel.selectedCell).parent().parent().find('tr').first().find('#' + columnId[0] + '-' + 0); } else { cell = $($.fn.jexcel.selectedCell).parent().prev().find('#' + columnId[0] + '-' + (columnId[1] - 1)); } e.preventDefault(); } } else if (e.which == 40) { // Bottom arrow if (! $($.fn.jexcel.selectedCell).hasClass('edition')) { if (e.ctrlKey) { cell = $($.fn.jexcel.selectedCell).parent().parent().find('tr').last().find('#' + columnId[0] + '-' + ($.fn.jexcel.defaults[$.fn.jexcel.current].data.length - 1)); } else { cell = $($.fn.jexcel.selectedCell).parent().next().find('#' + columnId[0] + '-' + (parseInt(columnId[1]) + 1)); } e.preventDefault(); } } else if (e.which == 27) { // Escape if ($($.fn.jexcel.selectedCell).hasClass('edition')) { // Exit without saving $('#' + $.fn.jexcel.current).jexcel('closeEditor', $($.fn.jexcel.selectedCell), false); } } else if (e.which == 13) { // Edition in progress if ($($.fn.jexcel.selectedCell).hasClass('edition')) { // Exit saving data if ($.fn.jexcel.defaults[$.fn.jexcel.current].columns[columnId[0]].type == 'calendar') { $('#' + $.fn.jexcel.current).find('editor').jcalendar('close', 1) } else { $('#' + $.fn.jexcel.current).jexcel('closeEditor', $($.fn.jexcel.selectedCell), true); } } // If not edition check if the selected cell is in the last row if ($.fn.jexcel.defaults[$.fn.jexcel.current].allowInsertRow == true) { if (columnId[1] == $.fn.jexcel.defaults[$.fn.jexcel.current].data.length - 1) { // New record in case selectedCell in the last row $('#' + $.fn.jexcel.current).jexcel('insertRow'); } } // Go to the next line cell = $($.fn.jexcel.selectedCell).parent().next().find('#' + columnId[0] + '-' + (parseInt(columnId[1]) + 1)); e.preventDefault(); } else if (e.which == 9) { // Edition in progress if ($($.fn.jexcel.selectedCell).hasClass('edition')) { // Exit saving data if ($.fn.jexcel.defaults[$.fn.jexcel.current].columns[columnId[0]].type == 'calendar') { $('#' + $.fn.jexcel.current).find('editor').jcalendar('close', 1) } else { $('#' + $.fn.jexcel.current).jexcel('closeEditor', $($.fn.jexcel.selectedCell), true); } } // Tab key - Get the id of the selected cell if ($.fn.jexcel.defaults[$.fn.jexcel.current].allowInsertColumn == true) { if (columnId[0] == $.fn.jexcel.defaults[$.fn.jexcel.current].data[0].length - 1) { // New record in case selectedCell in the last column $('#' + $.fn.jexcel.current).jexcel('insertColumn'); } } // Highlight new column if (! $($.fn.jexcel.selectedCell).hasClass('edition')) { cell = $($.fn.jexcel.selectedCell).next(); } e.preventDefault(); } else if (e.which == 46) { // Delete (erase cell in case no edition is running) if ($.fn.jexcel.defaults[$.fn.jexcel.current].editable == true) { if (! $($.fn.jexcel.selectedCell).hasClass('edition')) { // Prepare History var records = $('#' + $.fn.jexcel.current).jexcel('prepareHistoryRecords', $('#' + $.fn.jexcel.current).find('.highlight'), ''); // Save history $('#' + $.fn.jexcel.current).jexcel('setHistory', records); // Change value $('#' + $.fn.jexcel.current).jexcel('setValue', $('#' + $.fn.jexcel.current).find('.highlight'), ''); } } } else { if (e.metaKey && ! e.shiftKey && ! e.ctrlKey) { if (e.which == 67) { // Command + C, Mac $('#' + $.fn.jexcel.current).jexcel('copy', true); e.preventDefault(); } } else if (! e.shiftKey && ! e.ctrlKey) { if ($.fn.jexcel.selectedCell) { if ($.fn.jexcel.defaults[$.fn.jexcel.current].editable == true) { // If is not readonly if ($.fn.jexcel.defaults[$.fn.jexcel.current].columns[columnId[0]].type != 'readonly') { // Start edition in case a valid character. if (! $($.fn.jexcel.selectedCell).hasClass('edition')) { // TODO: check the sample characters able to start a edition if (/[a-zA-Z0-9]/.test(String.fromCharCode(e.keyCode))) { $('#' + $.fn.jexcel.current).jexcel('openEditor', $($.fn.jexcel.selectedCell), true); } } } } } } else if (! e.shiftKey && e.ctrlKey) { if (e.which == 65) { // Ctrl + A t = $(this).find('.jexcel tbody td').not('.jexcel_label'); o = $(t).first(); t = $(t).last(); $('#' + $.fn.jexcel.current).jexcel('updateSelection', o, t); // Prevent page selection e.preventDefault(); } else if (e.which == 83) { // Ctrl + S $('#' + $.fn.jexcel.current).jexcel('download'); // Prevent page selection e.preventDefault(); } else if (e.which == 89) { // Ctrl + Y if (!$($.fn.jexcel.selectedCell).hasClass('edition')) { $('#' + $.fn.jexcel.current).jexcel('redo'); } e.preventDefault(); } else if (e.which == 90) { // Ctrl + Z if (!$($.fn.jexcel.selectedCell).hasClass('edition')) { $('#' + $.fn.jexcel.current).jexcel('undo'); } e.preventDefault(); } else if (e.which == 67) { // Ctrl + C $('#' + $.fn.jexcel.current).jexcel('copy', true); e.preventDefault(); } else if (e.which == 88) { // Ctrl + X if ($.fn.jexcel.defaults[$.fn.jexcel.current].editable == true) { $('#' + $.fn.jexcel.current).jexcel('cut'); } else { $('#' + $.fn.jexcel.current).jexcel('copy', true); } e.preventDefault(); } else if (e.which == 86) { // Ctrl + V if (window.clipboardData) { if ($.fn.jexcel.defaults[$.fn.jexcel.current].editable == true) { $('#' + $.fn.jexcel.current).jexcel('paste', $.fn.jexcel.selectedCell, window.clipboardData.getData('Text')); } e.preventDefault(); } } } } // Arrows control if (cell) { // Control selected cell if ($(cell).length > 0 && $(cell).prop('id').substr(0,3) != 'row') { // In case of a multiple cell selection if (e.shiftKey) { // Keep first selected cell if (! keyBoardCell) { keyBoardCell = $.fn.jexcel.selectedCell; } // Origin cell o = keyBoardCell; } else if (e.ctrlKey) { // Remove previous cell keyBoardCell = null; o = cell; } else { // Remove previous cell keyBoardCell = null; // Origin cell o = cell; } // Target cell t = cell; // Current cell $.fn.jexcel.selectedCell = cell; // Focus $(cell).focus(); // Update selection $('#' + $.fn.jexcel.current).jexcel('updateSelection', o, t); } } } } }); } // Load data $(this).jexcel('setData'); }, /** * Set data * * @param array data In case no data is sent, default is reloaded * @return void */ setData : function(data) { // Id var id = $(this).prop('id'); // Update data if (data) { if (typeof(data) == 'string') { data = JSON.parse(data); } $.fn.jexcel.defaults[id].data = data; } // Create history track array $.fn.jexcel.defaults[id].history = []; $.fn.jexcel.defaults[id].historyIndex = -1; // Adjust minimal dimensions var size_i = $.fn.jexcel.defaults[id].colHeaders.length; var size_j = $.fn.jexcel.defaults[id].data.length; var min_i = $.fn.jexcel.defaults[id].minDimensions[0]; var min_j = $.fn.jexcel.defaults[id].minDimensions[1]; var max_i = min_i > size_i ? min_i : size_i; var max_j = min_j > size_j ? min_j : size_j; for (j = 0; j < max_j; j++) { for (i = 0; i < max_i; i++) { if ($.fn.jexcel.defaults[id].data[j] == undefined) { $.fn.jexcel.defaults[id].data[j] = []; } if ($.fn.jexcel.defaults[id].data[j][i] == undefined) { $.fn.jexcel.defaults[id].data[j][i] = ''; } } } // Dynamic columns $.fn.jexcel.defaults[id].dynamicColumns = []; // Data container var tbody = $(this).find('tbody'); // Reset data $(tbody).html(''); // Create cells for (j = 0; j < $.fn.jexcel.defaults[id].data.length; j++) { // New line of data to be append in the table tr = document.createElement('tr'); // Index column $(tr).append('<td id="row-' + j + '" class="jexcel_label">' + parseInt(j + 1) + '</td>'); // Data columns for (i = 0; i < $.fn.jexcel.defaults[id].colHeaders.length; i++) { // New column of data to be append in the line td = $(this).jexcel('createCell', i, j); // Add column to the row $(tr).append(td); } // Add row to the table body $(tbody).append(tr); } // Dynamic updates if ($.fn.jexcel.defaults[id].dynamicColumns.length > 0) { $(this).jexcel('formula'); } // Table is ready if (typeof($.fn.jexcel.defaults[id].onload) == 'function') { $.fn.jexcel.defaults[id].onload($(this)); } }, /** * Update table settings helper. Update cells after loading * * @param methods * @return void */ updateSettings : function(options) { // Id var id = $(this).prop('id'); // Keep options if (! options) { if ($.fn.jexcel.defaults[id].updateSettingsOptions) { options = $.fn.jexcel.defaults[id].updateSettingsOptions; } } // Go through all cells if (typeof(options) == 'object') { $.fn.jexcel.defaults[id].updateSettingsOptions = options; var cells = $(this).find('.jexcel tbody td').not('.jexcel_label'); if (typeof(options.cells) == 'function') { $.each(cells, function (k, v) { id = $(v).prop('id').split('-'); options.cells($(v), id[0], id[1]); }); } } }, /** * Open the editor * * @param object cell * @return void */ openEditor : function(cell, empty) { // Id var id = $(this).prop('id'); // Main var main = $(this); // Options var options = $.fn.jexcel.defaults[id]; // Get cell position var position = $(cell).prop('id').split('-'); // Readonly if ($(cell).hasClass('readonly') == true) { // Do nothing } else { // Holder $.fn.jexcel.edition = $(cell).html(); $.fn.jexcel.editionValue = $(this).jexcel('getValue', $(cell)); // If there is a custom editor for it if (options.columns[position[0]].editor) { // Keep the current value $(cell).addClass('edition'); // Custom editors options.columns[position[0]].editor.openEditor(cell); } else { // Native functions if (options.columns[position[0]].type == 'checkbox' || options.columns[position[0]].type == 'hidden') { // Do nothing for checkboxes or hidden columns } else if (options.columns[position[0]].type == 'dropdown') { // Keep the current value $(cell).addClass('edition'); // Create dropdown if (typeof(options.columns[position[0]].filter) == 'function') { var source = options.columns[position[0]].filter($(this), $(cell), position[0], position[1], options.columns[position[0]].source); } else { var source = options.columns[position[0]].source; } var html = '<select>'; for (i = 0; i < source.length; i++) { if (typeof(source[i]) == 'object') { k = source[i].id; v = source[i].name; } else { k = source[i]; v = source[i]; } html += '<option value="' + k + '">' + v + '</option>'; } html += '</select>'; // Get current value var value = $(cell).find('input').val(); // Open editor $(cell).html(html); // Editor configuration var editor = $(cell).find('select'); $(editor).change(function () { $(main).jexcel('closeEditor', $(this).parent(), true); }); $(editor).blur(function () { $(main).jexcel('closeEditor', $(this).parent(), true); }); $(editor).focus(); if (value) { $(editor).val(value); } } else if (options.columns[position[0]].type == 'calendar') { $(cell).addClass('edition'); // Get content var value = $(cell).find('input').val(); // Basic editor var editor = document.createElement('input'); $(editor).prop('class', 'editor'); $(editor).css('width', $(cell).width()); $(editor).val($(cell).text()); $(cell).html(editor); $(cell).find(''); $(cell).focus(); options.columns[position[0]].options.onclose = function () { $(main).jexcel('closeEditor', $(cell), true); } // Current value $(editor).jcalendar(options.columns[position[0]].options); $(editor).jcalendar('open', value); } else if (options.columns[position[0]].type == 'autocomplete') { // Keep the current value $(cell).addClass('edition'); // Get content var html = $(cell).text(); var value = $(cell).find('input').val(); // Basic editor var editor = document.createElement('input'); $(editor).prop('class', 'editor'); $(editor).css('width', $(cell).width()); // Results var result = document.createElement('div'); $(result).prop('class', 'results'); if (html) { $(result).html('<li id="' + value + '">' + html + '</li>'); } else { $(result).css('display', 'none'); } // Search var timeout = null; $(editor).on('keyup', function () { // String var str = $(this).val(); // Timeout if (timeout) { clearTimeout(timeout) } // Delay search timeout = setTimeout(function () { // Object $(result).html(''); // List result showResult = function(data, str) { // Create options $.each(data, function(k, v) { if (typeof(v) == 'object') { name = v.name; id = v.id; } else { name = v; id = v; } if (name.toLowerCase().indexOf(str.toLowerCase()) != -1) { li = document.createElement('li'); $(li).prop('id', id) $(li).html(name); $(li).mousedown(function (e) { // TODO: avoid other selection in this handler. $(cell).html(this); $(main).jexcel('closeEditor', $(cell), true); }); $(result).append(li); } }); if (! $(result).html()) { $(result).html('<div style="padding:6px;">No result found</div>'); } $(result).css('display', ''); } // Search if (options.columns[position[0]].url) { $.getJSON (options.columns[position[0]].url + '?q=' + str + '&r=' + $(main).jexcel('getRowData', position[1]), function (data) { showResult(data, str); }); } else if (options.columns[position[0]].source) { showResult(options.columns[position[0]].source, str); } }, 500); }); $(cell).html(editor); $(cell).append(result); // Current value $(editor).focus(); $(editor).val(''); // Close editor handler $(editor).blur(function () { $(main).jexcel('closeEditor', $(cell), false); }); } else { // Keep the current value $(cell).addClass('edition'); var input = $(cell).find('input'); // Get content if ($(input).length) { var html = $(input).val(); } else { var html = $(cell).html(); } // Basic editor var editor = document.createElement('input'); $(editor).prop('class', 'editor'); $(editor).css('width', $(cell).width()); $(cell).html(editor); // Bind mask if (options.columns[position[0]].mask) { if (! $.fn.masked) { console.error('Jexcel: it was not possible to load the mask plugin.'); } else { $(editor).mask(options.columns[position[0]].mask, options.columns[position[0]].options) } } // Current value $(editor).focus(); if (! empty) { $(editor).val(html); } // Close editor handler $(editor).blur(function () { $(main).jexcel('closeEditor', $(this).parent(), true); }); } } } }, /** * Close the editor and save the information * * @param object cell * @param boolean save * @return void */ closeEditor : function(cell, save) { // Remove edition mode mark $(cell).removeClass('edition'); // Id var id = $(this).prop('id'); // Options var options = $.fn.jexcel.defaults[id]; // Cell identification var position = $(cell).prop('id').split('-'); // Get cell properties if (save == true) { // Before change if (typeof(options.columns[position[0]].onbeforechange) == 'function') { options.columns[position[0]].onbeforechange($(this), $(cell)); } // If custom editor if (options.columns[position[0]].editor) { // Custom editor options.columns[position[0]].editor.closeEditor(cell, save); } else { // Native functions if (options.columns[position[0]].type == 'checkbox' || options.columns[position[0]].type == 'hidden') { // Do nothing } else if (options.columns[position[0]].type == 'dropdown') { // Get value var value = $(cell).find('select').val(); var text = $(cell).find('select').find('option:selected').text(); // Set value if (! text) { text = '&nbsp'; } $(cell).html('<input type="hidden" value="' + value + '">' + text + '<span class="jexcel_arrow"><span id="jexcel_arrow"></span></span>'); } else if (options.columns[position[0]].type == 'autocomplete') { // Set value var obj = $(cell).find('li'); if (obj.length > 0) { var value = $(cell).find('li').prop('id'); var text = $(cell).find('li').html(); $(cell).html('<input type="hidden" value="' + value + '">' + text); } else { $(cell).html(''); } } else if (options.columns[position[0]].type == 'calendar') { var value = $(cell).find('.jcalendar_value').val(); var text = $(cell).find('.jcalendar_input').val(); $(cell).html('<input type="hidden" value="' + value + '">' + text); } else { // Get content var value = $(cell).find('.editor').val(); // For formulas if (value.substr(0,1) == '=') { if ($.fn.jexcel.defaults[id].dynamicColumns.indexOf($(cell).prop('id')) == -1) { $.fn.jexcel.defaults[id].dynamicColumns.push($(cell).prop('id')); } } $(cell).html(value); } } // Prepare History var records = $(this).jexcel('prepareHistoryRecords', cell, value, $.fn.jexcel.editionValue); // Save history $(this).jexcel('setHistory', records); // Get value from column and set the default $.fn.jexcel.defaults[id].data[position[1]][position[0]] = $(this).jexcel('getValue', $(cell)); // Change if (typeof(options.onchange) == 'function') { options.onchange($(this), $(cell), value); } // After changes $(this).jexcel('afterChange'); // Sparerows and sparecols configuration if (options.minSpareCols > 0) { if (position[0] == $.fn.jexcel.defaults[id].data[0].length - 1) { $('#' + $.fn.jexcel.current).jexcel('insertColumn', options.minSpareCols); } } if (options.minSpareRows > 0) { if (position[1] == $.fn.jexcel.defaults[id].data.length - 1) { $('#' + $.fn.jexcel.current).jexcel('insertRow', options.minSpareRows); } } } else { if (options.columns[position[0]].type == 'calendar') { // Do nothing - calendar will be closed without keeping the current value } else { // Restore value $(cell).html($.fn.jexcel.edition); // Finish temporary edition $.fn.jexcel.edition = null; } } }, /** * Get the value from a cell * * @param object cell * @return string value */ getValue : function(cell) { var value = null; // If is a string get the cell object if (typeof(cell) != 'object') { // Convert in case name is excel liked ex. A10, BB92 cell = $(this).jexcel('getIdFromColumnName', cell); // Get object based on a string ex. 12-1, 13-3 cell = $(this).find('[id=' + cell +']'); } // If column exists if ($(cell).length) { // Id var id = $(this).prop('id'); // Global options var options = $.fn.jexcel.defaults[id]; // Configuration var position = $(cell).prop('id').split('-'); // Get value based on the type if (options.columns[position[0]].editor) { // Custom editor value = options.columns[position[0]].editor.getValue(cell); } else { // Native functions if (options.columns[position[0]].type == 'checkbox') { // Get checkbox value value = $(cell).find('input').is(':checked') ? '1' : '0'; } else if (options.columns[position[0]].type == 'dropdown' || options.columns[position[0]].type == 'autocomplete' || options.columns[position[0]].type == 'calendar') { // Get value value = $(cell).find('input').val(); } else if (options.columns[position[0]].type == 'currency') { value = $(cell).html().replace( /\D/g, ''); } else { // Get default value value = $(cell).find('input'); if ($(value).length) { value = $(value).val(); } else { value = $(cell).html(); } } } } return value; }, /** * Set a cell value * * IMPORTANT: Programatically changes are not considered for history (undo/redo). * * @param object cell destination cell * @param object value value * @return void */ setValue : function(cell, value, ignoreEvents) { // If is a string get the cell object if (typeof(cell) !== 'object') { // Convert in case name is excel liked ex. A10, BB92 cell = $(this).jexcel('getIdFromColumnName', cell); // Get object based on a string ex. 12-1, 13-3 cell = $(this).find('[id=' + cell +']'); } // If column exists if ($(cell).length) { // Id var id = $(this).prop('id'); // Main object var main = $(this); // Global options var options = $.fn.jexcel.defaults[id]; // Go throw all cells $.each(cell, function(k, v) { // Cell identification var position = $(v).prop('id').split('-'); // Before Change if (! ignoreEvents) { if (typeof(options.columns[position[0]].onbeforechange) == 'function') { options.columns[position[0]].onbeforechange($(this), $(v)); } } if (options.columns[position[0]].editor) { // Custom editor options.columns[position[0]].editor.setValue(v, value); } else if ($(v).hasClass('readonly') == true) { // Do nothing value = null; } else { // Native functions if (options.columns[position[0]].type == 'checkbox') { if (value == 1 || value == true) { $(v).find('input').prop('checked', true); } else { $(v).find('input').prop('checked', false); } } else if (options.columns[position[0]].type == 'dropdown' || options.columns[position[0]].type == 'autocomplete') { // Dropdown and autocompletes key = ''; val = ''; if (value) { var combo = []; var source = options.columns[position[0]].source; for (num = 0; num < source.length; num++) { if (typeof(source[num]) == 'object') { combo[source[num].id] = source[num].name; } else { combo[source[num]] = source[num]; } } if (combo[value]) { key = value; val = combo[value]; } else { val = null; } } if (! val) { val = '&nbsp'; } $(v).html('<input type="hidden" value="' + key + '">' + val + '<span class="jexcel_arrow"><span id="jexcel_arrow"></span></span>'); } else if (options.columns[position[0]].type == 'calendar') { val = ''; if (value != 'undefined') { val = $.fn.jcalendar('label', value); } else { val = ''; } $(v).html('<input type="hidden" value="' + value + '">' + val); } else { if (value) { if (value.substr(0,1) == '=') { if ($.fn.jexcel.defaults[id].dynamicColumns.indexOf($(cell).prop('id')) == -1) { $.fn.jexcel.defaults[id].dynamicColumns.push($(cell).prop('id')); } } } $(v).html(value); } } // Get value from column and set the default $.fn.jexcel.defaults[id].data[position[1]][position[0]] = value; // Change if (! ignoreEvents) { if (typeof(options.onchange) == 'function') { options.onchange($(this), $(v), value); } } }); // After changes if (! ignoreEvents) { $(this).jexcel('afterChange'); } return true; } else { return false; } }, /** * Update the cells selection * * @param object o cell origin * @param object d cell destination * @return void */ updateSelection : function(o, d, ignoreEvents, origin) { // Main table var main = $(this); // Id var id = $(this).prop('id'); // Cells var cells = $(this).find('tbody td'); var header = $(this).find('thead td'); // Remove highlight $(cells).removeClass('highlight'); $(cells).removeClass('highlight-left'); $(cells).removeClass('highlight-right'); $(cells).removeClass('highlight-top'); $(cells).removeClass('highlight-bottom'); // Update selected column $(header).removeClass('selected'); $(cells).removeClass('selected'); // Origin & Destination if (o && d) { $(o).addClass('selected'); // Define coordinates o = $(o).prop('id').split('-'); d = $(d).prop('id').split('-'); if (parseInt(o[0]) < parseInt(d[0])) { px = parseInt(o[0]); ux = parseInt(d[0]); } else { px = parseInt(d[0]); ux = parseInt(o[0]); } if (parseInt(o[1]) < parseInt(d[1])) { py = parseInt(o[1]); uy = parseInt(d[1]); } else { py = parseInt(d[1]); uy = parseInt(o[1]); } // Redefining styles for (i = px; i <= ux; i++) { for (j = py; j <= uy; j++) { $(this).find('#' + i + '-' + j).addClass('highlight'); $(this).find('#' + px + '-' + j).addClass('highlight-left'); $(this).find('#' + ux + '-' + j).addClass('highlight-right'); $(this).find('#' + i + '-' + py).addClass('highlight-top'); $(this).find('#' + i + '-' + uy).addClass('highlight-bottom'); // Row and column headers $(main).find('#col-' + i).addClass('selected'); $(main).find('#row-' + j).addClass('selected'); } } } // Events if (! ignoreEvents) { if (typeof($.fn.jexcel.defaults[id].oncellselection) == 'function') { $.fn.jexcel.defaults[id].oncellselection($('#' + $.fn.jexcel.current), o, d, origin); } } // Find corner cell $(this).jexcel('updateCornerPosition'); }, /** * Update the cells move data TODO: copy multi columns - TODO! * * @param object o cell origin * @param object d cell destination * @return void */ updateCornerSelection : function(current) { // Main table var main = $(this); // Remove selection var cells = $(this).find('tbody td'); $(cells).removeClass('selection'); $(cells).removeClass('selection-left'); $(cells).removeClass('selection-right'); $(cells).removeClass('selection-top'); $(cells).removeClass('selection-bottom'); // Get selection var selection = $(this).find('tbody td.highlight'); // Get elements first and last var s = $(selection[0]).prop('id').split('-'); var d = $(selection[selection.length - 1]).prop('id').split('-'); // Get current var c = $(current).prop('id').split('-'); // Vertical copy if (c[1] > d[1] || c[1] < s[1]) { // Vertical var px = parseInt(s[0]); var ux = parseInt(d[0]); if (parseInt(c[1]) > parseInt(d[1])) { var py = parseInt(d[1]) + 1; var uy = parseInt(c[1]); } else { var py = parseInt(c[1]); var uy = parseInt(s[1]) - 1; } } else if (c[0] > d[0] || c[0] < s[0]) { // Horizontal copy var py = parseInt(s[1]); var uy = parseInt(d[1]); if (parseInt(c[0]) > parseInt(d[0])) { var px = parseInt(d[0]) + 1; var ux = parseInt(c[0]); } else { var px = parseInt(c[0]); var ux = parseInt(s[0]) - 1; } } for (j = py; j <= uy; j++) { for (i = px; i <= ux; i++) { $(this).find('#' + i + '-' + j).addClass('selection'); $(this).find('#' + i + '-' + py).addClass('selection-top'); $(this).find('#' + i + '-' + uy).addClass('selection-bottom'); $(this).find('#' + px + '-' + j).addClass('selection-left'); $(this).find('#' + ux + '-' + j).addClass('selection-right'); } } //$(this).jexcel('updateCornerPosition'); }, /** * Update corner position * * @return void */ updateCornerPosition : function() { var cells = $(this).find('.highlight'); if ($(cells).length) { corner = $(cells).last(); // Get the position of the corner helper var t = parseInt($(corner).offset().top) + $(corner).height() + 5; var l = parseInt($(corner).offset().left) + $(corner).width() + 5; // Place the corner in the correct place $('.jexcel_corner').css('top', t); $('.jexcel_corner').css('left', l); } }, /** * Get the data from a row * * @param integer row number * @return string value */ getRowData : function(row) { // Get row row = $(this).find('#row-' + row).parent().find('td').not(':first'); // String var str = ''; // Search all tds in a row if (row.length > 0) { for (i = 0; i < row.length; i++) { str += $(this).jexcel('getValue', $(row)[i]) + ','; } } return str; }, /** * Get the whole table data * * @param integer row number * @return string value */ getData : function(highlighted) { // Control vars var dataset = []; var px = 0; var py = 0; // Column and row length var x = $(this).find('thead tr td').not(':first').length; var y = $(this).find('tbody tr').length; // Go through the columns to get the data for (j = 0; j < y; j++) { px = 0; for (i = 0; i < x; i++) { // Cell cell = $(this).find('#' + i + '-' + j); // Cell selected or fullset if (! highlighted || $(cell).hasClass('highlight')) { // Get value if (! dataset[py]) { dataset[py] = []; } dataset[py][px] = $(this).jexcel('getValue', $(cell)); px++; } } if (px > 0) { py++; } } return dataset; }, /** * Copy method * * @param bool highlighted - Get only highlighted cells * @param delimiter - \t default to keep compatibility with excel * @return string value */ copy : function(highlighted, delimiter, returnData) { if (! delimiter) { delimiter = "\t"; } var str = ''; var row = ''; var val = ''; var pc = false; var pr = false; // Column and row length var x = $(this).find('thead tr td').not(':first').length; var y = $(this).find('tbody tr').length; // Go through the columns to get the data for (j = 0; j < y; j++) { row = ''; pc = false; for (i = 0; i < x; i++) { // Get cell cell = $(this).find('#' + i + '-' + j); // If cell is highlighted if (! highlighted || $(cell).hasClass('highlight')) { if (pc) { row += delimiter; } // Get value val = $(this).jexcel('getValue', $(cell)); if (val.match(/,/g)) { val = '"' + val + '"'; } row += val; pc = true; } } if (row) { if (pr) { str += "\n"; } str += row; pr = true; } } // Create a hidden textarea to copy the values if (! returnData) { txt = $('.jexcel_textarea'); $(txt).val(str); $(txt).select(); document.execCommand("copy"); } return str; }, cut : function () { var main = $(this); // Copy data $(this).jexcel('copy', true); var cells = $(this).find('.highlight'); // Prepare History var records = $('#' + $.fn.jexcel.current).jexcel('prepareHistoryRecords', cells, ''); // Save history $('#' + $.fn.jexcel.current).jexcel('setHistory', records); // Remove current data $(this).jexcel('setValue', cells, ''); }, /** * Paste method TODO: if the clipboard is larger than the table create automatically columns/rows? * * @param integer row number * @return string value */ paste : function(cell, data) { // Id var id = $(this).prop('id'); // Data data = data.replace(/(\r)/gm, ''); data = data.split("\n"); // Initial position var position = $(cell).prop('id'); if (position) { position = position.split('-'); var x = parseInt(position[0]); var y = parseInt(position[1]); // Automatic adding new rows when the copied data is larger then the table if (y + data.length > $.fn.jexcel.defaults[id].data.length) { $(this).jexcel('insertRow', y + data.length - $.fn.jexcel.defaults[id].data.length); } // Automatic adding new columns when the copied data is larger then the table if (data[0]) { row = data[0].split("\t"); if (x + row.length > $.fn.jexcel.defaults[id].data[y].length) { $(this).jexcel('insertColumn', x + row.length - $.fn.jexcel.defaults[id].data[y].length); } } // History records var records = []; // Go through the columns to get the data for (j = 0; j < data.length; j++) { // Explode column values row = data[j].split("\t"); for (i = 0; i < row.length; i++) { // Get cell cell = $(this).find('#' + (parseInt(i) + parseInt(x)) + '-' + (parseInt(j) + parseInt(y))); // If cell exists if ($(cell).length > 0) { // Keep cells history records.push({ cell: $(cell), newValue: row[i], oldValue: $(this).jexcel('getValue', $(cell)), }); // Update new value $(this).jexcel('setValue', $(cell), row[i], false); } } } // Save history if (records.length > 0) { $(this).jexcel('setHistory', records); } } }, /** * Insert a new column * * @param object properties - column properties * @param int numColumns - number of columns to be created * @return void */ insertColumn : function (numColumns, properties, position) { var main = $(this); // Id var id = $(this).prop('id'); // Number of columns to be created if (! numColumns) { numColumns = 1; } // Minimal default properties var defaults = { column: { type:'text' }, width:'50', align:'center' }; properties = $.extend(defaults, properties); // Get the main object configuration var options = $.fn.jexcel.defaults[id]; // Configuration if (options.allowInsertColumn == true) { // Current column number var num = options.colHeaders.length; // Create columns for (i = num; i < (num + numColumns); i++) { // Adding the column properties to the main property holder options.colHeaders[i] = properties.header || $.fn.jexcel('getColumnName', i); options.colWidths[i] = properties.width; options.colAlignments[i] = properties.align; options.columns[i] = properties.column; if (! options.columns[i].source) { $.fn.jexcel.defaults[id].columns[i].source = []; } if (! options.columns[i].options) { $.fn.jexcel.defaults[id].columns[i].options = []; } // Default header cell properties width = options.colWidths[i]; align = options.colAlignments[i]; header = options.colHeaders[i]; // Create header html var td = '<td id="col-' + i + '" width="' + width + '" align="' + align + '">' + header + '</td>'; // Add element to the table var tr = $(this).find('thead.jexcel_label tr')[0]; $(tr).append(td); // Add columns to the content rows tr = $(this).find('table > tbody > tr'); $.each(tr, function (k, v) { // Update data array options.data[k][i] = ''; // HTML cell td = $(main).jexcel('createCell', i, k); // Append cell to the tbody $(v).append(td); }); } } }, /** * Insert a new row * * @param object numLines - how many lines to be included * @return void */ insertRow : function(numLines, position) { // Id var id = $(this).prop('id'); // Main configuration var options = $.fn.jexcel.defaults[id]; // Configuration if (options.allowInsertRow == true) { // Num lines if (! numLines) { // Add one line is the default numLines = 1; } j = parseInt($.fn.jexcel.defaults[id].data.length); // Adding lines for (row = 0; row < numLines; row++) { // New line of data to be append in the table tr = document.createElement('tr'); // Index column $(tr).append('<td id="row-' + j + '" class="jexcel_label">' + parseInt(j + 1) + '</td>'); // New data $.fn.jexcel.defaults[id].data[j] = []; for (i = 0; i < $.fn.jexcel.defaults[id].colHeaders.length; i++) { // New Data $.fn.jexcel.defaults[id].data[j][i] = ''; // New column of data to be append in the line td = $(this).jexcel('createCell', i, j); // Add column to the row $(tr).append(td); } // Add row to the table body $(this).find('tbody').append(tr); j++; } } }, /** * Delete a row by number * * @param integer lineNumber - line show be excluded * @return void */ deleteRow : function(lineNumber) { // Id var id = $(this).prop('id'); // Main configuration var options = $.fn.jexcel.defaults[id]; // Global Configuration if (options.allowDeleteRow == true) { // Id var id = $(this).prop('id'); if (parseInt(lineNumber) > -1) { // Remove from source $.fn.jexcel.defaults[id].data.splice(parseInt(lineNumber), 1); // Update table $(this).jexcel('setData', $.fn.jexcel.defaults[id].data); } } }, /** * Delete a column by number * * @TODO: need to recreate the headers * @param integer columnNumber - column show be excluded * @return void */ deleteColumn : function(columnNumber) { // Id /*var id = $(this).prop('id'); // Main configuration var options = $.fn.jexcel.defaults[id]; // Global Configuration if (options.allowDeleteColumn == true) { // Id var id = $(this).prop('id'); if (parseInt(columnNumber) > -1) { // Default headers options.columns.splice(parseInt(columnNumber), 1); options.colHeaders.splice(parseInt(columnNumber), 1); options.colAlignments.splice(parseInt(columnNumber), 1); options.colWidths.splice(parseInt(columnNumber), 1); // Delete data from source for (j = 0; j < $.fn.jexcel.defaults[id].data.length; j++) { // Remove column from each line options.data[j].splice(parseInt(columnNumber), 1); } // Update table $(this).jexcel('setData', options.data); } }*/ }, /** * Set the column width * @param column - column number (first column is: 0) * @param width - new column width */ setWidth : function (column, width) { if (width > 0) { // In case the column is an object if (typeof(column) == 'object') { column = $(column).prop('id').split('-'); column = column[0]; } var col = $(this).find('thead #col-' + column); if (col.length) { $(col).prop('width', width); } } }, /** * Get the column width * @param column - column number (first column is: 0) * @return width - current column width */ getWidth : function (column) { // In case the column is an object if (typeof(column) == 'object') { column = $(column).prop('id').split('-'); column = column[0]; } var col = $(this).find('thead #col-' + column); if (col.length) { return $(col).prop('width'); } }, /** * Set the column title * @param column - column number (first column is: 0) * @param title - new column title */ setHeader : function (column, title) { if (title) { var col = $(this).find('thead #col-' + column); if (col.length) { $(col).html(title); } } }, /** * Update column source for dropboxes */ setSource : function (column, source) { // In case the column is an object if (typeof(column) == 'object') { column = $(column).prop('id').split('-'); column = column[0]; } // Id var id = $(this).prop('id'); // Update defaults $.fn.jexcel.defaults[id].columns[column].source = source; }, /** * After change */ afterChange : function() { // Id var id = $(this).prop('id'); // Dynamic updates if ($.fn.jexcel.defaults[id].dynamicColumns.length > 0) { $(this).jexcel('formula'); } // After Changes if (typeof($.fn.jexcel.defaults[id].onafterchange) == 'function') { $.fn.jexcel.defaults[id].onafterchange($(this)); } // Update settings $(this).jexcel('updateSettings'); }, /** * Helper function to copy data using the corner icon */ copyData : function(o, d) { // Get data from all selected cells var data = $(this).jexcel('getData', true); // Cells var px = parseInt(o[0]); var ux = parseInt(d[0]); var py = parseInt(o[1]); var uy = parseInt(d[1]); // History records var records = []; // Copy data procedure var posx = 0; var posy = 0; for (j = py; j <= uy; j++) { // Controls if (data[posy] == undefined) { posy = 0; } posx = 0; // Data columns for (i = px; i <= ux; i++) { // Column if (data[posy] == undefined) { posx = 0; } else if (data[posy][posx] == undefined) { posx = 0; } // Get cell cell = $(this).find('#' + i + '-' + j); // Update non-readonly if ($(cell).length && ! $(cell).hasClass('readonly')) { // Keep cells history records.push({ cell: $(cell), newValue: data[posy][posx], oldValue: $(this).jexcel('getValue', $(cell)), }); // Set data $(this).jexcel('setValue', cell, data[posy][posx], false); } posx++; } posy++; } // Save history if (records.length > 0) { $(this).jexcel('setHistory', records); } }, /** * Sort data and reload table */ orderBy : function(column, order) { if (column >= 0) { // Identify thead container var c = $(this).find('thead').first(); // No order specified then toggle order if (! (order == '0' || order == '1')) { var d = $(c).find('.arrow-down'); if ($(d).length > 0) { order = 1; } else { order = 0; } } // Remove styling $(c).find('.arrow-down').remove(); $(c).find('.arrow-up').remove(); $(c).find('td').css('text-decoration', 'none'); // Add style on specified column if (order == 1) { $(c).find('#col-' + column).append('<span class="arrow-up"></span>').css('text-decoration', 'underline'); } else { $(c).find('#col-' + column).append('<span class="arrow-down"></span>').css('text-decoration', 'underline'); } // Hide corner $('.jexcel_corner').css('top', '-200px'); $('.jexcel_corner').css('left', '-200px'); // Id var id = $(this).prop('id'); var options = $.fn.jexcel.defaults[id]; Array.prototype.sortBy = function(p, o) { return this.slice(0).sort(function(a, b) { if (! o) { return (a[p] > b[p]) ? 1 : (a[p] < b[p]) ? -1 : 0; } else { return (a[p] > b[p]) ? -1 : (a[p] < b[p]) ? 1 : 0; } }); } var data = options.data.sortBy(column, order); $(this).jexcel('setData', data); return true; } }, /** * Apply formula to all columns in the table */ formula : function() { // Keep instannce of this object var main = $(this); // Id var id = $(this).prop('id'); // Custom formulas if ($.fn.jexcel.defaults[id].formulas) { var formulas = $.fn.jexcel.defaults[id].formulas; // Set instance $.fn.jexcel.defaults[id].formulas.instance = this; } // Dynamic columns var columns = $.fn.jexcel.defaults[id].dynamicColumns; // Define global variables var varibles = $(this).find('.jexcel tbody td').not('.jexcel_label'); $.each(varibles, function (k, v) { i = $(main).jexcel('getColumnNameFromId', $(v).prop('id')); v = $(main).jexcel('getValue', $(v)); if (v == parseInt(v)) { window[i] = parseInt(v); } else { window[i] = v; } }) if (typeof excelFormulaUtilities == 'object') { // Process columns $.each(columns, function (k, column) { // Get value from the column formula = $(main).jexcel('getValue', column); // Column value is a formula if (formula) { if (formula.substr(0,1) == '=') { // Convert formula to javascript value = excelFormulaUtilities.formula2JavaScript(formula); value = eval(value); // Set value if (value === null || isNaN(value)) { $(main).find('#' + column).addClass('error'); value = '<input type="hidden" value="' + formula + '">#ERROR'; // Update cell content $(main).find('#' + column).html(value); } else { $(main).find('#' + column).removeClass('error'); value = '<input type="hidden" value="' + formula + '">' + value; // Update cell content $(main).find('#' + column).html(value); } } else { // Remove any existing calculation error $(main).find('#' + column).removeClass('error'); // No longer dynamic columns.splice(k, 1); } } else { // Remove any existing calculation error $(main).find('#' + column).removeClass('error'); // No longer dynamic columns.splice(k, 1); } }); } else { console.error('excelFormulaUtilities lib not included'); } }, /** * Multi-utility helper * * @param object options { action: METHOD_NAME } * @return mixed */ helper : function (options) { var data = []; if (typeof(options) == 'object') { // Return a empty bidimensional array if (options.action == 'createEmptyData') { var x = options.cols || 10; var y = options.rows || 100; for (j = 0; j < y; j++) { data[j] = []; for (i = 0; i < x; i++) { data[j][i] = ''; } } } } return data; }, /** * Download CSV table * * @return null */ download : function () { // Get table id var id = $(this).prop('id'); // Increment and get the current history index var options = $.fn.jexcel.defaults[id]; // Data var data = ''; // Get headers if applicable if (options.csvHeaders == true) { data = options.colHeaders.join() + "\n"; } // Get data data += $(this).jexcel('copy', false, ',', true); // Download elment var pom = document.createElement('a'); var blob = new Blob([data], {type: 'text/csv;charset=utf-8;'}); var url = URL.createObjectURL(blob); pom.href = url; pom.setAttribute('download', 'jexcelTable.csv'); pom.click(); }, /** * Initializes a new history record for undo/redo * * @return null */ setHistory : function(changes) { var main = $(this); var id = $(this).prop('id'); // Increment and get the current history index var index = ++$.fn.jexcel.defaults[id].historyIndex; // Slice the array to discard undone changes var history = ($.fn.jexcel.defaults[id].history = $.fn.jexcel.defaults[id].history.slice(0, index + 1)); // Create history slot history[index] = { firstSelected: changes[0].cell, lastSelected: changes[changes.length - 1].cell, cellChanges: changes }; }, /** * Prepare a history record to be saved * * @return historyRecord */ prepareHistoryRecords : function(cell, newValue, oldValue) { var main = $(this); // Create history slot var records = []; // Store the cell change details $.each(cell, function (k, v) { // Get current value if (typeof(oldValue) == 'undefined') { ov = $(main).jexcel('getValue', $(v)); } else { ov = oldValue; } // Keep cells history records.push({ cell: $(v), newValue: newValue, oldValue: ov, }); }); return records; }, /** * Prepare a history record by array * * @return historyRecord */ prepareHistory : function(cell, newValue, oldValue) { // Create history slot var historyRecord = { firstSelected: cell[0], lastSelected: cell[cell.length - 1], cellChanges: [] }; // Store the cell change details $.each(cell, function (k, v) { // Get current value if (typeof(oldValue) == 'undefined') { ov = $(main).jexcel('getValue', $(v)); } else { ov = oldValue; } // Keep cells history historyRecord.cellChanges.push({ cell: $(v), newValue: newValue, oldValue: ov, }); }); return historyRecord; }, /** * Undo last action */ undo : function () { var id = $(this).prop('id'); if ($.fn.jexcel.defaults[id].historyIndex >= 0) { var historyRecord = $.fn.jexcel.defaults[id].history[$.fn.jexcel.defaults[id].historyIndex--]; for (var i = 0; i < historyRecord.cellChanges.length; i++) { $(this).jexcel('setValue', $(historyRecord.cellChanges[i].cell), historyRecord.cellChanges[i].oldValue, true); } $(this).jexcel('updateSelection', historyRecord.firstSelected, historyRecord.lastSelected); } }, /** * Redo previously undone action */ redo : function () { var id = $(this).prop('id'); if ($.fn.jexcel.defaults[id].historyIndex < $.fn.jexcel.defaults[id].history.length - 1) { var historyRecord = $.fn.jexcel.defaults[id].history[++$.fn.jexcel.defaults[id].historyIndex]; for (var i = 0; i < historyRecord.cellChanges.length; i++) { $(this).jexcel('setValue', $(historyRecord.cellChanges[i].cell), historyRecord.cellChanges[i].newValue, true); } $(this).jexcel('updateSelection', historyRecord.firstSelected, historyRecord.lastSelected); } }, /** * Create cell */ createCell : function(i, j) { // Get object identification var id = $(this).prop('id'); // Main configuration var options = $.fn.jexcel.defaults[id]; // Line properties align = options.colAlignments[i]; width = options.colWidths[i]; // Create cell and properties td = document.createElement('td'); $(td).prop('width', width); $(td).prop('align', align); $(td).prop('id', i + '-' +j); $(td).addClass('c' + i); $(td).addClass('r' + j); // Hidden column if (options.columns[i].type == 'hidden') { $(td).css('display', 'none'); } else if (options.columns[i].type == 'checkbox') { if (options.columns[i].readOnly == true) { $(td).html('<input type="checkbox" disabled="disabled">'); } else { $(td).html('<input type="checkbox" onclick="var instance = $(this).parents(\'.jexcel\').parent(); $(instance).jexcel(\'setHistory\', $(instance).jexcel(\'prepareHistoryRecords\', $(this).parent(), $(this).prop(\'checked\') ? 1 : 0, $(this).prop(\'checked\') ? 0 : 1)); $(instance).jexcel(\'setValue\', $(this).parent(), $(this).prop(\'checked\') ? 1 : 0);">'); } } // Set column value $(this).jexcel('setValue', $(td), '' + options.data[j][i], true); // Readonly if (options.columns[i].readOnly == true) { $(td).addClass('readonly', 'readonly'); } return $(td); }, /** * Get header letter when no name is specified */ getColumnName : function(i) { var letter = ''; if (i > 701) { letter += String.fromCharCode(64 + parseInt(i / 676)); letter += String.fromCharCode(64 + parseInt((i % 676) / 26)); } else if (i > 25) { letter += String.fromCharCode(64 + parseInt(i / 26)); } letter += String.fromCharCode(65 + (i % 26)); return letter; }, /** * Convert excel like column to jexcel id * * @param string id * @return string id */ getIdFromColumnName : function (id) { var t = /^[a-zA-Z]+/.exec(id); if (t) { var code = 0; for (var i = 0; i < t[0].length; i++) { code += parseInt(t[0].charCodeAt(i) - 65); } id = code + '-' + (parseInt(/[0-9]+$/.exec(id)) - 1); } return id; }, /** * Convert jexcel id to excel like column name * * @param string id * @return string id */ getColumnNameFromId : function (id) { var name = id.split('-'); return $.fn.jexcel('getColumnName', name[0]) + (parseInt(name[1]) + 1); } }; $.fn.jexcel = function( method ) { if ( methods[method] ) { return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.tooltip' ); } }; })( jQuery );
joeyparrish/cdnjs
ajax/libs/jexcel/1.2.2/js/jquery.jexcel.js
JavaScript
mit
113,171
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('main.html', { 'width': 800, 'height': 600 }); });
plxaye/chromium
src/remoting/webapp/background.js
JavaScript
apache-2.0
313
;(function(undefined) { 'use strict'; /** * BottleJS v0.1.0 - 2014-09-24 * A powerful, extensible dependency injection micro container * * Copyright (c) 2014 Stephen Young * Licensed MIT */ /** * Unique id counter; * * @type Number */ var id = 0; /** * Local slice alias * * @type Functions */ var slice = Array.prototype.slice; /** * Register a constant * * @param String name * @param mixed value * @return Bottle */ var constant = function constant(name, value) { Object.defineProperty(this.container, name, { configurable : false, enumerable : true, value : value, writable : false }); return this; }; /** * Register a factory inside a generic provider. * * @param String name * @param Function Factory * @return Bottle */ var factory = function factory(name, Factory) { return provider.call(this, name, function GenericProvider() { this.$get = Factory; }); }; /** * Map of middlewear by index => name * * @type Object */ var middles = []; var getMiddlewear = function getMiddlewear(id, name) { var group = middles[id]; if (!group) { group = middles[id] = {}; } if (!group[name]) { group[name] = []; } return group[name]; }; /** * Register middlewear. * * @param String name * @param Function func * @return Bottle */ var middlewear = function middlewear(name, func) { if (typeof name === 'function') { func = name; name = '__global__'; } getMiddlewear(this.id, name).push(func); return this; }; /** * Map of provider constructors by index => name * * @type Object */ var providers = []; var getProviders = function(id) { if (!providers[id]) { providers[id] = {}; } return providers[id]; }; /** * Used to process middlewear in the provider * * @param Object instance * @param Function func * @return Mixed */ var reducer = function reducer(instance, func) { return func(instance); }; /** * Register a provider. * * @param String name * @param Function Provider * @return Bottle */ var provider = function provider(name, Provider) { var providerName, providers, properties, container, id; id = this.id; providers = getProviders(id); if (providers[name]) { return console.error(name + ' provider already registered.'); } container = this.container; providers[name] = Provider; providerName = name + 'Provider'; properties = Object.create(null); properties[providerName] = { configurable : true, enumerable : true, get : function getProvider() { var Constructor = providers[name], instance; if (Constructor) { instance = new Constructor(); delete container[providerName]; container[providerName] = instance; } return instance; } }; properties[name] = { configurable : true, enumerable : true, get : function getService() { var provider = container[providerName], instance; if (provider) { instance = provider.$get(container); // filter through middlewear instance = getMiddlewear(id, '__global__') .concat(getMiddlewear(id, name)) .reduce(reducer, instance); delete container[providerName]; delete container[name]; container[name] = instance; } return instance; } }; Object.defineProperties(container, properties); return this; }; /** * Map used to inject dependencies in the generic factory; * * @param String key * @return mixed */ var mapContainer = function mapContainer(key) { return this.container[key]; }; /** * Register a service inside a generic factory. * * @param String name * @param Function Service * @return Bottle */ var service = function service(name, Service) { var deps = arguments.length > 2 ? slice.call(arguments, 1) : null; var bottle = this; return factory.call(bottle, name, function GenericFactory() { if (deps) { Service = Service.bind.apply(Service, deps.map(mapContainer, bottle)); } return new Service(); }); }; /** * Register a value * * @param String name * @param mixed val * @return */ var value = function value(name, val) { Object.defineProperty(this.container, name, { configurable : true, enumerable : true, value : val, writable : true }); return this; }; /** * Bottle constructor */ var Bottle = function Bottle() { if (!(this instanceof Bottle)) { return new Bottle(); } this.id = id++; this.container = {}; }; /** * Bottle prototype */ Bottle.prototype = { constant : constant, factory : factory, middlewear : middlewear, provider : provider, service : service, value : value }; /** * Bottle static */ Bottle.pop = function pop() { return new Bottle(); }; /** * Exports script adapted from lodash v2.4.1 Modern Build * * @see http://lodash.com/ */ /** * Valid object type map * * @type Object */ var objectTypes = { 'function' : true, 'object' : true }; (function exportBottle(root) { /** * Free variable exports * * @type Function */ var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; /** * Free variable module * * @type Object */ var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; /** * CommonJS module.exports * * @type Function */ var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; /** * Free variable `global` * * @type Object */ var freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } /** * Export */ if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) { root.Bottle = Bottle; define(function() { return Bottle; }); } else if (freeExports && freeModule) { if (moduleExports) { (freeModule.exports = Bottle).Bottle = Bottle; } else { freeExports.Bottle = Bottle; } } else { root.Bottle = Bottle; } }((objectTypes[typeof window] && window) || this)); }.call(this));
jonobr1/cdnjs
ajax/libs/bottlejs/0.1.0/bottle.js
JavaScript
mit
7,819
"use strict"; exports.DOMException = require("../web-idl/DOMException"); exports.NamedNodeMap = require("./attributes").NamedNodeMap; exports.Attr = require("./generated/Attr").interface; exports.Node = require("./generated/Node").interface; exports.Element = require("./generated/Element").interface; exports.DocumentFragment = require("./generated/DocumentFragment").interface; exports.Document = exports.HTMLDocument = require("./generated/Document").interface; exports.XMLDocument = require("./generated/XMLDocument").interface; exports.CharacterData = require("./generated/CharacterData").interface; exports.Comment = require("./generated/Comment").interface; exports.DocumentType = require("./generated/DocumentType").interface; exports.DOMImplementation = require("./generated/DOMImplementation").interface; exports.ProcessingInstruction = require("./generated/ProcessingInstruction").interface; exports.Text = require("./generated/Text").interface; exports.Event = require("./generated/Event").interface; exports.CustomEvent = require("./generated/CustomEvent").interface; exports.MessageEvent = require("./generated/MessageEvent").interface; exports.ErrorEvent = require("./generated/ErrorEvent").interface; exports.HashChangeEvent = require("./generated/HashChangeEvent").interface; exports.FocusEvent = require("./generated/FocusEvent").interface; exports.PopStateEvent = require("./generated/PopStateEvent").interface; exports.UIEvent = require("./generated/UIEvent").interface; exports.MouseEvent = require("./generated/MouseEvent").interface; exports.KeyboardEvent = require("./generated/KeyboardEvent").interface; exports.TouchEvent = require("./generated/TouchEvent").interface; exports.ProgressEvent = require("./generated/ProgressEvent").interface; exports.EventTarget = require("./generated/EventTarget").interface; exports.Location = require("./generated/Location").interface; exports.History = require("./generated/History").interface; exports.DOMParser = require("./generated/DOMParser").interface; exports.FormData = require("./generated/FormData").interface; require("./register-elements")(exports); // These need to be cleaned up... require("../level2/style")(exports); require("../level3/xpath")(exports); // These are OK but need migration to webidl2js eventually. require("./html-collection")(exports); require("./node-filter")(exports); require("./node-iterator")(exports); require("./node-list")(exports); exports.Blob = require("./blob"); exports.File = require("./file"); require("./filelist")(exports); require("./xmlhttprequest-event-target")(exports); require("./xmlhttprequest-upload")(exports); exports.DOMTokenList = require("./dom-token-list").DOMTokenList; exports.URL = require("whatwg-url").URL;
ElvisLouis/code
work/js/node_modules/jsdom/lib/jsdom/living/index.js
JavaScript
gpl-2.0
2,747
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v5.0.1 * @link http://www.ag-grid.com/ * @license MIT */ var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var component_1 = require("../widgets/component"); var rowNode_1 = require("../entities/rowNode"); var utils_1 = require('../utils'); var context_1 = require("../context/context"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var svgFactory_1 = require("../svgFactory"); var svgFactory = svgFactory_1.SvgFactory.getInstance(); var CheckboxSelectionComponent = (function (_super) { __extends(CheckboxSelectionComponent, _super); function CheckboxSelectionComponent() { _super.call(this, "<span class=\"ag-selection-checkbox\"/>"); } CheckboxSelectionComponent.prototype.createAndAddIcons = function () { this.eCheckedIcon = utils_1.Utils.createIconNoSpan('checkboxChecked', this.gridOptionsWrapper, null, svgFactory.createCheckboxCheckedIcon); this.eUncheckedIcon = utils_1.Utils.createIconNoSpan('checkboxUnchecked', this.gridOptionsWrapper, null, svgFactory.createCheckboxUncheckedIcon); this.eIndeterminateIcon = utils_1.Utils.createIconNoSpan('checkboxIndeterminate', this.gridOptionsWrapper, null, svgFactory.createCheckboxIndeterminateIcon); var eGui = this.getGui(); eGui.appendChild(this.eCheckedIcon); eGui.appendChild(this.eUncheckedIcon); eGui.appendChild(this.eIndeterminateIcon); }; CheckboxSelectionComponent.prototype.onSelectionChanged = function () { var state = this.rowNode.isSelected(); utils_1.Utils.setVisible(this.eCheckedIcon, state === true); utils_1.Utils.setVisible(this.eUncheckedIcon, state === false); utils_1.Utils.setVisible(this.eIndeterminateIcon, typeof state !== 'boolean'); }; CheckboxSelectionComponent.prototype.onCheckedClicked = function () { this.rowNode.setSelected(false); }; CheckboxSelectionComponent.prototype.onUncheckedClicked = function (event) { this.rowNode.setSelectedParams({ newValue: true, rangeSelect: event.shiftKey }); }; CheckboxSelectionComponent.prototype.onIndeterminateClicked = function (event) { this.rowNode.setSelectedParams({ newValue: true, rangeSelect: event.shiftKey }); }; CheckboxSelectionComponent.prototype.init = function (params) { this.createAndAddIcons(); this.rowNode = params.rowNode; this.onSelectionChanged(); // we don't want the row clicked event to fire when selecting the checkbox, otherwise the row // would possibly get selected twice this.addGuiEventListener('click', function (event) { return event.stopPropagation(); }); // likewise we don't want double click on this icon to open a group this.addGuiEventListener('dblclick', function (event) { return event.stopPropagation(); }); this.addDestroyableEventListener(this.eCheckedIcon, 'click', this.onCheckedClicked.bind(this)); this.addDestroyableEventListener(this.eUncheckedIcon, 'click', this.onUncheckedClicked.bind(this)); this.addDestroyableEventListener(this.eIndeterminateIcon, 'click', this.onIndeterminateClicked.bind(this)); this.addDestroyableEventListener(this.rowNode, rowNode_1.RowNode.EVENT_ROW_SELECTED, this.onSelectionChanged.bind(this)); }; __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper) ], CheckboxSelectionComponent.prototype, "gridOptionsWrapper", void 0); return CheckboxSelectionComponent; })(component_1.Component); exports.CheckboxSelectionComponent = CheckboxSelectionComponent;
redmunds/cdnjs
ajax/libs/ag-grid/5.0.1/lib/rendering/checkboxSelectionComponent.js
JavaScript
mit
4,732
import {cartesian, cartesianAddInPlace, cartesianCross, cartesianDot, cartesianScale, spherical} from "../cartesian"; import {circleStream} from "../circle"; import {abs, cos, epsilon, pi, sqrt} from "../math"; import pointEqual from "../pointEqual"; import clip from "./index"; export default function(radius, delta) { var cr = cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > epsilon; // TODO optimise for this common case function interpolate(from, to, direction, stream) { circleStream(stream, radius, delta, direction, from, to); } function visible(lambda, phi) { return cos(lambda) * cos(phi) > cr; } // Takes a line and cuts into visible segments. Return values used for polygon // clipping: 0 - there were intersections or the line was empty; 1 - no // intersections 2 - there were intersections, and the first and last segments // should be rejoined. function clipLine(stream) { var point0, // previous point c0, // code for previous point v0, // visibility of previous point v00, // visibility of first point clean; // no intersections return { lineStart: function() { v00 = v0 = false; clean = 1; }, point: function(lambda, phi) { var point1 = [lambda, phi], point2, v = visible(lambda, phi), c = smallRadius ? v ? 0 : code(lambda, phi) : v ? code(lambda + (lambda < 0 ? pi : -pi), phi) : 0; if (!point0 && (v00 = v0 = v)) stream.lineStart(); // Handle degeneracies. // TODO ignore if not clipping polygons. if (v !== v0) { point2 = intersect(point0, point1); if (pointEqual(point0, point2) || pointEqual(point1, point2)) { point1[0] += epsilon; point1[1] += epsilon; v = visible(point1[0], point1[1]); } } if (v !== v0) { clean = 0; if (v) { // outside going in stream.lineStart(); point2 = intersect(point1, point0); stream.point(point2[0], point2[1]); } else { // inside going out point2 = intersect(point0, point1); stream.point(point2[0], point2[1]); stream.lineEnd(); } point0 = point2; } else if (notHemisphere && point0 && smallRadius ^ v) { var t; // If the codes for two points are different, or are both zero, // and there this segment intersects with the small circle. if (!(c & c0) && (t = intersect(point1, point0, true))) { clean = 0; if (smallRadius) { stream.lineStart(); stream.point(t[0][0], t[0][1]); stream.point(t[1][0], t[1][1]); stream.lineEnd(); } else { stream.point(t[1][0], t[1][1]); stream.lineEnd(); stream.lineStart(); stream.point(t[0][0], t[0][1]); } } } if (v && (!point0 || !pointEqual(point0, point1))) { stream.point(point1[0], point1[1]); } point0 = point1, v0 = v, c0 = c; }, lineEnd: function() { if (v0) stream.lineEnd(); point0 = null; }, // Rejoin first and last segments if there were intersections and the first // and last points were visible. clean: function() { return clean | ((v00 && v0) << 1); } }; } // Intersects the great circle between a and b with the clip circle. function intersect(a, b, two) { var pa = cartesian(a), pb = cartesian(b); // We have two planes, n1.p = d1 and n2.p = d2. // Find intersection line p(t) = c1 n1 + c2 n2 + t (n1 ⨯ n2). var n1 = [1, 0, 0], // normal n2 = cartesianCross(pa, pb), n2n2 = cartesianDot(n2, n2), n1n2 = n2[0], // cartesianDot(n1, n2), determinant = n2n2 - n1n2 * n1n2; // Two polar points. if (!determinant) return !two && a; var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = cartesianCross(n1, n2), A = cartesianScale(n1, c1), B = cartesianScale(n2, c2); cartesianAddInPlace(A, B); // Solve |p(t)|^2 = 1. var u = n1xn2, w = cartesianDot(A, u), uu = cartesianDot(u, u), t2 = w * w - uu * (cartesianDot(A, A) - 1); if (t2 < 0) return; var t = sqrt(t2), q = cartesianScale(u, (-w - t) / uu); cartesianAddInPlace(q, A); q = spherical(q); if (!two) return q; // Two intersection points. var lambda0 = a[0], lambda1 = b[0], phi0 = a[1], phi1 = b[1], z; if (lambda1 < lambda0) z = lambda0, lambda0 = lambda1, lambda1 = z; var delta = lambda1 - lambda0, polar = abs(delta - pi) < epsilon, meridian = polar || delta < epsilon; if (!polar && phi1 < phi0) z = phi0, phi0 = phi1, phi1 = z; // Check that the first point is between a and b. if (meridian ? polar ? phi0 + phi1 > 0 ^ q[1] < (abs(q[0] - lambda0) < epsilon ? phi0 : phi1) : phi0 <= q[1] && q[1] <= phi1 : delta > pi ^ (lambda0 <= q[0] && q[0] <= lambda1)) { var q1 = cartesianScale(u, (-w + t) / uu); cartesianAddInPlace(q1, A); return [q, spherical(q1)]; } } // Generates a 4-bit vector representing the location of a point relative to // the small circle's bounding box. function code(lambda, phi) { var r = smallRadius ? radius : pi - radius, code = 0; if (lambda < -r) code |= 1; // left else if (lambda > r) code |= 2; // right if (phi < -r) code |= 4; // below else if (phi > r) code |= 8; // above return code; } return clip(visible, clipLine, interpolate, smallRadius ? [0, -radius] : [-pi, radius - pi]); }
rhoon/thesis
work/analysis/node_modules/d3/node_modules/d3-geo/src/clip/circle.js
JavaScript
mit
5,956
!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),(f.ic||(f.ic={})).tabs=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ "use strict"; var TabComponent = _dereq_("./tab")["default"] || _dereq_("./tab"); var TabListComponent = _dereq_("./tab-list")["default"] || _dereq_("./tab-list"); var TabPanelComponent = _dereq_("./tab-panel")["default"] || _dereq_("./tab-panel"); var TabsComponent = _dereq_("./tabs")["default"] || _dereq_("./tabs"); var tabsCssTemplate = _dereq_("./tabs-css")["default"] || _dereq_("./tabs-css"); var Application = window.Ember.Application; Application.initializer({ name: 'ic-tabs', initialize: function(container) { container.register('component:ic-tab', TabComponent); container.register('component:ic-tab-list', TabListComponent); container.register('component:ic-tab-panel', TabPanelComponent); container.register('component:ic-tabs', TabsComponent); container.register('template:components/ic-tabs-css', tabsCssTemplate); } }); exports.TabComponent = TabComponent; exports.TabListComponent = TabListComponent; exports.TabPanelComponent = TabPanelComponent; exports.TabsComponent = TabsComponent; },{"./tab":4,"./tab-list":2,"./tab-panel":3,"./tabs":6,"./tabs-css":5}],2:[function(_dereq_,module,exports){ "use strict"; var Component = window.Ember.Component; var ArrayProxy = window.Ember.ArrayProxy; var computed = window.Ember.computed; exports["default"] = Component.extend({ tagName: 'ic-tab-list', attributeBindings: [ 'role', 'aria-multiselectable' ], /** * See http://www.w3.org/TR/wai-aria/roles#tablist * * @property role * @type String */ role: 'tablist', /** * Tells screenreaders that only one tab can be selected at a time. * * @property 'aria-multiselectable' * @private */ 'aria-multiselectable': false, /** * The currently selected tab. * * @property activeTab */ activeTab: computed.alias('parentView.activeTab'), /** * Registers itself with the ic-tab component. * * @method registerWithTabs * @private */ registerWithTabs: function() { this.get('parentView').registerTabList(this); }.on('didInsertElement'), /** * Storage for all tab components, facilitating keyboard navigation. * * @property tabs * @type ArrayProxy */ tabs: null, /** * Creates the tabs ArrayProxy on init (otherwise would be shared by every * instance) * * @private */ createTabs: function() { this.set('tabs', ArrayProxy.create({content: []})); }.on('init'), /** * Adds a tab to the tabs ArrayProxy. * * @method registerTab * @private */ registerTab: function(tab) { this.get('tabs').addObject(tab); }, unregisterTab: function(tab) { var tabs = this.get('tabs'); var index = tab.get('index'); var parent = this.get('parentView'); tabs.removeObject(tab); if (parent.get('activeTab') == tab) { if (tabs.get('length') === 0) return; var index = (index === 0) ? index : index - 1; var tab = tabs.objectAt(index); parent.select(tab); } }, /** * Sets up keyboard navigation. * * @method navigateOnKeyDown * @private */ navigateOnKeyDown: function(event) { var key = event.keyCode; if (key == 37 /*<*/ || key == 38 /*^*/) { this.selectPrevious(); } else if (key == 39 /*>*/ || key == 40 /*v*/) { this.selectNext(); } else { return; } event.preventDefault(); }.on('keyDown'), /** * Tracks the index of the active tab so we can select previous/next. * * @property activeTabIndex * @type Number */ activeTabIndex: function() { return this.get('tabs').indexOf(this.get('activeTab')); }.property('activeTab'), /** * Selects the next tab in the list, or loops to the beginning. * * @method selectNext * @private */ selectNext: function() { var index = this.get('activeTabIndex') + 1; if (index == this.get('tabs.length')) { index = 0; } this.selectTabAtIndex(index); }, /** * Selects the previous tab in the list, or loops to the end. * * @method selectPrevious * @private */ selectPrevious: function() { var index = this.get('activeTabIndex') - 1; if (index == -1) { index = this.get('tabs.length') - 1; } this.selectTabAtIndex(index); }, /** * Selects a tab at an index. * * @method selectTabAtIndex * @private */ selectTabAtIndex: function(index) { var tab = this.get('tabs').objectAt(index); tab.select({focus: true}); } }); },{}],3:[function(_dereq_,module,exports){ "use strict"; var Component = window.Ember.Component; var computed = window.Ember.computed; exports["default"] = Component.extend({ tagName: 'ic-tab-panel', attributeBindings: [ 'role', 'aria-labeledby' ], // TODO: remove this, toggleVisibility won't fire w/o it though (?) classNameBindings: ['active'], /** * See http://www.w3.org/TR/wai-aria/roles#tabpanel * * @property role * @type String * @private */ role: 'tabpanel', /** * Reference to the TabListComponent instance, used so we can find the * associated tab. * * @property tabList * @type TabListComponent * @private */ tabList: computed.alias('parentView.tabList'), /** * Reference to the ArrayProxy of TabPanelComponent instances. * * @property tabPanels * @type ArrayProxy * @private */ tabPanels: computed.alias('parentView.tabPanels'), /** * Tells screenreaders which tab labels this panel. * * @property 'aria-labeledby' * @type String * @private */ 'aria-labeledby': computed.alias('tab.elementId'), /** * Reference to this panel's associated tab. * * @property tab * @type TabComponent */ tab: function() { var index = this.get('tabPanels').indexOf(this); var tabs = this.get('tabList.tabs'); return tabs && tabs.objectAt(index); }.property('tabList.tabs.@each'), /** * Tells whether or not this panel is active. * * @property active * @type Boolean */ active: function() { return this.get('tab.active'); }.property('tab.active'), /** * Shows or hides this panel depending on whether or not its active. * * @method toggleVisibility * @private */ toggleVisibility: function() { var display = this.get('active') ? '' : 'none'; this.$().css('display', display); }.observes('active'), /** * Registers with the TabsComponent. * * @method registerWithTabs * @private */ registerWithTabs: function() { this.get('parentView').registerTabPanel(this); }.on('didInsertElement'), unregisterWithTabs: function() { this.get('parentView').unregisterTabPanel(this); }.on('willDestroyElement') }); },{}],4:[function(_dereq_,module,exports){ "use strict"; var Component = window.Ember.Component; var computed = window.Ember.computed; var alias = computed.alias; exports["default"] = Component.extend({ tagName: 'ic-tab', attributeBindings: [ 'role', 'aria-controls', 'aria-selected', 'aria-expanded', 'tabindex', 'selected' ], /** * See http://www.w3.org/TR/wai-aria/roles#tab * * @property role * @type String * @private */ role: 'tab', /** * Sets the [selected] attribute on the element when this tab is active. * Makes sure to remove the attribute completely when not selected. * * @property selected * @type Boolean */ selected: function() { return this.get('active') ? 'selected' : null; }.property('active'), /** * Makes the selected tab keyboard tabbable, also prevents tabs from getting * focus when clicked with a mouse. * * @property tabindex * @type Number */ tabindex: function() { return this.get('active') ? 0 : null; }.property('active'), /** * Reference to the parent TabsComponent instance. * * @property tabs * @type TabsComponent */ tabs: alias('parentView.parentView'), /** * Reference to the parent TabListComponent instance. * * @property tabs * @type TabList */ tabList: alias('parentView'), /** * Tells screenreaders which panel this tab controls. * * @property 'aria-controls' * @type String * @private */ 'aria-controls': alias('tabPanel.elementId'), /** * Tells screenreaders whether or not this tab is selected. * * @property 'aria-selected' * @type String * @private */ 'aria-selected': function() { // coerce to ensure a "true" or "false" attribute value return this.get('active')+''; }.property('active'), /** * Tells screenreaders whether or not this tabs panel is expanded. * * @property 'aria-expanded' * @type String * @private */ 'aria-expanded': alias('aria-selected'), /** * Whether or not this tab is selected. * * @property active * @type Boolean */ active: function(key, val) { return this.get('tabs.activeTab') === this; }.property('tabs.activeTab'), /** * Selects this tab, bound to click. * * @method select * @param [options] * @param {*} [options.focus] - focuses the element when selected. */ select: function(options) { this.get('tabs').select(this); if (options && options.focus) { Ember.run.schedule('afterRender', this, function() { this.$().focus(); }); } }.on('click'), /** * The index of this tab in the TabListComponent instance. * * @property index * @type Number */ index: function() { return this.get('tabList.tabs').indexOf(this); }.property('tabList.tabs.@each'), /** * Reference to the associated TabPanel instance. * * @property tabPanel * @type TabPanelComponent */ tabPanel: function() { var index = this.get('index'); var panels = this.get('tabs.tabPanels'); return panels && panels.objectAt(index); }.property('tabs.tabPanels.@each'), /** * Selects this tab when the TabsComponent selected-index property matches * the index of this tab. Mostly useful for query-params support. * * @method selectFromTabsSelectedIndex * @private */ selectFromTabsSelectedIndex: function() { var activeTab = this.get('tabs.activeTab'); if (activeTab === this) return; // this was just selected var index = parseInt(this.get('tabs.selected-index'), 10); var myIndex = this.get('index'); if (index === myIndex) { this.select(); } }.observes('tabs.selected-index').on('didInsertElement'), /** * Registers this tab with the TabListComponent instance. * * @method registerWithTabList * @private */ registerWithTabList: function() { this.get('tabList').registerTab(this); }.on('didInsertElement'), unregisterWithTabList: function() { this.get('tabList').unregisterTab(this); }.on('willDestroyElement') }); },{}],5:[function(_dereq_,module,exports){ "use strict"; var Ember = window.Ember["default"] || window.Ember; exports["default"] = Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Ember.Handlebars.helpers); data = data || {}; data.buffer.push("ic-tabs,\nic-tab-list,\nic-tab-panel {\n display: block\n}\n\nic-tab-list {\n border-bottom: 1px solid #aaa;\n}\n\nic-tab {\n display: inline-block;\n padding: 6px 12px;\n border: 1px solid transparent;\n border-top-left-radius: 3px;\n border-top-right-radius: 3px;\n cursor: pointer;\n margin-bottom: -1px;\n position: relative;\n}\n\nic-tab[selected] {\n border-color: #aaa;\n border-bottom-color: #fff;\n}\n\nic-tab:focus {\n box-shadow: 0 10px 0 0 #fff,\n 0 0 5px hsl(208, 99%, 50%);\n border-color: hsl(208, 99%, 50%);\n border-bottom-color: #fff;\n outline: none;\n}\n\nic-tab:focus:before,\nic-tab:focus:after {\n content: '';\n position: absolute;\n bottom: -6px;\n width: 5px;\n height: 5px;\n background: #fff;\n}\n\nic-tab:focus:before {\n left: -4px;\n}\n\nic-tab:focus:after {\n right: -4px;\n}\n\n"); }); },{}],6:[function(_dereq_,module,exports){ "use strict"; var Component = window.Ember.Component; var ArrayProxy = window.Ember.ArrayProxy; var computed = window.Ember.computed; exports["default"] = Component.extend({ tagName: 'ic-tabs', /** * The selected TabComponent instance. * * @property activeTab * @type TabComponent */ activeTab: null, /** * The TabPanelComponent instances. * * @property tabPanels * @type ArrayProxy */ tabPanels: null, /** * Set this to the tab you'd like to be active. Usually it is bound to a * controller property that is used as a query parameter, but can be bound to * anything. * * @property 'selected-index' * @type Number */ 'selected-index': 0, /** * Creates the `tabPanels` ArrayProxy. * * @method createTabPanels * @private */ createTabPanels: function(tabList) { this.set('tabPanels', ArrayProxy.create({content: []})); }.on('init'), /** * Selects a tab. * * @method select */ select: function(tab) { this.set('activeTab', tab); this.set('selected-index', tab.get('index')); }, /** * Registers the TabListComponent instance. * * @method registerTabList * @private */ registerTabList: function(tabList) { this.set('tabList', tabList); }, /** * Registers TabPanelComponent instances so related components can access * them. * * @method registerTabPanel * @private */ registerTabPanel: function(tabPanel) { this.get('tabPanels').addObject(tabPanel); }, unregisterTabPanel: function(tabPanel) { this.get('tabPanels').removeObject(tabPanel); } }); },{}]},{},[1]) (1) });
ajpi222/canvas-lms-hdi
public/javascripts/bower/ic-tabs/dist/globals/main.js
JavaScript
agpl-3.0
14,526
/** * @fileoverview HTML reporter * @author Julian Laval */ "use strict"; const lodash = require("lodash"); const fs = require("fs"); const path = require("path"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ const pageTemplate = lodash.template(fs.readFileSync(path.join(__dirname, "html-template-page.html"), "utf-8")); const messageTemplate = lodash.template(fs.readFileSync(path.join(__dirname, "html-template-message.html"), "utf-8")); const resultTemplate = lodash.template(fs.readFileSync(path.join(__dirname, "html-template-result.html"), "utf-8")); /** * Given a word and a count, append an s if count is not one. * @param {string} word A word in its singular form. * @param {int} count A number controlling whether word should be pluralized. * @returns {string} The original word with an s on the end if count is not one. */ function pluralize(word, count) { return (count === 1 ? word : `${word}s`); } /** * Renders text along the template of x problems (x errors, x warnings) * @param {string} totalErrors Total errors * @param {string} totalWarnings Total warnings * @returns {string} The formatted string, pluralized where necessary */ function renderSummary(totalErrors, totalWarnings) { const totalProblems = totalErrors + totalWarnings; let renderedText = `${totalProblems} ${pluralize("problem", totalProblems)}`; if (totalProblems !== 0) { renderedText += ` (${totalErrors} ${pluralize("error", totalErrors)}, ${totalWarnings} ${pluralize("warning", totalWarnings)})`; } return renderedText; } /** * Get the color based on whether there are errors/warnings... * @param {string} totalErrors Total errors * @param {string} totalWarnings Total warnings * @returns {int} The color code (0 = green, 1 = yellow, 2 = red) */ function renderColor(totalErrors, totalWarnings) { if (totalErrors !== 0) { return 2; } if (totalWarnings !== 0) { return 1; } return 0; } /** * Get HTML (table rows) describing the messages. * @param {Array} messages Messages. * @param {int} parentIndex Index of the parent HTML row. * @returns {string} HTML (table rows) describing the messages. */ function renderMessages(messages, parentIndex) { /** * Get HTML (table row) describing a message. * @param {Object} message Message. * @returns {string} HTML (table row) describing a message. */ return lodash.map(messages, message => { const lineNumber = message.line || 0; const columnNumber = message.column || 0; return messageTemplate({ parentIndex, lineNumber, columnNumber, severityNumber: message.severity, severityName: message.severity === 1 ? "Warning" : "Error", message: message.message, ruleId: message.ruleId }); }).join("\n"); } /** * @param {Array} results Test results. * @returns {string} HTML string describing the results. */ function renderResults(results) { return lodash.map(results, (result, index) => resultTemplate({ index, color: renderColor(result.errorCount, result.warningCount), filePath: result.filePath, summary: renderSummary(result.errorCount, result.warningCount) }) + renderMessages(result.messages, index)).join("\n"); } //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ module.exports = function(results) { let totalErrors, totalWarnings; totalErrors = 0; totalWarnings = 0; // Iterate over results to get totals results.forEach(result => { totalErrors += result.errorCount; totalWarnings += result.warningCount; }); return pageTemplate({ date: new Date(), reportColor: renderColor(totalErrors, totalWarnings), reportSummary: renderSummary(totalErrors, totalWarnings), results: renderResults(results) }); };
EdwardStudy/myghostblog
versions/1.25.7/node_modules/eslint/lib/formatters/html.js
JavaScript
mit
4,182
module.exports = { prefix: 'fas', iconName: 'neuter', icon: [288, 512, [], "f22c", "M288 176c0-79.5-64.5-144-144-144S0 96.5 0 176c0 68.5 47.9 125.9 112 140.4V468c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12V316.4c64.1-14.5 112-71.9 112-140.4zm-144 80c-44.1 0-80-35.9-80-80s35.9-80 80-80 80 35.9 80 80-35.9 80-80 80z"] };
evepraisal/go-evepraisal
web/resources/static/thirdparty/fontawesome-free-5.0.8/advanced-options/use-with-node-js/fontawesome-free-solid/faNeuter.js
JavaScript
mit
316
define(function () { return {"zones":{"Etc/GMT+2":["z",{"wallclock":-1.7976931348623157e+308,"format":"GMT+2","abbrev":"GMT+2","offset":-7200000,"posix":-1.7976931348623157e+308,"save":0}]},"rules":{}} });
Rvor/canvas-lms
public/javascripts/vendor/timezone/Etc/GMT+2.js
JavaScript
agpl-3.0
205
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), CollectionGroup = _dereq_('../lib/CollectionGroup'), View = _dereq_('../lib/View'), Highchart = _dereq_('../lib/Highchart'), Persist = _dereq_('../lib/Persist'), Document = _dereq_('../lib/Document'), Overview = _dereq_('../lib/Overview'), OldView = _dereq_('../lib/OldView'), OldViewBind = _dereq_('../lib/OldView.Bind'), Grid = _dereq_('../lib/Grid'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/CollectionGroup":6,"../lib/Core":7,"../lib/Document":9,"../lib/Grid":11,"../lib/Highchart":12,"../lib/OldView":29,"../lib/OldView.Bind":28,"../lib/Overview":32,"../lib/Persist":34,"../lib/View":40}],2:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver; /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; this._keyArr = sharedPathSolver.parse(orderBy, true); }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); sharedPathSolver = new Path(); /** * Gets / sets the primary key used by the active bucket. * @returns {String} The current primary key. */ Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof sharedPathSolver.get(obj, sortType.path); if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.value === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.value === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += sharedPathSolver.get(obj, sortType.path); } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Path":33,"./Shared":39}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver = new Path(); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) { this._store = []; this._keys = []; if (primaryKey !== undefined) { this.primaryKey(primaryKey); } if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'primaryKey'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (this.debug()) { console.log('Setting index', index, sharedPathSolver.parse(index, true)); } // Convert the index object to an array of key val objects this.keys(sharedPathSolver.parse(index, true)); } return this.$super.call(this, index); }); /** * Remove all data from the binary tree. */ BinaryTree.prototype.clear = function () { delete this._data; delete this._left; delete this._right; this._store = []; }; /** * Sets this node's data object. All further inserted documents that * match this node's key and value will be pushed via the push() * method into the this._store array. When deciding if a new data * should be created left, right or middle (pushed) of this node the * new data is checked against the data set via this method. * @param val * @returns {*} */ BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.value === 1) { result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (this.debug()) { console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result); } if (result !== 0) { if (this.debug()) { console.log('Retuning result %d', result); } return result; } } if (this.debug()) { console.log('Retuning result %d', result); } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.path]; } return hash;*/ return obj[this._keys[0].path]; }; /** * Removes (deletes reference to) either left or right child if the passed * node matches one of them. * @param {BinaryTree} node The node to remove. */ BinaryTree.prototype.removeChildNode = function (node) { if (this._left === node) { // Remove left delete this._left; } else if (this._right === node) { // Remove right delete this._right; } }; /** * Returns the branch this node matches (left or right). * @param node * @returns {String} */ BinaryTree.prototype.nodeBranch = function (node) { if (this._left === node) { return 'left'; } else if (this._right === node) { return 'right'; } }; /** * Inserts a document into the binary tree. * @param data * @returns {*} */ BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (this.debug()) { console.log('Inserting', data); } if (!this._data) { if (this.debug()) { console.log('Node has no data, setting data', data); } // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { if (this.debug()) { console.log('Data is equal (currrent, new)', this._data, data); } //this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } if (result === -1) { if (this.debug()) { console.log('Data is greater (currrent, new)', this._data, data); } // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._right._parent = this; } return true; } if (result === 1) { if (this.debug()) { console.log('Data is less (currrent, new)', this._data, data); } // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } return false; }; BinaryTree.prototype.remove = function (data) { var pk = this.primaryKey(), result, removed, i; if (data instanceof Array) { // Insert array of data removed = []; for (i = 0; i < data.length; i++) { if (this.remove(data[i])) { removed.push(data[i]); } } return removed; } if (this.debug()) { console.log('Removing', data); } if (this._data[pk] === data[pk]) { // Remove this node return this._remove(this); } // Compare the data to work out which branch to send the remove command down result = this._compareFunc(this._data, data); if (result === -1 && this._right) { return this._right.remove(data); } if (result === 1 && this._left) { return this._left.remove(data); } return false; }; BinaryTree.prototype._remove = function (node) { var leftNode, rightNode; if (this._left) { // Backup branch data leftNode = this._left; rightNode = this._right; // Copy data from left node this._left = leftNode._left; this._right = leftNode._right; this._data = leftNode._data; this._store = leftNode._store; if (rightNode) { // Attach the rightNode data to the right-most node // of the leftNode leftNode.rightMost()._right = rightNode; } } else if (this._right) { // Backup branch data rightNode = this._right; // Copy data from right node this._left = rightNode._left; this._right = rightNode._right; this._data = rightNode._data; this._store = rightNode._store; } else { this.clear(); } return true; }; BinaryTree.prototype.leftMost = function () { if (!this._left) { return this; } else { return this._left.leftMost(); } }; BinaryTree.prototype.rightMost = function () { if (!this._right) { return this; } else { return this._right.rightMost(); } }; /** * Searches the binary tree for all matching documents based on the data * passed (query). * @param data * @param options * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visited === undefined) { resultArr._visited = 0; } resultArr._visited++; result = this.sortAsc(thisDataPathVal, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":33,"./Shared":39}],4:[function(_dereq_,module,exports){ "use strict"; var crcTable, checksum; crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); /** * Returns a checksum of a string. * @param {String} str The string to checksum. * @return {Number} The checksum generated. */ checksum = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; module.exports = checksum; },{}],5:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Overload, ReactorIO, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this.sharedPathSolver = sharedPathSolver; this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); sharedPathSolver = new Path(); /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. */ Shared.synthesize(Collection.prototype, 'cappedSize'); Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback.call(this, false, true); } return true; } } else { if (callback) { callback.call(this, false, true); } return true; } if (callback) { callback.call(this, false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', { keyName: keyName, oldData: oldKey }); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = this.serialiser.convert(new Date()); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = new Overload('Collection.prototype.setData', { '*': function (data) { return this.$main.call(this, data, {}); }, '*, object': function (data, options) { return this.$main.call(this, data, options); }, '*, function': function (data, callback) { return this.$main.call(this, data, {}, callback); }, '*, *, function': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, '*, *, *': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, '$main': function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var deferredSetting = this.deferredCalls(), oldData = [].concat(this._data); // Switch off deferred calls since setData should be // a synchronous call this.deferredCalls(false); options = this.options(options); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } // Remove all items from the collection this.remove({}); // Insert the new data this.insert(data); // Switch deferred calls back to previous settings this.deferredCalls(deferredSetting); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback.call(this); } return this; } }); /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a hash string jString = this.hash(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This should use remove so that chain reactor events are properly // TODO: handled, but ensure that chunking is switched off this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.emit('immediateChange', {type: 'truncate'}); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback.call(this); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj, callback); break; case 'update': returnData.result = this.update(query, obj, {}, callback); break; default: break; } return returnData; } else { if (callback) { callback.call(this); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when the update is * complete. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } else { // Decouple the update data update = this.decouple(update); } // Handle transform update = this.transformIn(update); return this._handleUpdate(query, update, options, callback); }; Collection.prototype._handleUpdate = function (query, update, options, callback) { var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); if (this.chainWillSend()) { this.chainSend('update', { query: query, update: update, dataSet: this.decouple(updated) }, options); } op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); if (callback) { callback.call(this); } this.emit('immediateChange', {type: 'update', data: updated}); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback.call(this, false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.emit('immediateChange', {type: 'remove', data: returnArr}); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback.call(this, false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback.call(this, resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback.call(this, resultObj); } this._onChange(); this.emit('immediateChange', {type: 'insert', data: inserted}); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); if (self.chainWillSend()) { self.chainSend('insert', { dataSet: self.decouple([doc]) }, { index: index }); } //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, hash = this.hash(doc), pk = this._primaryKey; // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[pk], doc); this._primaryCrc.uniqueSet(doc[pk], hash); this._crcLookup.uniqueSet(hash, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, hash = this.hash(doc), pk = this._primaryKey; // Remove from primary key index this._primaryIndex.unSet(doc[pk]); this._primaryCrc.unSet(doc[pk]); this._crcLookup.unSet(hash); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinIndex, joinSource = {}, joinQuery, joinPath, joinSourceKey, joinSourceType, joinSourceIdentifier, joinSourceData, resultRemove = [], i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); // Check if the query tries to limit by data that would only exist after // the join operation has been completed if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get references to the join sources op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinSourceData = analysis.joinsOn[joinIndex]; joinSourceKey = joinSourceData.key; joinSourceType = joinSourceData.type; joinSourceIdentifier = joinSourceData.id; joinPath = new Path(analysis.joinQueries[joinSourceKey]); joinQuery = joinPath.value(query)[0]; joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinSourceKey]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource)); op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); this.spliceArrayByIndexList(resultArr, resultRemove); op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ /*Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; };*/ /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinSourceIndex, joinSourceKey, joinSourceType, joinSourceIdentifier, joinMatch, joinSources = [], joinSourceReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) { // Loop the join sources and keep a reference to them for (joinSourceKey in options.$join[joinSourceIndex]) { if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) { joinMatch = options.$join[joinSourceIndex][joinSourceKey]; joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; joinSources.push({ id: joinSourceIdentifier, type: joinSourceType, key: joinSourceKey }); // Check if the join uses an $as operator if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) { joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as); } else { joinSourceReferences.push(joinSourceKey); } } } } // Loop the join source references and determine if the query references // any of the sources that are used in the join. If there no queries against // joined sources the find method can use a code path optimised for this. // Queries against joined sources requires the joined sources to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinSourceReferences.length; index++) { // Check if the query references any source data that the join will create queryPath = this._queryReferencesSource(query, joinSourceReferences[index], ''); if (queryPath) { analysis.joinQueries[joinSources[index].key] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinSources; analysis.queriesOn = analysis.queriesOn.concat(joinSources); } return analysis; }; /** * Checks if the passed query references a source object (such * as a collection) by name. * @param {Object} query The query object to scan. * @param {String} sourceName The source name to scan for in the query. * @param {String=} path The path to scan from. * @returns {*} * @private */ Collection.prototype._queryReferencesSource = function (query, sourceName, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === sourceName) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesSource(query[i], sourceName, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents that matches * the subDocQuery parameter. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { if (options.type) { // Check if the specified type is available if (Shared.index[options.type]) { // We found the type, generate it index = new Shared.index[options.type](keys, options, this); } else { throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)'); } } else { // Create default index type index = new IndexHashMap(keys, options, this); } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', { /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data.dataSet); self.update({}, obj1); } else { self.insert(packet.data.dataSet); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data.dataSet); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload('Db.prototype.collection', { /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Index2d":13,"./IndexBinaryTree":14,"./IndexHashMap":15,"./KeyValueStore":16,"./Metrics":17,"./Overload":31,"./Path":33,"./ReactorIO":37,"./Shared":39}],6:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Events'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {String=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Remove old data this._data.remove(chainPacket.data.oldData); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); delete this._listeners; if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; /** * Creates a new collectionGroup instance or returns an existing * instance if one already exists with the passed name. * @func collectionGroup * @memberOf Db * @param {String} name The name of the instance. * @returns {*} */ Db.prototype.collectionGroup = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof CollectionGroup) { return name; } if (this._collectionGroup && this._collectionGroup[name]) { return this._collectionGroup[name]; } this._collectionGroup[name] = new CollectionGroup(name).db(this); self.emit('create', self._collectionGroup[name], 'collectionGroup', name); return this._collectionGroup[name]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":5,"./Shared":39}],7:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (val) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":8,"./Metrics.js":17,"./Overload":31,"./Shared":39}],8:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Checksum, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Checksum = _dereq_('./Checksum.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.Checksum = Checksum; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Checksum.js":4,"./Collection.js":5,"./Metrics.js":17,"./Overload":31,"./Shared":39}],9:[function(_dereq_,module,exports){ "use strict"; // TODO: Remove the _update* methods because we are already mixing them // TODO: in now via Mixin.Updating and update autobind to extend the _update* // TODO: methods like we already do with collection var Shared, Collection, Db; Shared = _dereq_('./Shared'); /** * Creates a new Document instance. Documents allow you to create individual * objects that can have standard ForerunnerDB CRUD operations run against * them, as well as data-binding if the AutoBind module is included in your * project. * @name Document * @class Document * @constructor */ var FdbDocument = function () { this.init.apply(this, arguments); }; FdbDocument.prototype.init = function (name) { this._name = name; this._data = {}; }; Shared.addModule('Document', FdbDocument); Shared.mixin(FdbDocument.prototype, 'Mixin.Common'); Shared.mixin(FdbDocument.prototype, 'Mixin.Events'); Shared.mixin(FdbDocument.prototype, 'Mixin.ChainReactor'); Shared.mixin(FdbDocument.prototype, 'Mixin.Constants'); Shared.mixin(FdbDocument.prototype, 'Mixin.Triggers'); Shared.mixin(FdbDocument.prototype, 'Mixin.Matching'); Shared.mixin(FdbDocument.prototype, 'Mixin.Updating'); Shared.mixin(FdbDocument.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; /** * Gets / sets the current state. * @func state * @memberof Document * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'state'); /** * Gets / sets the db instance this class instance belongs to. * @func db * @memberof Document * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'db'); /** * Gets / sets the document name. * @func name * @memberof Document * @param {String=} val The name to assign * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'name'); /** * Sets the data for the document. * @func setData * @memberof Document * @param data * @param options * @returns {Document} */ FdbDocument.prototype.setData = function (data, options) { var i, $unset; if (data) { options = options || { $decouple: true }; if (options && options.$decouple === true) { data = this.decouple(data); } if (this._linked) { $unset = {}; // Remove keys that don't exist in the new data from the current object for (i in this._data) { if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) { // Check if existing data has key if (data[i] === undefined) { // Add property name to those to unset $unset[i] = 1; } } } data.$unset = $unset; // Now update the object with new data this.updateObject(this._data, data, {}); } else { // Straight data assignment this._data = data; } this.deferEmit('change', {type: 'setData', data: this.decouple(this._data)}); } return this; }; /** * Gets the document's data returned as a single object. * @func find * @memberof Document * @param {Object} query The query object - currently unused, just * provide a blank object e.g. {} * @param {Object=} options An options object. * @returns {Object} The document's data object. */ FdbDocument.prototype.find = function (query, options) { var result; if (options && options.$decouple === false) { result = this._data; } else { result = this.decouple(this._data); } return result; }; /** * Modifies the document. This will update the document with the data held in 'update'. * @func update * @memberof Document * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ FdbDocument.prototype.update = function (query, update, options) { var result = this.updateObject(this._data, update, query, options); if (result) { this.deferEmit('change', {type: 'update', data: this.decouple(this._data)}); } }; /** * Internal method for document updating. * @func updateObject * @memberof Document * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ FdbDocument.prototype.updateObject = Collection.prototype.updateObject; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @func _isPositionalKey * @memberof Document * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ FdbDocument.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Updates a property on an object depending on if the collection is * currently running data-binding or not. * @func _updateProperty * @memberof Document * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ FdbDocument.prototype._updateProperty = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, val); if (this.debug()) { console.log(this.logIdentifier() + ' Setting data-bound document property "' + prop + '"'); } } else { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"'); } } }; /** * Increments a value for a property on a document by the passed number. * @func _updateIncrement * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ FdbDocument.prototype._updateIncrement = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, doc[prop] + val); } else { doc[prop] += val; } }; /** * Changes the index of an item in the passed array. * @func _updateSpliceMove * @memberof Document * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ FdbDocument.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) { if (this._linked) { window.jQuery.observable(arr).move(indexFrom, indexTo); if (this.debug()) { console.log(this.logIdentifier() + ' Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } } else { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } } }; /** * Inserts an item into the passed array at the specified index. * @func _updateSplicePush * @memberof Document * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ FdbDocument.prototype._updateSplicePush = function (arr, index, doc) { if (arr.length > index) { if (this._linked) { window.jQuery.observable(arr).insert(index, doc); } else { arr.splice(index, 0, doc); } } else { if (this._linked) { window.jQuery.observable(arr).insert(doc); } else { arr.push(doc); } } }; /** * Inserts an item at the end of an array. * @func _updatePush * @memberof Document * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ FdbDocument.prototype._updatePush = function (arr, doc) { if (this._linked) { window.jQuery.observable(arr).insert(doc); } else { arr.push(doc); } }; /** * Removes an item from the passed array. * @func _updatePull * @memberof Document * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ FdbDocument.prototype._updatePull = function (arr, index) { if (this._linked) { window.jQuery.observable(arr).remove(index); } else { arr.splice(index, 1); } }; /** * Multiplies a value for a property on a document by the passed number. * @func _updateMultiply * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ FdbDocument.prototype._updateMultiply = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, doc[prop] * val); } else { doc[prop] *= val; } }; /** * Renames a property on a document to the passed property. * @func _updateRename * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ FdbDocument.prototype._updateRename = function (doc, prop, val) { var existingVal = doc[prop]; if (this._linked) { window.jQuery.observable(doc).setProperty(val, existingVal); window.jQuery.observable(doc).removeProperty(prop); } else { doc[val] = existingVal; delete doc[prop]; } }; /** * Deletes a property on a document. * @func _updateUnset * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ FdbDocument.prototype._updateUnset = function (doc, prop) { if (this._linked) { window.jQuery.observable(doc).removeProperty(prop); } else { delete doc[prop]; } }; /** * Drops the document. * @func drop * @memberof Document * @returns {boolean} True if successful, false if not. */ FdbDocument.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._db && this._name) { if (this._db && this._db._document && this._db._document[this._name]) { this._state = 'dropped'; delete this._db._document[this._name]; delete this._data; this.emit('drop', this); if (callback) { callback(false, true); } delete this._listeners; return true; } } } else { return true; } return false; }; /** * Creates a new document instance or returns an existing * instance if one already exists with the passed name. * @func document * @memberOf Db * @param {String} name The name of the instance. * @returns {*} */ Db.prototype.document = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof FdbDocument) { if (name.state() !== 'droppped') { return name; } else { name = name.name(); } } if (this._document && this._document[name]) { return this._document[name]; } this._document = this._document || {}; this._document[name] = new FdbDocument(name).db(this); self.emit('create', self._document[name], 'document', name); return this._document[name]; } else { // Return an object of document data return this._document; } }; /** * Returns an array of documents the DB currently has. * @func documents * @memberof Db * @returns {Array} An array of objects containing details of each document * the database is currently managing. */ Db.prototype.documents = function () { var arr = [], item, i; for (i in this._document) { if (this._document.hasOwnProperty(i)) { item = this._document[i]; arr.push({ name: i, linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Document'); module.exports = FdbDocument; },{"./Collection":5,"./Shared":39}],10:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - rob@irrelon.com "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders; bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to longitude/latitude. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { latitude: lat, longitude: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; module.exports = GeoHash; },{}],11:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, View, CollectionInit, DbInit, ReactorIO; //Shared = ForerunnerDB.shared; Shared = _dereq_('./Shared'); /** * Creates a new grid instance. * @name Grid * @class Grid * @param {String} selector jQuery selector. * @param {String} template The template selector. * @param {Object=} options The options object to apply to the grid. * @constructor */ var Grid = function (selector, template, options) { this.init.apply(this, arguments); }; Grid.prototype.init = function (selector, template, options) { var self = this; this._selector = selector; this._template = template; this._options = options || {}; this._debug = {}; this._id = this.objectId(); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; }; Shared.addModule('Grid', Grid); Shared.mixin(Grid.prototype, 'Mixin.Common'); Shared.mixin(Grid.prototype, 'Mixin.ChainReactor'); Shared.mixin(Grid.prototype, 'Mixin.Constants'); Shared.mixin(Grid.prototype, 'Mixin.Triggers'); Shared.mixin(Grid.prototype, 'Mixin.Events'); Shared.mixin(Grid.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); View = _dereq_('./View'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @func state * @memberof Grid * @param {String=} val The name of the state to set. * @returns {Grid} */ Shared.synthesize(Grid.prototype, 'state'); /** * Gets / sets the current name. * @func name * @memberof Grid * @param {String=} val The name to set. * @returns {Grid} */ Shared.synthesize(Grid.prototype, 'name'); /** * Executes an insert against the grid's underlying data-source. * @func insert * @memberof Grid */ Grid.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the grid's underlying data-source. * @func update * @memberof Grid */ Grid.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the grid's underlying data-source. * @func updateById * @memberof Grid */ Grid.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the grid's underlying data-source. * @func remove * @memberof Grid */ Grid.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Sets the collection from which the grid will assemble its data. * @func from * @memberof Grid * @param {Collection} collection The collection to use to assemble grid data. * @returns {Grid} */ Grid.prototype.from = function (collection) { //var self = this; if (collection !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); this._from._removeGrid(this); } if (typeof(collection) === 'string') { collection = this._db.collection(collection); } this._from = collection; this._from.on('drop', this._collectionDroppedWrap); this.refresh(); } return this; }; /** * Gets / sets the db instance this class instance belongs to. * @func db * @memberof Grid * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Grid.prototype, 'db', function (db) { if (db) { // Apply the same debug settings this.debug(db.debug()); } return this.$super.apply(this, arguments); }); Grid.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from grid delete this._from; } }; /** * Drops a grid and all it's stored data from the database. * @func drop * @memberof Grid * @returns {boolean} True on success, false on failure. */ Grid.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { // Remove data-binding this._from.unlink(this._selector, this.template()); // Kill listeners and references this._from.off('drop', this._collectionDroppedWrap); this._from._removeGrid(this); if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping grid ' + this._selector); } this._state = 'dropped'; if (this._db && this._selector) { delete this._db._grid[this._selector]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._selector; delete this._template; delete this._from; delete this._db; delete this._listeners; return true; } } else { return true; } return false; }; /** * Gets / sets the grid's HTML template to use when rendering. * @func template * @memberof Grid * @param {Selector} template The template's jQuery selector. * @returns {*} */ Grid.prototype.template = function (template) { if (template !== undefined) { this._template = template; return this; } return this._template; }; Grid.prototype._sortGridClick = function (e) { var elem = window.jQuery(e.currentTarget), sortColText = elem.attr('data-grid-sort') || '', sortColDir = parseInt((elem.attr('data-grid-dir') || "-1"), 10) === -1 ? 1 : -1, sortCols = sortColText.split(','), sortObj = {}, i; // Remove all grid sort tags from the grid window.jQuery(this._selector).find('[data-grid-dir]').removeAttr('data-grid-dir'); // Flip the sort direction elem.attr('data-grid-dir', sortColDir); for (i = 0; i < sortCols.length; i++) { sortObj[sortCols] = sortColDir; } Shared.mixin(sortObj, this._options.$orderBy); this._from.orderBy(sortObj); this.emit('sort', sortObj); }; /** * Refreshes the grid data such as ordering etc. * @func refresh * @memberof Grid */ Grid.prototype.refresh = function () { if (this._from) { if (this._from.link) { var self = this, elem = window.jQuery(this._selector), sortClickListener = function () { self._sortGridClick.apply(self, arguments); }; // Clear the container elem.html(''); if (self._from.orderBy) { // Remove listeners elem.off('click', '[data-grid-sort]', sortClickListener); } if (self._from.query) { // Remove listeners elem.off('click', '[data-grid-filter]', sortClickListener); } // Set wrap name if none is provided self._options.$wrap = self._options.$wrap || 'gridRow'; // Auto-bind the data to the grid template self._from.link(self._selector, self.template(), self._options); // Check if the data source (collection or view) has an // orderBy method (usually only views) and if so activate // the sorting system if (self._from.orderBy) { // Listen for sort requests elem.on('click', '[data-grid-sort]', sortClickListener); } if (self._from.query) { // Listen for filter requests var queryObj = {}; elem.find('[data-grid-filter]').each(function (index, filterElem) { filterElem = window.jQuery(filterElem); var filterField = filterElem.attr('data-grid-filter'), filterVarType = filterElem.attr('data-grid-vartype'), filterSort = {}, title = filterElem.html(), dropDownButton, dropDownMenu, template, filterQuery, filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField); filterSort[filterField] = 1; filterQuery = { $distinct: filterSort }; filterView .query(filterQuery) .orderBy(filterSort) .from(self._from._from); template = [ '<div class="dropdown" id="' + self._id + '_' + filterField + '">', '<button class="btn btn-default dropdown-toggle" type="button" id="' + self._id + '_' + filterField + '_dropdownButton" data-toggle="dropdown" aria-expanded="true">', title + ' <span class="caret"></span>', '</button>', '</div>' ]; dropDownButton = window.jQuery(template.join('')); dropDownMenu = window.jQuery('<ul class="dropdown-menu" role="menu" id="' + self._id + '_' + filterField + '_dropdownMenu"></ul>'); dropDownButton.append(dropDownMenu); filterElem.html(dropDownButton); // Data-link the underlying data to the grid filter drop-down filterView.link(dropDownMenu, { template: [ '<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">', '<input type="search" class="form-control gridFilterSearch" placeholder="Search...">', '<span class="input-group-btn">', '<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>', '</span>', '</li>', '<li role="presentation" class="divider"></li>', '<li role="presentation" data-val="$all">', '<a role="menuitem" tabindex="-1">', '<input type="checkbox" checked>&nbsp;All', '</a>', '</li>', '<li role="presentation" class="divider"></li>', '{^{for options}}', '<li role="presentation" data-link="data-val{:' + filterField + '}">', '<a role="menuitem" tabindex="-1">', '<input type="checkbox">&nbsp;{^{:' + filterField + '}}', '</a>', '</li>', '{{/for}}' ].join('') }, { $wrap: 'options' }); elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) { var elem = window.jQuery(this), query = filterView.query(), search = elem.val(); if (search) { query[filterField] = new RegExp(search, 'gi'); } else { delete query[filterField]; } filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) { // Clear search text box window.jQuery(this).parents('li').find('.gridFilterSearch').val(''); // Clear view query var query = filterView.query(); delete query[filterField]; filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) { e.stopPropagation(); var fieldValue, elem = $(this), checkbox = elem.find('input[type="checkbox"]'), checked, addMode = true, fieldInArr, liElem, i; // If the checkbox is not the one clicked on if (!window.jQuery(e.target).is('input')) { // Set checkbox to opposite of current value checkbox.prop('checked', !checkbox.prop('checked')); checked = checkbox.is(':checked'); } else { checkbox.prop('checked', checkbox.prop('checked')); checked = checkbox.is(':checked'); } liElem = window.jQuery(this); fieldValue = liElem.attr('data-val'); // Check if the selection is the "all" option if (fieldValue === '$all') { // Remove the field from the query delete queryObj[filterField]; // Clear all other checkboxes liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false); } else { // Clear the "all" checkbox liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false); // Check if the type needs casting switch (filterVarType) { case 'integer': fieldValue = parseInt(fieldValue, 10); break; case 'float': fieldValue = parseFloat(fieldValue); break; default: } // Check if the item exists already queryObj[filterField] = queryObj[filterField] || { $in: [] }; fieldInArr = queryObj[filterField].$in; for (i = 0; i < fieldInArr.length; i++) { if (fieldInArr[i] === fieldValue) { // Item already exists if (checked === false) { // Remove the item fieldInArr.splice(i, 1); } addMode = false; break; } } if (addMode && checked) { fieldInArr.push(fieldValue); } if (!fieldInArr.length) { // Remove the field from the query delete queryObj[filterField]; } } // Set the view query self._from.queryData(queryObj); if (self._from.pageFirst) { self._from.pageFirst(); } }); }); } self.emit('refresh'); } else { throw('Grid requires the AutoBind module in order to operate!'); } } return this; }; /** * Returns the number of documents currently in the grid. * @func count * @memberof Grid * @returns {Number} */ Grid.prototype.count = function () { return this._from.count(); }; /** * Creates a grid and assigns the collection as its data source. * @func grid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.grid = View.prototype.grid = function (selector, template, options) { if (this._db && this._db._grid ) { if (selector !== undefined) { if (template !== undefined) { if (!this._db._grid[selector]) { var grid = new Grid(selector, template, options) .db(this._db) .from(this); this._grid = this._grid || []; this._grid.push(grid); this._db._grid[selector] = grid; return grid; } else { throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector); } } return this._db._grid[selector]; } return this._db._grid; } }; /** * Removes a grid safely from the DOM. Must be called when grid is * no longer required / is being removed from DOM otherwise references * will stick around and cause memory leaks. * @func unGrid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) { var i, grid; if (this._db && this._db._grid ) { if (selector && template) { if (this._db._grid[selector]) { grid = this._db._grid[selector]; delete this._db._grid[selector]; return grid.drop(); } else { throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name); } } else { // No parameters passed, remove all grids from this module for (i in this._db._grid) { if (this._db._grid.hasOwnProperty(i)) { grid = this._db._grid[i]; delete this._db._grid[i]; grid.drop(); if (this.debug()) { console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"'); } } } this._db._grid = {}; } } }; /** * Adds a grid to the internal grid lookup. * @func _addGrid * @memberof Collection * @param {Grid} grid The grid to add. * @returns {Collection} * @private */ Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) { if (grid !== undefined) { this._grid = this._grid || []; this._grid.push(grid); } return this; }; /** * Removes a grid from the internal grid lookup. * @func _removeGrid * @memberof Collection * @param {Grid} grid The grid to remove. * @returns {Collection} * @private */ Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) { if (grid !== undefined && this._grid) { var index = this._grid.indexOf(grid); if (index > -1) { this._grid.splice(index, 1); } } return this; }; // Extend DB with grids init Db.prototype.init = function () { this._grid = {}; DbInit.apply(this, arguments); }; /** * Determine if a grid with the passed name already exists. * @func gridExists * @memberof Db * @param {String} selector The jQuery selector to bind the grid to. * @returns {boolean} */ Db.prototype.gridExists = function (selector) { return Boolean(this._grid[selector]); }; /** * Creates a grid based on the passed arguments. * @func grid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.grid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Removes a grid based on the passed arguments. * @func unGrid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.unGrid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Returns an array of grids the DB currently has. * @func grids * @memberof Db * @returns {Array} An array of objects containing details of each grid * the database is currently managing. */ Db.prototype.grids = function () { var arr = [], item, i; for (i in this._grid) { if (this._grid.hasOwnProperty(i)) { item = this._grid[i]; arr.push({ name: i, count: item.count(), linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Grid'); module.exports = Grid; },{"./Collection":5,"./CollectionGroup":6,"./ReactorIO":37,"./Shared":39,"./View":40}],12:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Collection, CollectionInit, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The constructor. * * @constructor */ var Highchart = function (collection, options) { this.init.apply(this, arguments); }; Highchart.prototype.init = function (collection, options) { this._options = options; this._selector = window.jQuery(this._options.selector); if (!this._selector[0]) { throw(this.classIdentifier() + ' "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector); } this._listeners = {}; this._collection = collection; // Setup the chart this._options.series = []; // Disable attribution on highcharts options.chartOptions = options.chartOptions || {}; options.chartOptions.credits = false; // Set the data for the chart var data, seriesObj, chartData; switch (this._options.type) { case 'pie': // Create chart from data this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); // Generate graph data from collection data data = this._collection.find(); seriesObj = { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)', style: { color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black' } } }; chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField); window.jQuery.extend(seriesObj, this._options.seriesOptions); window.jQuery.extend(seriesObj, { name: this._options.seriesName, data: chartData }); this._chart.addSeries(seriesObj, true, true); break; case 'line': case 'area': case 'column': case 'bar': // Generate graph data from collection data chartData = this.seriesDataFromCollectionData( this._options.seriesField, this._options.keyField, this._options.valField, this._options.orderBy, this._options ); this._options.chartOptions.xAxis = chartData.xAxis; this._options.chartOptions.series = chartData.series; this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); break; default: throw(this.classIdentifier() + ' "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type); } // Hook the collection events to auto-update the chart this._hookEvents(); }; Shared.addModule('Highchart', Highchart); Collection = Shared.modules.Collection; CollectionInit = Collection.prototype.init; Shared.mixin(Highchart.prototype, 'Mixin.Common'); Shared.mixin(Highchart.prototype, 'Mixin.Events'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Highchart.prototype, 'state'); /** * Generate pie-chart series data from the given collection data array. * @param data * @param keyField * @param valField * @returns {Array} */ Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) { var graphData = [], i; for (i = 0; i < data.length; i++) { graphData.push([data[i][keyField], data[i][valField]]); } return graphData; }; /** * Generate line-chart series data from the given collection data array. * @param seriesField * @param keyField * @param valField * @param orderBy */ Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy, options) { var data = this._collection.distinct(seriesField), seriesData = [], xAxis = options && options.chartOptions && options.chartOptions.xAxis ? options.chartOptions.xAxis : { categories: [] }, seriesName, query, dataSearch, seriesValues, sData, i, k; // What we WANT to output: /*series: [{ name: 'Responses', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6] }]*/ // Loop keys for (i = 0; i < data.length; i++) { seriesName = data[i]; query = {}; query[seriesField] = seriesName; seriesValues = []; dataSearch = this._collection.find(query, { orderBy: orderBy }); // Loop the keySearch data and grab the value for each item for (k = 0; k < dataSearch.length; k++) { if (xAxis.categories) { xAxis.categories.push(dataSearch[k][keyField]); seriesValues.push(dataSearch[k][valField]); } else { seriesValues.push([dataSearch[k][keyField], dataSearch[k][valField]]); } } sData = { name: seriesName, data: seriesValues }; if (options.seriesOptions) { for (k in options.seriesOptions) { if (options.seriesOptions.hasOwnProperty(k)) { sData[k] = options.seriesOptions[k]; } } } seriesData.push(sData); } return { xAxis: xAxis, series: seriesData }; }; /** * Hook the events the chart needs to know about from the internal collection. * @private */ Highchart.prototype._hookEvents = function () { var self = this; self._collection.on('change', function () { self._changeListener.apply(self, arguments); }); // If the collection is dropped, clean up after ourselves self._collection.on('drop', function () { self.drop.apply(self); }); }; /** * Handles changes to the collection data that the chart is reading from and then * updates the data in the chart display. * @private */ Highchart.prototype._changeListener = function () { var self = this; // Update the series data on the chart if (typeof self._collection !== 'undefined' && self._chart) { var data = self._collection.find(), i; switch (self._options.type) { case 'pie': self._chart.series[0].setData( self.pieDataFromCollectionData( data, self._options.keyField, self._options.valField ), true, true ); break; case 'bar': case 'line': case 'area': case 'column': var seriesData = self.seriesDataFromCollectionData( self._options.seriesField, self._options.keyField, self._options.valField, self._options.orderBy, self._options ); if (seriesData.xAxis.categories) { self._chart.xAxis[0].setCategories( seriesData.xAxis.categories ); } for (i = 0; i < seriesData.series.length; i++) { if (self._chart.series[i]) { // Series exists, set it's data self._chart.series[i].setData( seriesData.series[i].data, true, true ); } else { // Series data does not yet exist, add a new series self._chart.addSeries( seriesData.series[i], true, true ); } } break; default: break; } } }; /** * Destroys the chart and all internal references. * @returns {Boolean} */ Highchart.prototype.drop = function (callback) { if (!this.isDropped()) { this._state = 'dropped'; if (this._chart) { this._chart.destroy(); } if (this._collection) { this._collection.off('change', this._changeListener); this._collection.off('drop', this.drop); if (this._collection._highcharts) { delete this._collection._highcharts[this._options.selector]; } } delete this._chart; delete this._options; delete this._collection; this.emit('drop', this); if (callback) { callback(false, true); } delete this._listeners; return true; } else { return true; } }; // Extend collection with highchart init Collection.prototype.init = function () { this._highcharts = {}; CollectionInit.apply(this, arguments); }; /** * Creates a pie chart from the collection. * @type {Overload} */ Collection.prototype.pieChart = new Overload({ /** * Chart via options object. * @func pieChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'pie'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'pie'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func pieChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {String} seriesName The name of the series to display on the chart. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) { options = options || {}; options.selector = selector; options.keyField = keyField; options.valField = valField; options.seriesName = seriesName; // Call the main chart method this.pieChart(options); } }); /** * Creates a line chart from the collection. * @type {Overload} */ Collection.prototype.lineChart = new Overload({ /** * Chart via selector. * @func lineChart * @memberof Highchart * @param {String} selector The chart selector. * @returns {*} */ 'string': function (selector) { return this._highcharts[selector]; }, /** * Chart via options object. * @func lineChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'line'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'line'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func lineChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.lineChart(options); } }); /** * Creates an area chart from the collection. * @type {Overload} */ Collection.prototype.areaChart = new Overload({ /** * Chart via options object. * @func areaChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'area'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'area'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func areaChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.areaChart(options); } }); /** * Creates a column chart from the collection. * @type {Overload} */ Collection.prototype.columnChart = new Overload({ /** * Chart via options object. * @func columnChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'column'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'column'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func columnChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.columnChart(options); } }); /** * Creates a bar chart from the collection. * @type {Overload} */ Collection.prototype.barChart = new Overload({ /** * Chart via options object. * @func barChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'bar'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'bar'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func barChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.barChart(options); } }); /** * Creates a stacked bar chart from the collection. * @type {Overload} */ Collection.prototype.stackedBarChart = new Overload({ /** * Chart via options object. * @func stackedBarChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'bar'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'bar'; options.plotOptions = options.plotOptions || {}; options.plotOptions.series = options.plotOptions.series || {}; options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func stackedBarChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.stackedBarChart(options); } }); /** * Removes a chart from the page by it's selector. * @memberof Collection * @param {String} selector The chart selector. */ Collection.prototype.dropChart = function (selector) { if (this._highcharts && this._highcharts[selector]) { this._highcharts[selector].drop(); } }; Shared.finishModule('Highchart'); module.exports = Highchart; },{"./Overload":31,"./Shared":39}],13:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; /** * Create the index. * @param {Object} keys The object with the keys that the user wishes the index * to operate on. * @param {Object} options Can be undefined, if passed is an object with arbitrary * options keys and values. * @param {Collection} collection The collection the index should be created for. */ Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.lookup = function (query, options) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options) { var self = this, geoHash, neighbours, visited, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } // Get the lngLat geohash from the query geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision); // Calculate 9 box geohashes neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'}); // Lookup all matching co-ordinates from the btree results = []; visited = 0; for (i = 0; i < 9; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visited += search._visited; results = results.concat(search); } // Work with original data results = this._collection._primaryIndex.lookup(results); if (results.length) { distance = {}; // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { // Add item inside radius distance finalResults.push(results[i]); } } // Sort by distance from center finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index['2d'] = Index2d; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":3,"./GeoHash":10,"./Path":33,"./Shared":39}],14:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query, options) { return this._btree.lookup(query, options); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.btree = IndexBinaryTree; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":3,"./Path":33,"./Shared":39}],15:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.hashed = IndexHashMap; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":33,"./Shared":39}],16:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} val A lookup query. * @returns {*} */ KeyValueStore.prototype.lookup = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, result = []; // Check for early exit conditions if (valType === 'string' || valType === 'number') { lookupItem = this.get(val); if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } else if (valType === 'object') { if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this.lookup(val[arrIndex]); if (lookupItem) { if (lookupItem instanceof Array) { result = result.concat(lookupItem); } else { result.push(lookupItem); } } } return result; } else if (val[pk]) { return this.lookup(val[pk]); } } // COMMENTED AS CODE WILL NEVER BE REACHED // Complex lookup /*lookupData = this._lookupKeys(val); keys = lookupData.keys; negate = lookupData.negate; if (!negate) { // Loop keys and return values for (arrIndex = 0; arrIndex < keys.length; arrIndex++) { result.push(this.get(keys[arrIndex])); } } else { // Loop data and return non-matching keys for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (keys.indexOf(arrIndex) === -1) { result.push(this.get(arrIndex)); } } } } return result;*/ }; // COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES /*KeyValueStore.prototype._lookupKeys = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, bool, result; if (valType === 'string' || valType === 'number') { return { keys: [val], negate: false }; } else if (valType === 'object') { if (val instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (val.test(arrIndex)) { result.push(arrIndex); } } } return { keys: result, negate: false }; } else if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { result = result.concat(this._lookupKeys(val[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val.$in && (val.$in instanceof Array)) { return { keys: this._lookupKeys(val.$in).keys, negate: false }; } else if (val.$nin && (val.$nin instanceof Array)) { return { keys: this._lookupKeys(val.$nin).keys, negate: true }; } else if (val.$ne) { return { keys: this._lookupKeys(val.$ne, true).keys, negate: true }; } else if (val.$or && (val.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) { result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val[pk]) { return this._lookupKeys(val[pk]); } } };*/ /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":39}],17:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":30,"./Shared":39}],18:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],19:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * Creates a chain link between the current reactor node and the passed * reactor node. Chain packets that are send by this reactor node will * then be propagated to the passed node for subsequent packets. * @param {*} obj The chain reactor node to link to. */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, /** * Removes a chain link between the current reactor node and the passed * reactor node. Chain packets sent from this reactor node will no longer * be received by the passed node. * @param {*} obj The chain reactor node to unlink from. */ unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, /** * Determines if this chain reactor node has any listeners downstream. * @returns {Boolean} True if there are nodes downstream of this node. */ chainWillSend: function () { return Boolean(this._chain); }, /** * Sends a chain reactor packet downstream from this node to any of its * chained targets that were linked to this node via a call to chain(). * @param {String} type The type of chain reactor packet to send. This * can be any string but the receiving reactor nodes will not react to * it unless they recognise the string. Built-in strings include: "insert", * "update", "remove", "setData" and "debug". * @param {Object} data A data object that usually contains a key called * "dataSet" which is an array of items to work on, and can contain other * custom keys that help describe the operation. * @param {Object=} options An options object. Can also contain custom * key/value pairs that your custom chain reactor code can operate on. */ chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index, dataCopy = this.decouple(data, count); for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, dataCopy[index], options); } } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, /** * Handles receiving a chain reactor message that was sent via the chainSend() * method. Creates the chain packet object and then allows it to be processed. * @param {Object} sender The node that is sending the packet. * @param {String} type The type of packet. * @param {Object} data The data related to the packet. * @param {Object=} options An options object. */ chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }, cancelPropagate = false; if (this.debug && this.debug()) { console.log(this.logIdentifier() + ' Received data from parent reactor node'); } // Check if we have a chain handler method if (this._chainHandler) { // Fire our internal handler cancelPropagate = this._chainHandler(chainPacket); } // Check if we were told to cancel further propagation if (!cancelPropagate) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],20:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Generates a JSON serialisation-compatible object instance. After the * instance has been passed through this method, it will be able to survive * a JSON.stringify() and JSON.parse() cycle and still end up as an * instance at the end. Further information about this process can be found * in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks * @param {*} val The object instance such as "new Date()" or "new RegExp()". */ make: function (val) { // This is a conversion request, hand over to serialiser return serialiser.convert(val); }, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined && data !== "") { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return JSON.parse(data, serialiser.reviver()); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { //return serialiser.stringify(data); return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Generates a unique hash for the passed object. * @param {Object} obj The object to generate a hash for. * @returns {String} */ hash: function (obj) { return JSON.stringify(obj); }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return 'ForerunnerDB ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; }, /** * Registers a timed callback that will overwrite itself if * the same id is used within the timeout period. Useful * for de-bouncing fast-calls. * @param {String} id An ID for the call (use the same one * to debounce the same calls). * @param {Function} callback The callback method to call on * timeout. * @param {Number} timeout The timeout in milliseconds before * the callback is called. */ debounce: function (id, callback, timeout) { var self = this, newData; self._debounce = self._debounce || {}; if (self._debounce[id]) { // Clear timeout for this item clearTimeout(self._debounce[id].timeout); } newData = { callback: callback, timeout: setTimeout(function () { // Delete existing reference delete self._debounce[id]; // Call the callback callback(); }, timeout) }; // Save current data self._debounce[id] = newData; } }; module.exports = Common; },{"./Overload":31,"./Serialiser":38}],21:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],22:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":31}],23:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; if (sourceType === 'object' && source === null) { sourceType = 'null'; } if (testType === 'object' && test === null) { testType = 'null'; } options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number' || sourceType === 'null') && (testType === 'string' || testType === 'number' || testType === 'null')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number' || sourceType === 'null' || testType === 'null') { // Number or null comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; }, /** * * @param {Array | Object} docArr An array of objects to run the join * operation against or a single object. * @param {Array} joinClause The join clause object array (the array in * the $join key of a normal join options object). * @param {Object} joinSource An object containing join source reference * data or a blank object if you are doing a bespoke join operation. * @param {Object} options An options object or blank object if no options. * @returns {Array} * @private */ applyJoin: function (docArr, joinClause, joinSource, options) { var self = this, joinSourceIndex, joinSourceKey, joinMatch, joinSourceType, joinSourceIdentifier, resultKeyName, joinSourceInstance, resultIndex, joinSearchQuery, joinMulti, joinRequire, joinPrefix, joinMatchIndex, joinMatchData, joinSearchOptions, joinFindResults, joinFindResult, joinItem, resultRemove = [], l; if (!(docArr instanceof Array)) { // Turn the document into an array docArr = [docArr]; } for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) { for (joinSourceKey in joinClause[joinSourceIndex]) { if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) { // Get the match data for the join joinMatch = joinClause[joinSourceIndex][joinSourceKey]; // Check if the join is to a collection (default) or a specified source type // e.g 'view' or 'collection' joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; // Set the key to store the join result in to the collection name by default // can be overridden by the '$as' clause in the join object resultKeyName = joinSourceKey; // Get the join collection instance from the DB if (joinSource[joinSourceIdentifier]) { // We have a joinSource for this identifier already (given to us by // an index when we analysed the query earlier on) and we can use // that source instead. joinSourceInstance = joinSource[joinSourceIdentifier]; } else { // We do not already have a joinSource so grab the instance from the db if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') { joinSourceInstance = this._db[joinSourceType](joinSourceKey); } } // Loop our result data array for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultKeyName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultKeyName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = docArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultIndex); } } } } } return resultRemove; }, /** * Takes a query object with dynamic references and converts the references * into actual values from the references source. * @param {Object} query The query object with dynamic references. * @param {Object} item The document to apply the references to. * @returns {*} * @private */ resolveDynamicQuery: function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; // Check for early exit conditions if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3)); } else { pathResult = this.sharedPathSolver.value(item, query); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self.resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }, spliceArrayByIndexList: function (arr, list) { var i; for (i = list.length - 1; i >= 0; i--) { arr.splice(list[i], 1); } } }; module.exports = Matching; },{}],24:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],25:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],26:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * When called in a before phase the newDoc object can be directly altered * to modify the data in it before the operation is carried out. * @callback addTriggerCallback * @param {Object} operation The details about the operation. * @param {Object} oldDoc The document before the operation. * @param {Object} newDoc The document after the operation. */ /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Constants} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Constants} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {addTriggerCallback} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { self.triggerStack = {}; // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, /** * Tells the current instance to fire or ignore all triggers whether they * are enabled or not. * @param {Boolean} val Set to true to ignore triggers or false to not * ignore them. * @returns {*} */ ignoreTriggers: function (val) { if (val !== undefined) { this._ignoreTriggers = val; return this; } return this._ignoreTriggers; }, /** * Generates triggers that fire in the after phase for all CRUD ops * that automatically transform data back and forth and keep both * import and export collections in sync with each other. * @param {String} id The unique id for this link IO. * @param {Object} ioData The settings for the link IO. */ addLinkIO: function (id, ioData) { var self = this, matchAll, exportData, importData, exportTriggerMethod, importTriggerMethod, exportTo, importFrom, allTypes, i; // Store the linkIO self._linkIO = self._linkIO || {}; self._linkIO[id] = ioData; exportData = ioData['export']; importData = ioData['import']; if (exportData) { exportTo = self.db().collection(exportData.to); } if (importData) { importFrom = self.db().collection(importData.from); } allTypes = [ self.TYPE_INSERT, self.TYPE_UPDATE, self.TYPE_REMOVE ]; matchAll = function (data, callback) { // Match all callback(false, true); }; if (exportData) { // Check for export match method if (!exportData.match) { // No match method found, use the match all method exportData.match = matchAll; } // Check for export types if (!exportData.types) { exportData.types = allTypes; } exportTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data exportData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) exportData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert exportTo.upsert(data, callback); } else { // Do remove exportTo.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (importData) { // Check for import match method if (!importData.match) { // No match method found, use the match all method importData.match = matchAll; } // Check for import types if (!importData.types) { importData.types = allTypes; } importTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data importData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) importData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert self.upsert(data, callback); } else { // Do remove self.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.addTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.PHASE_AFTER, exportTriggerMethod); } } if (importData) { for (i = 0; i < importData.types.length; i++) { importFrom.addTrigger(id + 'import' + importData.types[i], importData.types[i], self.PHASE_AFTER, importTriggerMethod); } } }, /** * Removes a previously added link IO via it's ID. * @param {String} id The id of the link IO to remove. * @returns {boolean} True if successful, false if the link IO * was not found. */ removeLinkIO: function (id) { var self = this, linkIO = self._linkIO[id], exportData, importData, importFrom, i; if (linkIO) { exportData = linkIO['export']; importData = linkIO['import']; if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.removeTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.db.PHASE_AFTER); } } if (importData) { importFrom = self.db().collection(importData.from); for (i = 0; i < importData.types.length; i++) { importFrom.removeTrigger(id + 'import' + importData.types[i], importData.types[i], self.db.PHASE_AFTER); } } delete self._linkIO[id]; return true; } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (!this._ignoreTriggers && this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response, typeName, phaseName; if (!self._ignoreTriggers && self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (self.debug()) { switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } console.log('Triggers: Processing trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Check if the trigger is already in the stack, if it is, // don't fire it again (this is so we avoid infinite loops // where a trigger triggers another trigger which calls this // one and so on) if (self.triggerStack && self.triggerStack[type] && self.triggerStack[type][phase] && self.triggerStack[type][phase][triggerItem.id]) { // The trigger is already in the stack, do not fire the trigger again if (self.debug()) { console.log('Triggers: Will not run trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '" as it is already in the stack!'); } continue; } // Add the trigger to the stack so we don't go down an endless // trigger loop self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = true; // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Remove the trigger from the stack self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = false; // Check the response for a non-expected result (anything other than // [undefined, true or false] is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":31}],27:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],28:[function(_dereq_,module,exports){ "use strict"; // Grab the view class var Shared, Core, OldView, OldViewInit; Shared = _dereq_('./Shared'); Core = Shared.modules.Core; OldView = Shared.modules.OldView; OldViewInit = OldView.prototype.init; OldView.prototype.init = function () { var self = this; this._binds = []; this._renderStart = 0; this._renderEnd = 0; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], _bindInsert: [], _bindUpdate: [], _bindRemove: [], _bindUpsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100, _bindInsert: 100, _bindUpdate: 100, _bindRemove: 100, _bindUpsert: 100 }; this._deferTime = { insert: 100, update: 1, remove: 1, upsert: 1, _bindInsert: 100, _bindUpdate: 1, _bindRemove: 1, _bindUpsert: 1 }; OldViewInit.apply(this, arguments); // Hook view events to update binds this.on('insert', function (successArr, failArr) { self._bindEvent('insert', successArr, failArr); }); this.on('update', function (successArr, failArr) { self._bindEvent('update', successArr, failArr); }); this.on('remove', function (successArr, failArr) { self._bindEvent('remove', successArr, failArr); }); this.on('change', self._bindChange); }; /** * Binds a selector to the insert, update and delete events of a particular * view and keeps the selector in sync so that updates are reflected on the * web page in real-time. * * @param {String} selector The jQuery selector string to get target elements. * @param {Object} options The options object. */ OldView.prototype.bind = function (selector, options) { if (options && options.template) { this._binds[selector] = options; } else { throw('ForerunnerDB.OldView "' + this.name() + '": Cannot bind data to element, missing options information!'); } return this; }; /** * Un-binds a selector from the view changes. * @param {String} selector The jQuery selector string to identify the bind to remove. * @returns {Collection} */ OldView.prototype.unBind = function (selector) { delete this._binds[selector]; return this; }; /** * Returns true if the selector is bound to the view. * @param {String} selector The jQuery selector string to identify the bind to check for. * @returns {boolean} */ OldView.prototype.isBound = function (selector) { return Boolean(this._binds[selector]); }; /** * Sorts items in the DOM based on the bind settings and the passed item array. * @param {String} selector The jQuery selector of the bind container. * @param {Array} itemArr The array of items used to determine the order the DOM * elements should be in based on the order they are in, in the array. */ OldView.prototype.bindSortDom = function (selector, itemArr) { var container = window.jQuery(selector), arrIndex, arrItem, domItem; if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting data in DOM...', itemArr); } for (arrIndex = 0; arrIndex < itemArr.length; arrIndex++) { arrItem = itemArr[arrIndex]; // Now we've done our inserts into the DOM, let's ensure // they are still ordered correctly domItem = container.find('#' + arrItem[this._primaryKey]); if (domItem.length) { if (arrIndex === 0) { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sort, moving to index 0...', domItem); } container.prepend(domItem); } else { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sort, moving to index ' + arrIndex + '...', domItem); } domItem.insertAfter(container.children(':eq(' + (arrIndex - 1) + ')')); } } else { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Warning, element for array item not found!', arrItem); } } } }; OldView.prototype.bindRefresh = function (obj) { var binds = this._binds, bindKey, bind; if (!obj) { // Grab current data obj = { data: this.find() }; } for (bindKey in binds) { if (binds.hasOwnProperty(bindKey)) { bind = binds[bindKey]; if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting DOM...'); } this.bindSortDom(bindKey, obj.data); if (bind.afterOperation) { bind.afterOperation(); } if (bind.refresh) { bind.refresh(); } } } }; /** * Renders a bind view data to the DOM. * @param {String} bindSelector The jQuery selector string to use to identify * the bind target. Must match the selector used when defining the original bind. * @param {Function=} domHandler If specified, this handler method will be called * with the final HTML for the view instead of the DB handling the DOM insertion. */ OldView.prototype.bindRender = function (bindSelector, domHandler) { // Check the bind exists var bind = this._binds[bindSelector], domTarget = window.jQuery(bindSelector), allData, dataItem, itemHtml, finalHtml = window.jQuery('<ul></ul>'), bindCallback, i; if (bind) { allData = this._data.find(); bindCallback = function (itemHtml) { finalHtml.append(itemHtml); }; // Loop all items and add them to the screen for (i = 0; i < allData.length; i++) { dataItem = allData[i]; itemHtml = bind.template(dataItem, bindCallback); } if (!domHandler) { domTarget.append(finalHtml.html()); } else { domHandler(bindSelector, finalHtml.html()); } } }; OldView.prototype.processQueue = function (type, callback) { var queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type]; if (queue.length) { var self = this, dataArr; // Process items up to the threshold if (queue.length) { if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } this._bindEvent(type, dataArr, []); } // Queue another process setTimeout(function () { self.processQueue(type, callback); }, deferTime); } else { if (callback) { callback(); } this.emit('bindQueueComplete'); } }; OldView.prototype._bindEvent = function (type, successArr, failArr) { /*var queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type];*/ var binds = this._binds, unfilteredDataSet = this.find({}), filteredDataSet, bindKey; // Check if the number of inserts is greater than the defer threshold /*if (successArr && successArr.length > deferThreshold) { // Break up upsert into blocks this._deferQueue[type] = queue.concat(successArr); // Fire off the insert queue handler this.processQueue(type); return; } else {*/ for (bindKey in binds) { if (binds.hasOwnProperty(bindKey)) { if (binds[bindKey].reduce) { filteredDataSet = this.find(binds[bindKey].reduce.query, binds[bindKey].reduce.options); } else { filteredDataSet = unfilteredDataSet; } switch (type) { case 'insert': this._bindInsert(bindKey, binds[bindKey], successArr, failArr, filteredDataSet); break; case 'update': this._bindUpdate(bindKey, binds[bindKey], successArr, failArr, filteredDataSet); break; case 'remove': this._bindRemove(bindKey, binds[bindKey], successArr, failArr, filteredDataSet); break; } } } //} }; OldView.prototype._bindChange = function (newDataArr) { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...', newDataArr); } this.bindRefresh(newDataArr); }; OldView.prototype._bindInsert = function (selector, options, successArr, failArr, all) { var container = window.jQuery(selector), itemElem, itemHtml, makeCallback, i; makeCallback = function (itemElem, insertedItem, failArr, all) { return function (itemHtml) { // Check if there is custom DOM insert method if (options.insert) { options.insert(itemHtml, insertedItem, failArr, all); } else { // Handle the insert automatically // Add the item to the container if (options.prependInsert) { container.prepend(itemHtml); } else { container.append(itemHtml); } } if (options.afterInsert) { options.afterInsert(itemHtml, insertedItem, failArr, all); } }; }; // Loop the inserted items for (i = 0; i < successArr.length; i++) { // Check for existing item in the container itemElem = container.find('#' + successArr[i][this._primaryKey]); if (!itemElem.length) { itemHtml = options.template(successArr[i], makeCallback(itemElem, successArr[i], failArr, all)); } } }; OldView.prototype._bindUpdate = function (selector, options, successArr, failArr, all) { var container = window.jQuery(selector), itemElem, makeCallback, i; makeCallback = function (itemElem, itemData) { return function (itemHtml) { // Check if there is custom DOM insert method if (options.update) { options.update(itemHtml, itemData, all, itemElem.length ? 'update' : 'append'); } else { if (itemElem.length) { // An existing item is in the container, replace it with the // new rendered item from the updated data itemElem.replaceWith(itemHtml); } else { // The item element does not already exist, append it if (options.prependUpdate) { container.prepend(itemHtml); } else { container.append(itemHtml); } } } if (options.afterUpdate) { options.afterUpdate(itemHtml, itemData, all); } }; }; // Loop the updated items for (i = 0; i < successArr.length; i++) { // Check for existing item in the container itemElem = container.find('#' + successArr[i][this._primaryKey]); options.template(successArr[i], makeCallback(itemElem, successArr[i])); } }; OldView.prototype._bindRemove = function (selector, options, successArr, failArr, all) { var container = window.jQuery(selector), itemElem, makeCallback, i; makeCallback = function (itemElem, data, all) { return function () { if (options.remove) { options.remove(itemElem, data, all); } else { itemElem.remove(); if (options.afterRemove) { options.afterRemove(itemElem, data, all); } } }; }; // Loop the removed items for (i = 0; i < successArr.length; i++) { // Check for existing item in the container itemElem = container.find('#' + successArr[i][this._primaryKey]); if (itemElem.length) { if (options.beforeRemove) { options.beforeRemove(itemElem, successArr[i], all, makeCallback(itemElem, successArr[i], all)); } else { if (options.remove) { options.remove(itemElem, successArr[i], all); } else { itemElem.remove(); if (options.afterRemove) { options.afterRemove(itemElem, successArr[i], all); } } } } } }; },{"./Shared":39}],29:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, CollectionGroup, Collection, CollectionInit, CollectionGroupInit, DbInit; Shared = _dereq_('./Shared'); /** * The view constructor. * @param viewName * @constructor */ var OldView = function (viewName) { this.init.apply(this, arguments); }; OldView.prototype.init = function (viewName) { var self = this; this._name = viewName; this._listeners = {}; this._query = { query: {}, options: {} }; // Register listeners for the CRUD events this._onFromSetData = function () { self._onSetData.apply(self, arguments); }; this._onFromInsert = function () { self._onInsert.apply(self, arguments); }; this._onFromUpdate = function () { self._onUpdate.apply(self, arguments); }; this._onFromRemove = function () { self._onRemove.apply(self, arguments); }; this._onFromChange = function () { if (self.debug()) { console.log('ForerunnerDB.OldView: Received change'); } self._onChange.apply(self, arguments); }; }; Shared.addModule('OldView', OldView); CollectionGroup = _dereq_('./CollectionGroup'); Collection = _dereq_('./Collection'); CollectionInit = Collection.prototype.init; CollectionGroupInit = CollectionGroup.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; Shared.mixin(OldView.prototype, 'Mixin.Events'); /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ OldView.prototype.drop = function () { if ((this._db || this._from) && this._name) { if (this.debug()) { console.log('ForerunnerDB.OldView: Dropping view ' + this._name); } this._state = 'dropped'; this.emit('drop', this); if (this._db && this._db._oldViews) { delete this._db._oldViews[this._name]; } if (this._from && this._from._oldViews) { delete this._from._oldViews[this._name]; } delete this._listeners; return true; } return false; }; OldView.prototype.debug = function () { // TODO: Make this function work return false; }; /** * Gets / sets the DB the view is bound against. Automatically set * when the db.oldView(viewName) method is called. * @param db * @returns {*} */ OldView.prototype.db = function (db) { if (db !== undefined) { this._db = db; return this; } return this._db; }; /** * Gets / sets the collection that the view derives it's data from. * @param {*} collection A collection instance or the name of a collection * to use as the data set to derive view data from. * @returns {*} */ OldView.prototype.from = function (collection) { if (collection !== undefined) { // Check if this is a collection name or a collection instance if (typeof(collection) === 'string') { if (this._db.collectionExists(collection)) { collection = this._db.collection(collection); } else { throw('ForerunnerDB.OldView "' + this.name() + '": Invalid collection in view.from() call.'); } } // Check if the existing from matches the passed one if (this._from !== collection) { // Check if we already have a collection assigned if (this._from) { // Remove ourselves from the collection view lookup this.removeFrom(); } this.addFrom(collection); } return this; } return this._from; }; OldView.prototype.addFrom = function (collection) { //var self = this; this._from = collection; if (this._from) { this._from.on('setData', this._onFromSetData); //this._from.on('insert', this._onFromInsert); //this._from.on('update', this._onFromUpdate); //this._from.on('remove', this._onFromRemove); this._from.on('change', this._onFromChange); // Add this view to the collection's view lookup this._from._addOldView(this); this._primaryKey = this._from._primaryKey; this.refresh(); return this; } else { throw('ForerunnerDB.OldView "' + this.name() + '": Cannot determine collection type in view.from()'); } }; OldView.prototype.removeFrom = function () { // Unsubscribe from events on this "from" this._from.off('setData', this._onFromSetData); //this._from.off('insert', this._onFromInsert); //this._from.off('update', this._onFromUpdate); //this._from.off('remove', this._onFromRemove); this._from.off('change', this._onFromChange); this._from._removeOldView(this); }; /** * Gets the primary key for this view from the assigned collection. * @returns {String} */ OldView.prototype.primaryKey = function () { if (this._from) { return this._from.primaryKey(); } return undefined; }; /** * Gets / sets the query that the view uses to build it's data set. * @param {Object=} query * @param {Boolean=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ OldView.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._query.query = query; } if (options !== undefined) { this._query.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._query; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ OldView.prototype.queryAdd = function (obj, overwrite, refresh) { var query = this._query.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ OldView.prototype.queryRemove = function (obj, refresh) { var query = this._query.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Gets / sets the query being used to generate the view data. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ OldView.prototype.query = function (query, refresh) { if (query !== undefined) { this._query.query = query; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._query.query; }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ OldView.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._query.options = options; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._query.options; }; /** * Refreshes the view data and diffs between previous and new data to * determine if any events need to be triggered or DOM binds updated. */ OldView.prototype.refresh = function (force) { if (this._from) { // Take a copy of the data before updating it, we will use this to // "diff" between the old and new data and handle DOM bind updates var oldData = this._data, oldDataArr, oldDataItem, newData, newDataArr, query, primaryKey, dataItem, inserted = [], updated = [], removed = [], operated = false, i; if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing view ' + this._name); console.log('ForerunnerDB.OldView: Existing data: ' + (typeof(this._data) !== "undefined")); if (typeof(this._data) !== "undefined") { console.log('ForerunnerDB.OldView: Current data rows: ' + this._data.find().length); } //console.log(OldView.prototype.refresh.caller); } // Query the collection and update the data if (this._query) { if (this.debug()) { console.log('ForerunnerDB.OldView: View has query and options, getting subset...'); } // Run query against collection //console.log('refresh with query and options', this._query.options); this._data = this._from.subset(this._query.query, this._query.options); //console.log(this._data); } else { // No query, return whole collection if (this._query.options) { if (this.debug()) { console.log('ForerunnerDB.OldView: View has options, getting subset...'); } this._data = this._from.subset({}, this._query.options); } else { if (this.debug()) { console.log('ForerunnerDB.OldView: View has no query or options, getting subset...'); } this._data = this._from.subset({}); } } // Check if there was old data if (!force && oldData) { if (this.debug()) { console.log('ForerunnerDB.OldView: Refresh not forced, old data detected...'); } // Now determine the difference newData = this._data; if (oldData.subsetOf() === newData.subsetOf()) { if (this.debug()) { console.log('ForerunnerDB.OldView: Old and new data are from same collection...'); } newDataArr = newData.find(); oldDataArr = oldData.find(); primaryKey = newData._primaryKey; // The old data and new data were derived from the same parent collection // so scan the data to determine changes for (i = 0; i < newDataArr.length; i++) { dataItem = newDataArr[i]; query = {}; query[primaryKey] = dataItem[primaryKey]; // Check if this item exists in the old data oldDataItem = oldData.find(query)[0]; if (!oldDataItem) { // New item detected inserted.push(dataItem); } else { // Check if an update has occurred if (JSON.stringify(oldDataItem) !== JSON.stringify(dataItem)) { // Updated / already included item detected updated.push(dataItem); } } } // Now loop the old data and check if any records were removed for (i = 0; i < oldDataArr.length; i++) { dataItem = oldDataArr[i]; query = {}; query[primaryKey] = dataItem[primaryKey]; // Check if this item exists in the old data if (!newData.find(query)[0]) { // Removed item detected removed.push(dataItem); } } if (this.debug()) { console.log('ForerunnerDB.OldView: Removed ' + removed.length + ' rows'); console.log('ForerunnerDB.OldView: Inserted ' + inserted.length + ' rows'); console.log('ForerunnerDB.OldView: Updated ' + updated.length + ' rows'); } // Now we have a diff of the two data sets, we need to get the DOM updated if (inserted.length) { this._onInsert(inserted, []); operated = true; } if (updated.length) { this._onUpdate(updated, []); operated = true; } if (removed.length) { this._onRemove(removed, []); operated = true; } } else { // The previous data and the new data are derived from different collections // and can therefore not be compared, all data is therefore effectively "new" // so first perform a remove of all existing data then do an insert on all new data if (this.debug()) { console.log('ForerunnerDB.OldView: Old and new data are from different collections...'); } removed = oldData.find(); if (removed.length) { this._onRemove(removed); operated = true; } inserted = newData.find(); if (inserted.length) { this._onInsert(inserted); operated = true; } } } else { // Force an update as if the view never got created by padding all elements // to the insert if (this.debug()) { console.log('ForerunnerDB.OldView: Forcing data update', newDataArr); } this._data = this._from.subset(this._query.query, this._query.options); newDataArr = this._data.find(); if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change event with data', newDataArr); } this._onInsert(newDataArr, []); } if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change'); } this.emit('change'); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ OldView.prototype.count = function () { return this._data && this._data._data ? this._data._data.length : 0; }; /** * Queries the view data. See Collection.find() for more information. * @returns {*} */ OldView.prototype.find = function () { if (this._data) { if (this.debug()) { console.log('ForerunnerDB.OldView: Finding data in view collection...', this._data); } return this._data.find.apply(this._data, arguments); } else { return []; } }; /** * Inserts into view data via the view collection. See Collection.insert() for more information. * @returns {*} */ OldView.prototype.insert = function () { if (this._from) { // Pass the args through to the from object return this._from.insert.apply(this._from, arguments); } else { return []; } }; /** * Updates into view data via the view collection. See Collection.update() for more information. * @returns {*} */ OldView.prototype.update = function () { if (this._from) { // Pass the args through to the from object return this._from.update.apply(this._from, arguments); } else { return []; } }; /** * Removed from view data via the view collection. See Collection.remove() for more information. * @returns {*} */ OldView.prototype.remove = function () { if (this._from) { // Pass the args through to the from object return this._from.remove.apply(this._from, arguments); } else { return []; } }; OldView.prototype._onSetData = function (newDataArr, oldDataArr) { this.emit('remove', oldDataArr, []); this.emit('insert', newDataArr, []); //this.refresh(); }; OldView.prototype._onInsert = function (successArr, failArr) { this.emit('insert', successArr, failArr); //this.refresh(); }; OldView.prototype._onUpdate = function (successArr, failArr) { this.emit('update', successArr, failArr); //this.refresh(); }; OldView.prototype._onRemove = function (successArr, failArr) { this.emit('remove', successArr, failArr); //this.refresh(); }; OldView.prototype._onChange = function () { if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing data'); } this.refresh(); }; // Extend collection with view init Collection.prototype.init = function () { this._oldViews = []; CollectionInit.apply(this, arguments); }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addOldView = function (view) { if (view !== undefined) { this._oldViews[view._name] = view; } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeOldView = function (view) { if (view !== undefined) { delete this._oldViews[view._name]; } return this; }; // Extend collection with view init CollectionGroup.prototype.init = function () { this._oldViews = []; CollectionGroupInit.apply(this, arguments); }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ CollectionGroup.prototype._addOldView = function (view) { if (view !== undefined) { this._oldViews[view._name] = view; } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ CollectionGroup.prototype._removeOldView = function (view) { if (view !== undefined) { delete this._oldViews[view._name]; } return this; }; // Extend DB with views init Db.prototype.init = function () { this._oldViews = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Db.prototype.oldView = function (viewName) { if (!this._oldViews[viewName]) { if (this.debug()) { console.log('ForerunnerDB.OldView: Creating view ' + viewName); } } this._oldViews[viewName] = this._oldViews[viewName] || new OldView(viewName).db(this); return this._oldViews[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Db.prototype.oldViewExists = function (viewName) { return Boolean(this._oldViews[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.oldViews = function () { var arr = [], i; for (i in this._oldViews) { if (this._oldViews.hasOwnProperty(i)) { arr.push({ name: i, count: this._oldViews[i].count() }); } } return arr; }; Shared.finishModule('OldView'); module.exports = OldView; },{"./Collection":5,"./CollectionGroup":6,"./Shared":39}],30:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":33,"./Shared":39}],31:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {String=} name A name to provide this overload to help identify * it if any errors occur during the resolving phase of the overload. This * is purely for debug purposes and serves no functional purpose. * @param {Object} def The overload definition. * @returns {Function} * @constructor */ var Overload = function (name, def) { if (!def) { def = name; name = undefined; } if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, overloadName; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload Definition:', def); throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['array', 'string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],32:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, DbDocument; Shared = _dereq_('./Shared'); var Overview = function () { this.init.apply(this, arguments); }; Overview.prototype.init = function (name) { var self = this; this._name = name; this._data = new DbDocument('__FDB__dc_data_' + this._name); this._collData = new Collection(); this._sources = []; this._sourceDroppedWrap = function () { self._sourceDropped.apply(self, arguments); }; }; Shared.addModule('Overview', Overview); Shared.mixin(Overview.prototype, 'Mixin.Common'); Shared.mixin(Overview.prototype, 'Mixin.ChainReactor'); Shared.mixin(Overview.prototype, 'Mixin.Constants'); Shared.mixin(Overview.prototype, 'Mixin.Triggers'); Shared.mixin(Overview.prototype, 'Mixin.Events'); Shared.mixin(Overview.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); DbDocument = _dereq_('./Document'); Db = Shared.modules.Db; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Overview.prototype, 'state'); Shared.synthesize(Overview.prototype, 'db'); Shared.synthesize(Overview.prototype, 'name'); Shared.synthesize(Overview.prototype, 'query', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Shared.synthesize(Overview.prototype, 'queryOptions', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Shared.synthesize(Overview.prototype, 'reduce', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Overview.prototype.from = function (source) { if (source !== undefined) { if (typeof(source) === 'string') { source = this._db.collection(source); } this._setFrom(source); return this; } return this._sources; }; Overview.prototype.find = function () { return this._collData.find.apply(this._collData, arguments); }; /** * Executes and returns the response from the current reduce method * assigned to the overview. * @returns {*} */ Overview.prototype.exec = function () { var reduceFunc = this.reduce(); return reduceFunc ? reduceFunc.apply(this) : undefined; }; Overview.prototype.count = function () { return this._collData.count.apply(this._collData, arguments); }; Overview.prototype._setFrom = function (source) { // Remove all source references while (this._sources.length) { this._removeSource(this._sources[0]); } this._addSource(source); return this; }; Overview.prototype._addSource = function (source) { if (source && source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } if (this._sources.indexOf(source) === -1) { this._sources.push(source); source.chain(this); source.on('drop', this._sourceDroppedWrap); this._refresh(); } return this; }; Overview.prototype._removeSource = function (source) { if (source && source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } var sourceIndex = this._sources.indexOf(source); if (sourceIndex > -1) { this._sources.splice(source, 1); source.unChain(this); source.off('drop', this._sourceDroppedWrap); this._refresh(); } return this; }; Overview.prototype._sourceDropped = function (source) { if (source) { // Source was dropped, remove from overview this._removeSource(source); } }; Overview.prototype._refresh = function () { if (!this.isDropped()) { if (this._sources && this._sources[0]) { this._collData.primaryKey(this._sources[0].primaryKey()); var tempArr = [], i; for (i = 0; i < this._sources.length; i++) { tempArr = tempArr.concat(this._sources[i].find(this._query, this._queryOptions)); } this._collData.setData(tempArr); } // Now execute the reduce method if (this._reduce) { var reducedData = this._reduce.apply(this); // Update the document with the newly returned data this._data.setData(reducedData); } } }; Overview.prototype._chainHandler = function (chainPacket) { switch (chainPacket.type) { case 'setData': case 'insert': case 'update': case 'remove': this._refresh(); break; default: break; } }; /** * Gets the module's internal data collection. * @returns {Collection} */ Overview.prototype.data = function () { return this._data; }; Overview.prototype.drop = function (callback) { if (!this.isDropped()) { this._state = 'dropped'; delete this._data; delete this._collData; // Remove all source references while (this._sources.length) { this._removeSource(this._sources[0]); } delete this._sources; if (this._db && this._name) { delete this._db._overview[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._listeners; } return true; }; Db.prototype.overview = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof Overview) { return name; } if (this._overview && this._overview[name]) { return this._overview[name]; } this._overview = this._overview || {}; this._overview[name] = new Overview(name).db(this); self.emit('create', self._overview[name], 'overview', name); return this._overview[name]; } else { // Return an object of collection data return this._overview || {}; } }; /** * Returns an array of overviews the DB currently has. * @returns {Array} An array of objects containing details of each overview * the database is currently managing. */ Db.prototype.overviews = function () { var arr = [], item, i; for (i in this._overview) { if (this._overview.hasOwnProperty(i)) { item = this._overview[i]; arr.push({ name: i, count: item.count(), linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Overview'); module.exports = Overview; },{"./Collection":5,"./Document":9,"./Shared":39}],33:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Gets a single value from the passed object and given path. * @param {Object} obj The object to inspect. * @param {String} path The path to retrieve data from. * @returns {*} */ Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; // Detect early exit if (path && path.indexOf('.') === -1) { return [obj[path]]; } if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.get(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":39}],34:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared = _dereq_('./Shared'), async = _dereq_('async'), localforage = _dereq_('localforage'), FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line Db, Collection, CollectionDrop, CollectionGroup, CollectionInit, DbInit, DbDrop, Persist, Overload;//, //DataVersion = '2.0'; /** * The persistent storage class handles loading and saving data to browser * storage. * @constructor */ Persist = function () { this.init.apply(this, arguments); }; /** * The local forage library. */ Persist.prototype.localforage = localforage; /** * The init method that can be overridden or extended. * @param {Db} db The ForerunnerDB database instance. */ Persist.prototype.init = function (db) { var self = this; this._encodeSteps = [ function () { return self._encode.apply(self, arguments); } ]; this._decodeSteps = [ function () { return self._decode.apply(self, arguments); } ]; // Check environment if (db.isClient()) { if (window.Storage !== undefined) { this.mode('localforage'); localforage.config({ driver: [ localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE ], name: String(db.core().name()), storeName: 'FDB' }); } } }; Shared.addModule('Persist', Persist); Shared.mixin(Persist.prototype, 'Mixin.ChainReactor'); Shared.mixin(Persist.prototype, 'Mixin.Common'); Db = Shared.modules.Db; Collection = _dereq_('./Collection'); CollectionDrop = Collection.prototype.drop; CollectionGroup = _dereq_('./CollectionGroup'); CollectionInit = Collection.prototype.init; DbInit = Db.prototype.init; DbDrop = Db.prototype.drop; Overload = Shared.overload; /** * Gets / sets the auto flag which determines if the persistence module * will automatically load data for collections the first time they are * accessed and save data whenever it changes. This is disabled by * default. * @param {Boolean} val Set to true to enable, false to disable * @returns {*} */ Shared.synthesize(Persist.prototype, 'auto', function (val) { var self = this; if (val !== undefined) { if (val) { // Hook db events this._db.on('create', function () { self._autoLoad.apply(self, arguments); }); this._db.on('change', function () { self._autoSave.apply(self, arguments); }); if (this._db.debug()) { console.log(this._db.logIdentifier() + ' Automatic load/save enabled'); } } else { // Un-hook db events this._db.off('create', this._autoLoad); this._db.off('change', this._autoSave); if (this._db.debug()) { console.log(this._db.logIdentifier() + ' Automatic load/save disbled'); } } } return this.$super.call(this, val); }); Persist.prototype._autoLoad = function (obj, objType, name) { var self = this; if (typeof obj.load === 'function') { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-loading data for ' + objType + ':', name); } obj.load(function (err, data) { if (err && self._db.debug()) { console.log(self._db.logIdentifier() + ' Automatic load failed:', err); } self.emit('load', err, data); }); } else { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-load for ' + objType + ':', name, 'no load method, skipping'); } } }; Persist.prototype._autoSave = function (obj, objType, name) { var self = this; if (typeof obj.save === 'function') { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-saving data for ' + objType + ':', name); } obj.save(function (err, data) { if (err && self._db.debug()) { console.log(self._db.logIdentifier() + ' Automatic save failed:', err); } self.emit('save', err, data); }); } }; /** * Gets / sets the persistent storage mode (the library used * to persist data to the browser - defaults to localForage). * @param {String} type The library to use for storage. Defaults * to localForage. * @returns {*} */ Persist.prototype.mode = function (type) { if (type !== undefined) { this._mode = type; return this; } return this._mode; }; /** * Gets / sets the driver used when persisting data. * @param {String} val Specify the driver type (LOCALSTORAGE, * WEBSQL or INDEXEDDB) * @returns {*} */ Persist.prototype.driver = function (val) { if (val !== undefined) { switch (val.toUpperCase()) { case 'LOCALSTORAGE': localforage.setDriver(localforage.LOCALSTORAGE); break; case 'WEBSQL': localforage.setDriver(localforage.WEBSQL); break; case 'INDEXEDDB': localforage.setDriver(localforage.INDEXEDDB); break; default: throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!'); } return this; } return localforage.driver(); }; /** * Starts a decode waterfall process. * @param {*} val The data to be decoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.decode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._decodeSteps), finished); }; /** * Starts an encode waterfall process. * @param {*} val The data to be encoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.encode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._encodeSteps), finished); }; Shared.synthesize(Persist.prototype, 'encodeSteps'); Shared.synthesize(Persist.prototype, 'decodeSteps'); /** * Adds an encode/decode step to the persistent storage system so * that you can add custom functionality. * @param {Function} encode The encode method called with the data from the * previous encode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the encoder will fail and throw an error. * @param {Function} decode The decode method called with the data from the * previous decode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the decoder will fail and throw an error. * @param {Number=} index Optional index to add the encoder step to. This * allows you to place a step before or after other existing steps. If not * provided your step is placed last in the list of steps. For instance if * you are providing an encryption step it makes sense to place this last * since all previous steps will then have their data encrypted by your * final step. */ Persist.prototype.addStep = new Overload({ 'object': function (obj) { this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0); }, 'function, function': function (encode, decode) { this.$main.call(this, encode, decode, 0); }, 'function, function, number': function (encode, decode, index) { this.$main.call(this, encode, decode, index); }, $main: function (encode, decode, index) { if (index === 0 || index === undefined) { this._encodeSteps.push(encode); this._decodeSteps.unshift(decode); } else { // Place encoder step at index then work out correct // index to place decoder step this._encodeSteps.splice(index, 0, encode); this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode); } } }); Persist.prototype.unwrap = function (dataStr) { var parts = dataStr.split('::fdb::'), data; switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } }; /** * Takes encoded data and decodes it for use as JS native objects and arrays. * @param {String} val The currently encoded string data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when decoding is * completed. * @private */ Persist.prototype._decode = function (val, meta, finished) { var parts, data; if (val) { parts = val.split('::fdb::'); switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } if (data) { meta.foundData = true; meta.rowCount = data.length || 0; } else { meta.foundData = false; meta.rowCount = 0; } if (finished) { finished(false, data, meta); } } else { meta.foundData = false; meta.rowCount = 0; if (finished) { finished(false, val, meta); } } }; /** * Takes native JS data and encodes it for for storage as a string. * @param {Object} val The current un-encoded data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when encoding is * completed. * @private */ Persist.prototype._encode = function (val, meta, finished) { var data = val; if (typeof val === 'object') { val = 'json::fdb::' + this.jStringify(val); } else { val = 'raw::fdb::' + val; } if (data) { meta.foundData = true; meta.rowCount = data.length || 0; } else { meta.foundData = false; meta.rowCount = 0; } if (finished) { finished(false, val, meta); } }; /** * Encodes passed data and then stores it in the browser's persistent * storage layer. * @param {String} key The key to store the data under in the persistent * storage. * @param {Object} data The data to store under the key. * @param {Function=} callback The method to call when the save process * has completed. */ Persist.prototype.save = function (key, data, callback) { switch (this.mode()) { case 'localforage': this.encode(data, function (err, data, tableStats) { if (!err) { localforage.setItem(key, data).then(function (data) { if (callback) { callback(false, data, tableStats); } }, function (err) { if (callback) { callback(err); } }); } else { callback(err); } }); break; default: if (callback) { callback('No data handler.'); } break; } }; /** * Loads and decodes data from the passed key. * @param {String} key The key to retrieve data from in the persistent * storage. * @param {Function=} callback The method to call when the load process * has completed. */ Persist.prototype.load = function (key, callback) { var self = this; switch (this.mode()) { case 'localforage': localforage.getItem(key).then(function (val) { self.decode(val, callback); }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; /** * Deletes data in persistent storage stored under the passed key. * @param {String} key The key to drop data for in the storage. * @param {Function=} callback The method to call when the data is dropped. */ Persist.prototype.drop = function (key, callback) { switch (this.mode()) { case 'localforage': localforage.removeItem(key).then(function () { if (callback) { callback(false); } }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; // Extend the Collection prototype with persist methods Collection.prototype.drop = new Overload({ /** * Drop collection and persistent storage. */ '': function () { if (!this.isDropped()) { this.drop(true); } }, /** * Drop collection and persistent storage with callback. * @param {Function} callback Callback method. */ 'function': function (callback) { if (!this.isDropped()) { this.drop(true, callback); } }, /** * Drop collection and optionally drop persistent storage. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. */ 'boolean': function (removePersistent) { if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name); this._db.persist.drop(this._db._name + '-' + this._name + '-metaData'); } } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } // Call the original method CollectionDrop.call(this); } }, /** * Drop collections and optionally drop persistent storage with callback. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. * @param {Function} callback Callback method. */ 'boolean, function': function (removePersistent, callback) { var self = this; if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name, function () { self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback); }); return CollectionDrop.call(this); } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); } } } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } } else { // Call the original method return CollectionDrop.call(this, callback); } } } }); /** * Saves an entire collection's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ Collection.prototype.save = function (callback) { var self = this, processSave; if (self._name) { if (self._db) { processSave = function () { // Save the collection data self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, data, tableStats) { if (!err) { self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, data, metaStats) { if (callback) { callback(err, data, tableStats, metaStats); } }); } else { if (callback) { callback(err); } } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads an entire collection's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ Collection.prototype.load = function (callback) { var self = this; if (self._name) { if (self._db) { // Load the collection data self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); //self.setData(data); } // Now load the collection's metadata self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); } } if (callback) { callback(err, tableStats, metaStats); } }); } else { if (callback) { callback(err); } } }); } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; /** * Gets the data that represents this collection for easy storage using * a third-party method / plugin instead of using the standard persistent * storage system. * @param {Function} callback The method to call with the data response. */ Collection.prototype.saveCustom = function (callback) { var self = this, myData = {}, processSave; if (self._name) { if (self._db) { processSave = function () { self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.data = { name: self._db._name + '-' + self._name, store: data, tableStats: tableStats }; self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.metaData = { name: self._db._name + '-' + self._name + '-metaData', store: data, tableStats: tableStats }; callback(false, myData); } else { callback(err); } }); } else { callback(err); } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads custom data loaded by a third-party plugin into the collection. * @param {Object} myData Data object previously saved by using saveCustom() * @param {Function} callback A callback method to receive notification when * data has loaded. */ Collection.prototype.loadCustom = function (myData, callback) { var self = this; if (self._name) { if (self._db) { if (myData.data && myData.data.store) { if (myData.metaData && myData.metaData.store) { self.decode(myData.data.store, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); self.decode(myData.metaData.store, function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); if (callback) { callback(err, tableStats, metaStats); } } } else { callback(err); } }); } } else { callback(err); } }); } else { callback('No "metaData" key found in passed object!'); } } else { callback('No "data" key found in passed object!'); } } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; // Override the DB init to instantiate the plugin Db.prototype.init = function () { DbInit.apply(this, arguments); this.persist = new Persist(this); }; Db.prototype.load = new Overload({ /** * Loads an entire database's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (myData, callback) { this.$main.call(this, myData, callback); }, '$main': function (myData, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, loadCallback, index; loadCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection load method if (!myData) { obj[index].load(loadCallback); } else { obj[index].loadCustom(myData, loadCallback); } } } } }); Db.prototype.save = new Overload({ /** * Saves an entire database's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (options, callback) { this.$main.call(this, options, callback); }, '$main': function (options, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, saveCallback, index; saveCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection save method if (!options.custom) { obj[index].save(saveCallback); } else { obj[index].saveCustom(saveCallback); } } } } }); Shared.finishModule('Persist'); module.exports = Persist; },{"./Collection":5,"./CollectionGroup":6,"./PersistCompress":35,"./PersistCrypto":36,"./Shared":39,"async":41,"localforage":76}],35:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), pako = _dereq_('pako'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); Plugin.prototype.encode = function (val, meta, finished) { var wrapper = { data: val, type: 'fdbCompress', enabled: false }, before, after, compressedVal; // Compress the data before = val.length; compressedVal = pako.deflate(val, {to: 'string'}); after = compressedVal.length; // If the compressed version is smaller than the original, use it! if (after < before) { wrapper.data = compressedVal; wrapper.enabled = true; } meta.compression = { enabled: wrapper.enabled, compressedBytes: after, uncompressedBytes: before, effect: Math.round((100 / before) * after) + '%' }; finished(false, this.jStringify(wrapper), meta); }; Plugin.prototype.decode = function (wrapper, meta, finished) { var compressionEnabled = false, data; if (wrapper) { wrapper = this.jParse(wrapper); // Check if we need to decompress the string if (wrapper.enabled) { data = pako.inflate(wrapper.data, {to: 'string'}); compressionEnabled = true; } else { data = wrapper.data; compressionEnabled = false; } meta.compression = { enabled: compressionEnabled }; if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, data, meta); } } }; // Register this plugin with ForerunnerDB Shared.plugins.FdbCompress = Plugin; module.exports = Plugin; },{"./Shared":39,"pako":77}],36:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), CryptoJS = _dereq_('crypto-js'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { // Ensure at least a password is passed in options if (!options || !options.pass) { throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.'); } this._algo = options.algo || 'AES'; this._pass = options.pass; }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); /** * Gets / sets the current pass-phrase being used to encrypt / decrypt * data with the plugin. */ Shared.synthesize(Plugin.prototype, 'pass'); Plugin.prototype.stringify = function (cipherParams) { // create json object with ciphertext var jsonObj = { ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64) }; // optionally add iv and salt if (cipherParams.iv) { jsonObj.iv = cipherParams.iv.toString(); } if (cipherParams.salt) { jsonObj.s = cipherParams.salt.toString(); } // stringify json object return this.jStringify(jsonObj); }; Plugin.prototype.parse = function (jsonStr) { // parse json string var jsonObj = this.jParse(jsonStr); // extract ciphertext from json object, and create cipher params object var cipherParams = CryptoJS.lib.CipherParams.create({ ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct) }); // optionally extract iv and salt if (jsonObj.iv) { cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv); } if (jsonObj.s) { cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s); } return cipherParams; }; Plugin.prototype.encode = function (val, meta, finished) { var self = this, wrapper = { type: 'fdbCrypto' }, encryptedVal; // Encrypt the data encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }); wrapper.data = encryptedVal.toString(); wrapper.enabled = true; meta.encryption = { enabled: wrapper.enabled }; if (finished) { finished(false, this.jStringify(wrapper), meta); } }; Plugin.prototype.decode = function (wrapper, meta, finished) { var self = this, data; if (wrapper) { wrapper = this.jParse(wrapper); data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }).toString(CryptoJS.enc.Utf8); if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, wrapper, meta); } } }; // Register this plugin with ForerunnerDB Shared.plugins.FdbCrypto = Plugin; module.exports = Plugin; },{"./Shared":39,"crypto-js":50}],37:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); delete this._listeners; } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":39}],38:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { var self = this; this._encoder = []; this._decoder = []; // Handler for Date() objects this.registerHandler('$date', function (objInstance) { if (objInstance instanceof Date) { // Augment this date object with a new toJSON method objInstance.toJSON = function () { return "$date:" + this.toISOString(); }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$date:') === 0) { return self.convert(new Date(data.substr(6))); } return undefined; }); // Handler for RegExp() objects this.registerHandler('$regexp', function (objInstance) { if (objInstance instanceof RegExp) { objInstance.toJSON = function () { return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : ''); /*return { source: this.source, params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '') };*/ }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$regexp:') === 0) { var dataStr = data.substr(8),//± lengthEnd = dataStr.indexOf(':'), sourceLength = Number(dataStr.substr(0, lengthEnd)), source = dataStr.substr(lengthEnd + 1, sourceLength), params = dataStr.substr(lengthEnd + sourceLength + 2); return self.convert(new RegExp(source, params)); } return undefined; }); }; Serialiser.prototype.registerHandler = function (handles, encoder, decoder) { if (handles !== undefined) { // Register encoder this._encoder.push(encoder); // Register decoder this._decoder.push(decoder); } }; Serialiser.prototype.convert = function (data) { // Run through converters and check for match var arr = this._encoder, i; for (i = 0; i < arr.length; i++) { if (arr[i](data)) { // The converter we called matched the object and converted it // so let's return it now. return data; } } // No converter matched the object, return the unaltered one return data; }; Serialiser.prototype.reviver = function () { var arr = this._decoder; return function (key, value) { // Check if we have a decoder method for this key var decodedData, i; for (i = 0; i < arr.length; i++) { decodedData = arr[i](value); if (decodedData !== undefined) { // The decoder we called matched the object and decoded it // so let's return it now. return decodedData; } } // No decoder, return basic value return value; }; }; module.exports = Serialiser; },{}],39:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.755', modules: {}, plugins: {}, index: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":18,"./Mixin.ChainReactor":19,"./Mixin.Common":20,"./Mixin.Constants":21,"./Mixin.Events":22,"./Mixin.Matching":23,"./Mixin.Sorting":24,"./Mixin.Tags":25,"./Mixin.Triggers":26,"./Mixin.Updating":27,"./Overload":31}],40:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket, Overload = _dereq_('./Overload'), Path, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.Matching'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); Shared.mixin(View.prototype, 'Mixin.Triggers'); Shared.mixin(View.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; Path = Shared.modules.Path; sharedPathSolver = new Path(); View.prototype.init = function (name, query, options) { var self = this; this.sharedPathSolver = sharedPathSolver; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._data = new Collection(this.name() + '_internal'); }; /** * This reactor IO node is given data changes from source data and * then acts as a firewall process between the source and view data. * Data needs to meet the requirements this IO node imposes before * the data is passed down the reactor chain (to the view). This * allows us to intercept data changes from the data source and act * on them such as applying transforms, checking the data matches * the view's query, applying joins to the data etc before sending it * down the reactor chain via the this.chainSend() calls. * * Update packets are especially complex to handle because an update * on the underlying source data could translate into an insert, * update or remove call on the view. Take a scenario where the view's * query limits the data see from the source. If the source data is * updated and the data now falls inside the view's query limitations * the data is technically now an insert on the view, not an update. * The same is true in reverse where the update becomes a remove. If * the updated data already exists in the view and will still exist * after the update operation then the update can remain an update. * @param {Object} chainPacket The chain reactor packet representing the * data operation that has just been processed on the source data. * @param {View} self The reference to the view we are operating for. * @private */ View.prototype._handleChainIO = function (chainPacket, self) { var type = chainPacket.type, hasActiveJoin, hasActiveQuery, hasTransformIn, sharedData; // NOTE: "self" in this context is the view instance. // NOTE: "this" in this context is the ReactorIO node sitting in // between the source (sender) and the destination (listener) and // in this case the source is the view's "from" data source and the // destination is the view's _data collection. This means // that "this.chainSend()" is asking the ReactorIO node to send the // packet on to the destination listener. // EARLY EXIT: Check that the packet is not a CRUD operation if (type !== 'setData' && type !== 'insert' && type !== 'update' && type !== 'remove') { // This packet is NOT a CRUD operation packet so exit early! // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } // We only need to check packets under three conditions // 1) We have a limiting query on the view "active query", // 2) We have a query options with a $join clause on the view "active join" // 3) We have a transformIn operation registered on the view. // If none of these conditions exist we can just allow the chain // packet to proceed as normal hasActiveJoin = Boolean(self._querySettings.options && self._querySettings.options.$join); hasActiveQuery = Boolean(self._querySettings.query); hasTransformIn = self._data._transformIn !== undefined; // EARLY EXIT: Check for any complex operation flags and if none // exist, send the packet on and exit early if (!hasActiveJoin && !hasActiveQuery && !hasTransformIn) { // We don't have any complex operation flags so exit early! // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } // We have either an active query, active join or a transformIn // function registered on the view // We create a shared data object here so that the disparate method // calls can share data with each other via this object whilst // still remaining separate methods to keep code relatively clean. sharedData = { dataArr: [], removeArr: [] }; // Check the packet type to get the data arrays to work on if (chainPacket.type === 'insert') { // Check if the insert data is an array if (chainPacket.data.dataSet instanceof Array) { // Use the insert data array sharedData.dataArr = chainPacket.data.dataSet; } else { // Generate an array from the single insert object sharedData.dataArr = [chainPacket.data.dataSet]; } } else if (chainPacket.type === 'update') { // Use the dataSet array sharedData.dataArr = chainPacket.data.dataSet; } else if (chainPacket.type === 'remove') { if (chainPacket.data.dataSet instanceof Array) { // Use the remove data array sharedData.removeArr = chainPacket.data.dataSet; } else { // Generate an array from the single remove object sharedData.removeArr = [chainPacket.data.dataSet]; } } // Safety check if (!(sharedData.dataArr instanceof Array)) { // This shouldn't happen, let's log it console.warn('WARNING: dataArr being processed by chain reactor in View class is inconsistent!'); sharedData.dataArr = []; } if (!(sharedData.removeArr instanceof Array)) { // This shouldn't happen, let's log it console.warn('WARNING: removeArr being processed by chain reactor in View class is inconsistent!'); sharedData.removeArr = []; } // We need to operate in this order: // 1) Check if there is an active join - active joins are operated // against the SOURCE data. The joined data can potentially be // utilised by any active query or transformIn so we do this step first. // 2) Check if there is an active query - this is a query that is run // against the SOURCE data after any active joins have been resolved // on the source data. This allows an active query to operate on data // that would only exist after an active join has been executed. // If the source data does not fall inside the limiting factors of the // active query then we add it to a removal array. If it does fall // inside the limiting factors when we add it to an upsert array. This // is because data that falls inside the query could end up being // either new data or updated data after a transformIn operation. // 3) Check if there is a transformIn function. If a transformIn function // exist we run it against the data after doing any active join and // active query. if (hasActiveJoin) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin'); } self._handleChainIO_ActiveJoin(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin'); } } if (hasActiveQuery) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery'); } self._handleChainIO_ActiveQuery(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery'); } } if (hasTransformIn) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_TransformIn'); } self._handleChainIO_TransformIn(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_TransformIn'); } } // Check if we still have data to operate on and exit // if there is none left if (!sharedData.dataArr.length && !sharedData.removeArr.length) { // There is no more data to operate on, exit without // sending any data down the chain reactor (return true // will tell reactor to exit without continuing)! return true; } // Grab the public data collection's primary key sharedData.pk = self._data.primaryKey(); // We still have data left, let's work out how to handle it // first let's loop through the removals as these are easy if (sharedData.removeArr.length) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_RemovePackets'); } self._handleChainIO_RemovePackets(this, chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_RemovePackets'); } } if (sharedData.dataArr.length) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets'); } self._handleChainIO_UpsertPackets(this, chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets'); } } // Now return true to tell the chain reactor not to propagate // the data itself as we have done all that work here return true; }; View.prototype._handleChainIO_ActiveJoin = function (chainPacket, sharedData) { var dataArr = sharedData.dataArr, removeArr; // Since we have an active join, all we need to do is operate // the join clause on each item in the packet's data array. removeArr = this.applyJoin(dataArr, this._querySettings.options.$join, {}, {}); // Now that we've run our join keep in mind that joins can exclude data // if there is no matching joined data and the require: true clause in // the join options is enabled. This means we have to store a removal // array that tells us which items from the original data we sent to // join did not match the join data and were set with a require flag. // Now that we have our array of items to remove, let's run through the // original data and remove them from there. this.spliceArrayByIndexList(dataArr, removeArr); // Make sure we add any items we removed to the shared removeArr sharedData.removeArr = sharedData.removeArr.concat(removeArr); }; View.prototype._handleChainIO_ActiveQuery = function (chainPacket, sharedData) { var self = this, dataArr = sharedData.dataArr, i; // Now we need to run the data against the active query to // see if the data should be in the final data list or not, // so we use the _match method. // Loop backwards so we can safely splice from the array // while we are looping for (i = dataArr.length - 1; i >= 0; i--) { if (!self._match(dataArr[i], self._querySettings.query, self._querySettings.options, 'and', {})) { // The data didn't match the active query, add it // to the shared removeArr sharedData.removeArr.push(dataArr[i]); // Now remove it from the shared dataArr dataArr.splice(i, 1); } } }; View.prototype._handleChainIO_TransformIn = function (chainPacket, sharedData) { var self = this, dataArr = sharedData.dataArr, removeArr = sharedData.removeArr, dataIn = self._data._transformIn, i; // At this stage we take the remaining items still left in the data // array and run our transformIn method on each one, modifying it // from what it was to what it should be on the view. We also have // to run this on items we want to remove too because transforms can // affect primary keys and therefore stop us from identifying the // correct items to run removal operations on. // It is important that these are transformed BEFORE they are passed // to the CRUD methods because we use the CU data to check the position // of the item in the array and that can only happen if it is already // pre-transformed. The removal stuff also needs pre-transformed // because ids can be modified by a transform. for (i = 0; i < dataArr.length; i++) { // Assign the new value dataArr[i] = dataIn(dataArr[i]); } for (i = 0; i < removeArr.length; i++) { // Assign the new value removeArr[i] = dataIn(removeArr[i]); } }; View.prototype._handleChainIO_RemovePackets = function (ioObj, chainPacket, sharedData) { var $or = [], pk = sharedData.pk, removeArr = sharedData.removeArr, packet = { dataSet: removeArr, query: { $or: $or } }, orObj, i; for (i = 0; i < removeArr.length; i++) { orObj = {}; orObj[pk] = removeArr[i][pk]; $or.push(orObj); } ioObj.chainSend('remove', packet); }; View.prototype._handleChainIO_UpsertPackets = function (ioObj, chainPacket, sharedData) { var data = this._data, primaryIndex = data._primaryIndex, primaryCrc = data._primaryCrc, pk = sharedData.pk, dataArr = sharedData.dataArr, arrItem, insertArr = [], updateArr = [], query, i; // Let's work out what type of operation this data should // generate between an insert or an update. for (i = 0; i < dataArr.length; i++) { arrItem = dataArr[i]; // Check if the data already exists in the data if (primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (primaryCrc.get(arrItem[pk]) !== this.hash(arrItem[pk])) { // The document exists in the data collection but data differs, update required updateArr.push(arrItem); } } else { // The document is missing from this collection, insert required insertArr.push(arrItem); } } if (insertArr.length) { ioObj.chainSend('insert', { dataSet: insertArr }); } if (updateArr.length) { for (i = 0; i < updateArr.length; i++) { arrItem = updateArr[i]; query = {}; query[pk] = arrItem[pk]; ioObj.chainSend('update', { query: query, update: arrItem, dataSet: [arrItem] }); } } }; /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Queries the view data for a single document. * @see Collection::findOne() * @returns {Object} The result of the find query. */ View.prototype.findOne = function (query, options) { return this._data.findOne(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this._data.findById(id, options); }; /** * Queries the view data in a sub-array. * @see Collection::findSub() * @returns {Array} The result of the find query. */ View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._data.findSub(match, path, subDocQuery, subDocOptions); }; /** * Queries the view data in a sub-array and returns first match. * @see Collection::findSubOne() * @returns {Object} The result of the find query. */ View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this._data.findSubOne(match, path, subDocQuery, subDocOptions); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._data; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @param {Function=} callback A callback method. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source, callback) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); // Remove the current reference to the _from since we // are about to replace it with a new one delete this._from; } // Check if we have an existing reactor io that links the // previous _from source to the view's internal data if (this._io) { // Drop the io and remove it this._io.drop(); delete this._io; } // Check if we were passed a source name rather than a // reference to a source object if (typeof(source) === 'string') { // We were passed a name, assume it is a collection and // get the reference to the collection of that name source = this._db.collection(source); } // Check if we were passed a reference to a view rather than // a collection. Views need to be handled slightly differently // since their data is stored in an internal data collection // rather than actually being a direct data source themselves. if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source._data; if (this.debug()) { console.log(this.logIdentifier() + ' Using internal data "' + source.instanceIdentifier() + '" for IO graph linking'); } } // Assign the new data source as the view's _from this._from = source; // Hook the new data source's drop event so we can unhook // it as a data source if it gets dropped. This is important // so that we don't run into problems using a dropped source // for active data. this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's _from source and determines how they should be interpreted by // this view. See the _handleChainIO() method which does all the chain packet // processing for the view. this._io = new ReactorIO(this._from, this, function (chainPacket) { return self._handleChainIO.call(this, chainPacket, self); }); // Set the view's internal data primary key to the same as the // current active _from data source this._data.primaryKey(source.primaryKey()); // Do the initial data lookup and populate the view's internal data // since at this point we don't actually have any data in the view // yet. var collData = source.find(this._querySettings.query, this._querySettings.options); this._data.setData(collData, {}, callback); // If we have an active query and that query has an $orderBy clause, // update our active bucket which allows us to keep track of where // data should be placed in our internal data array. This is about // ordering of data and making sure that we maintain an ordered array // so that if we have data-binding we can place an item in the data- // bound view at the correct location. Active buckets use quick-sort // algorithms to quickly determine the position of an item inside an // existing array based on a sort protocol. if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, updates, primaryKey, item, currentIndex; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data: ' + chainPacket.type); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._data.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); this._data.setData(collData); // Rebuild active bucket as well this.rebuildActiveBucket(this._querySettings.options); break; case 'insert': if (this.debug()) { console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._data.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Make sure we are working with an array if (!(chainPacket.data.dataSet instanceof Array)) { chainPacket.data.dataSet = [chainPacket.data.dataSet]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data.dataSet; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); this._data._insertHandle(arr[index], insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._data._data.length; this._data._insertHandle(chainPacket.data.dataSet, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._data.name() + '"'); } primaryKey = this._data.primaryKey(); // Do the update updates = this._data._handleUpdate( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._data._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._data._updateSpliceMove(this._data._data, currentIndex, insertIndex); } } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._data.name() + '"'); } this._data.remove(chainPacket.data.query, chainPacket.options); if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the dataSet and remove the objects from the ActiveBucket arr = chainPacket.data.dataSet; count = arr.length; for (index = 0; index < count; index++) { this._activeBucket.remove(arr[index]); } } break; default: break; } }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._data.ensureIndex.apply(this._data, arguments); }; /** /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._data.on.apply(this._data, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._data.off.apply(this._data, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._data.emit.apply(this._data, arguments); }; /** * Emits an event. * @see Mixin.Events::deferEmit() */ View.prototype.deferEmit = function () { return this._data.deferEmit.apply(this._data, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { return this._data.distinct(key, query, options); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this._data.primaryKey(); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._data) { this._data.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._chain; delete this._from; delete this._data; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } return false; }; /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} * @deprecated Use query(<query>, <options>, <refresh>) instead. Query * now supports being presented with multiple different variations of * arguments. */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._data.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._data.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } } if (query !== undefined) { this.emit('queryChange', query); } if (options !== undefined) { this.emit('queryOptionsChange', options); } if (query !== undefined || options !== undefined) { return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } if (query !== undefined) { this.emit('queryChange', query); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } if (query !== undefined) { this.emit('queryChange', query); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = new Overload({ '': function () { return this._querySettings.query; }, 'object': function (query) { return this.$main.call(this, query, undefined, true); }, '*, boolean': function (query, refresh) { return this.$main.call(this, query, undefined, refresh); }, 'object, object': function (query, options) { return this.$main.call(this, query, options, true); }, '*, *, boolean': function (query, options, refresh) { return this.$main.call(this, query, options, refresh); }, '$main': function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._data.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._data.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } } if (query !== undefined) { this.emit('queryChange', query); } if (options !== undefined) { this.emit('queryOptionsChange', options); } if (query !== undefined || options !== undefined) { return this; } return this._querySettings; } }); /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { // TODO: This could be wasteful if the previous options $orderBy was identical, do a hash and check first! this.rebuildActiveBucket(options.$orderBy); } if (options !== undefined) { this.emit('queryOptionsChange', options); } return this; } return this._querySettings.options; }; /** * Clears the existing active bucket and builds a new one based * on the passed orderBy object (if one is passed). * @param {Object=} orderBy The orderBy object describing how to * order any data. */ View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._data._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._data.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { var self = this, refreshResults, joinArr, i, k; if (this._from) { // Clear the private data collection which will propagate to the public data // collection automatically via the chain reactor node between them this._data.remove(); // Grab all the data from the underlying data source refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); // Insert the underlying data into the private data collection this._data.insert(refreshResults); // Store the current cursor data this._data._data.$cursor = refreshResults.$cursor; this._data._data.$cursor = refreshResults.$cursor; } if (this._querySettings && this._querySettings.options && this._querySettings.options.$join && this._querySettings.options.$join.length) { // Define the change handler method self.__joinChange = self.__joinChange || function () { self._joinChange(); }; // Check for existing join collections if (this._joinCollections && this._joinCollections.length) { // Loop the join collections and remove change listeners // Loop the collections and hook change events for (i = 0; i < this._joinCollections.length; i++) { this._db.collection(this._joinCollections[i]).off('immediateChange', self.__joinChange); } } // Now start hooking any new / existing joins joinArr = this._querySettings.options.$join; this._joinCollections = []; // Loop the joined collections and hook change events for (i = 0; i < joinArr.length; i++) { for (k in joinArr[i]) { if (joinArr[i].hasOwnProperty(k)) { this._joinCollections.push(k); } } } if (this._joinCollections.length) { // Loop the collections and hook change events for (i = 0; i < this._joinCollections.length; i++) { this._db.collection(this._joinCollections[i]).on('immediateChange', self.__joinChange); } } } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Handles when a change has occurred on a collection that is joined * by query to this view. * @param objName * @param objType * @private */ View.prototype._joinChange = function (objName, objType) { this.emit('joinChange'); // TODO: This is a really dirty solution because it will require a complete // TODO: rebuild of the view data. We need to implement an IO handler to // TODO: selectively update the data of the view based on the joined // TODO: collection data operation. // FIXME: This isnt working, major performance killer, invest in some IO from chain reactor to make this a targeted call this.refresh(); }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { return this._data.count.apply(this._data, arguments); }; // Call underlying View.prototype.subset = function () { return this._data.subset.apply(this._data, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" * and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { var currentSettings, newSettings; currentSettings = this._data.transform(); this._data.transform(obj); newSettings = this._data.transform(); // Check if transforms are enabled, a dataIn method is set and these // settings did not match the previous transform settings if (newSettings.enabled && newSettings.dataIn && (currentSettings.enabled !== newSettings.enabled || currentSettings.dataIn !== newSettings.dataIn)) { // The data in the view is now stale, refresh it this.refresh(); } return newSettings; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return this._data.filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.data = function () { return this._data; }; /** * @see Collection.indexOf * @returns {*} */ View.prototype.indexOf = function () { return this._data.indexOf.apply(this._data, arguments); }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this._data.db(db); // Apply the same debug settings this.debug(db.debug()); this._data.debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} name The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (name) { var self = this; // Handle being passed an instance if (name instanceof View) { return name; } if (this._view[name]) { return this._view[name]; } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + name); } this._view[name] = new View(name).db(this); self.emit('create', self._view[name], 'view', name); return this._view[name]; }; /** * Determine if a view with the passed name already exists. * @param {String} name The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (name) { return Boolean(this._view[name]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":2,"./Collection":5,"./CollectionGroup":6,"./Overload":31,"./ReactorIO":37,"./Shared":39}],41:[function(_dereq_,module,exports){ (function (process,global){ /*! * async * https://github.com/caolan/async * * Copyright 2010-2014 Caolan McMahon * Released under the MIT license */ (function () { var async = {}; function noop() {} function identity(v) { return v; } function toBool(v) { return !!v; } function notId(v) { return !v; } // global on the server, window in the browser var previous_async; // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. var root = typeof self === 'object' && self.self === self && self || typeof global === 'object' && global.global === global && global || this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { return function() { if (fn === null) throw new Error("Callback was already called."); fn.apply(this, arguments); fn = null; }; } function _once(fn) { return function() { if (fn === null) return; fn.apply(this, arguments); fn = null; }; } //// cross-browser compatiblity functions //// var _toString = Object.prototype.toString; var _isArray = Array.isArray || function (obj) { return _toString.call(obj) === '[object Array]'; }; // Ported from underscore.js isObject var _isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; function _isArrayLike(arr) { return _isArray(arr) || ( // has a positive integer length property typeof arr.length === "number" && arr.length >= 0 && arr.length % 1 === 0 ); } function _arrayEach(arr, iterator) { var index = -1, length = arr.length; while (++index < length) { iterator(arr[index], index, arr); } } function _map(arr, iterator) { var index = -1, length = arr.length, result = Array(length); while (++index < length) { result[index] = iterator(arr[index], index, arr); } return result; } function _range(count) { return _map(Array(count), function (v, i) { return i; }); } function _reduce(arr, iterator, memo) { _arrayEach(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; } function _forEachOf(object, iterator) { _arrayEach(_keys(object), function (key) { iterator(object[key], key); }); } function _indexOf(arr, item) { for (var i = 0; i < arr.length; i++) { if (arr[i] === item) return i; } return -1; } var _keys = Object.keys || function (obj) { var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; function _keyIterator(coll) { var i = -1; var len; var keys; if (_isArrayLike(coll)) { len = coll.length; return function next() { i++; return i < len ? i : null; }; } else { keys = _keys(coll); len = keys.length; return function next() { i++; return i < len ? keys[i] : null; }; } } // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) // This accumulates the arguments passed into an array, after a given index. // From underscore.js (https://github.com/jashkenas/underscore/pull/2140). function _restParam(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0); var rest = Array(length); for (var index = 0; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); } // Currently unused but handle cases outside of the switch statement: // var args = Array(startIndex + 1); // for (index = 0; index < startIndex; index++) { // args[index] = arguments[index]; // } // args[startIndex] = rest; // return func.apply(this, args); }; } function _withoutIndex(iterator) { return function (value, index, callback) { return iterator(value, callback); }; } //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// // capture the global reference to guard against fakeTimer mocks var _setImmediate = typeof setImmediate === 'function' && setImmediate; var _delay = _setImmediate ? function(fn) { // not a direct alias for IE10 compatibility _setImmediate(fn); } : function(fn) { setTimeout(fn, 0); }; if (typeof process === 'object' && typeof process.nextTick === 'function') { async.nextTick = process.nextTick; } else { async.nextTick = _delay; } async.setImmediate = _setImmediate ? _delay : async.nextTick; async.forEach = async.each = function (arr, iterator, callback) { return async.eachOf(arr, _withoutIndex(iterator), callback); }; async.forEachSeries = async.eachSeries = function (arr, iterator, callback) { return async.eachOfSeries(arr, _withoutIndex(iterator), callback); }; async.forEachLimit = async.eachLimit = function (arr, limit, iterator, callback) { return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback); }; async.forEachOf = async.eachOf = function (object, iterator, callback) { callback = _once(callback || noop); object = object || []; var iter = _keyIterator(object); var key, completed = 0; while ((key = iter()) != null) { completed += 1; iterator(object[key], key, only_once(done)); } if (completed === 0) callback(null); function done(err) { completed--; if (err) { callback(err); } // Check key is null in case iterator isn't exhausted // and done resolved synchronously. else if (key === null && completed <= 0) { callback(null); } } }; async.forEachOfSeries = async.eachOfSeries = function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); var key = nextKey(); function iterate() { var sync = true; if (key === null) { return callback(null); } iterator(obj[key], key, only_once(function (err) { if (err) { callback(err); } else { key = nextKey(); if (key === null) { return callback(null); } else { if (sync) { async.setImmediate(iterate); } else { iterate(); } } } })); sync = false; } iterate(); }; async.forEachOfLimit = async.eachOfLimit = function (obj, limit, iterator, callback) { _eachOfLimit(limit)(obj, iterator, callback); }; function _eachOfLimit(limit) { return function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); if (limit <= 0) { return callback(null); } var done = false; var running = 0; var errored = false; (function replenish () { if (done && running <= 0) { return callback(null); } while (running < limit && !errored) { var key = nextKey(); if (key === null) { done = true; if (running <= 0) { callback(null); } return; } running += 1; iterator(obj[key], key, only_once(function (err) { running -= 1; if (err) { callback(err); errored = true; } else { replenish(); } })); } })(); }; } function doParallel(fn) { return function (obj, iterator, callback) { return fn(async.eachOf, obj, iterator, callback); }; } function doParallelLimit(fn) { return function (obj, limit, iterator, callback) { return fn(_eachOfLimit(limit), obj, iterator, callback); }; } function doSeries(fn) { return function (obj, iterator, callback) { return fn(async.eachOfSeries, obj, iterator, callback); }; } function _asyncMap(eachfn, arr, iterator, callback) { callback = _once(callback || noop); arr = arr || []; var results = _isArrayLike(arr) ? [] : {}; eachfn(arr, function (value, index, callback) { iterator(value, function (err, v) { results[index] = v; callback(err); }); }, function (err) { callback(err, results); }); } async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = doParallelLimit(_asyncMap); // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.inject = async.foldl = async.reduce = function (arr, memo, iterator, callback) { async.eachOfSeries(arr, function (x, i, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; async.foldr = async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, identity).reverse(); async.reduce(reversed, memo, iterator, callback); }; async.transform = function (arr, memo, iterator, callback) { if (arguments.length === 3) { callback = iterator; iterator = memo; memo = _isArray(arr) ? [] : {}; } async.eachOf(arr, function(v, k, cb) { iterator(memo, v, k, cb); }, function(err) { callback(err, memo); }); }; function _filter(eachfn, arr, iterator, callback) { var results = []; eachfn(arr, function (x, index, callback) { iterator(x, function (v) { if (v) { results.push({index: index, value: x}); } callback(); }); }, function () { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); } async.select = async.filter = doParallel(_filter); async.selectLimit = async.filterLimit = doParallelLimit(_filter); async.selectSeries = async.filterSeries = doSeries(_filter); function _reject(eachfn, arr, iterator, callback) { _filter(eachfn, arr, function(value, cb) { iterator(value, function(v) { cb(!v); }); }, callback); } async.reject = doParallel(_reject); async.rejectLimit = doParallelLimit(_reject); async.rejectSeries = doSeries(_reject); function _createTester(eachfn, check, getResult) { return function(arr, limit, iterator, cb) { function done() { if (cb) cb(getResult(false, void 0)); } function iteratee(x, _, callback) { if (!cb) return callback(); iterator(x, function (v) { if (cb && check(v)) { cb(getResult(true, x)); cb = iterator = false; } callback(); }); } if (arguments.length > 3) { eachfn(arr, limit, iteratee, done); } else { cb = iterator; iterator = limit; eachfn(arr, iteratee, done); } }; } async.any = async.some = _createTester(async.eachOf, toBool, identity); async.someLimit = _createTester(async.eachOfLimit, toBool, identity); async.all = async.every = _createTester(async.eachOf, notId, notId); async.everyLimit = _createTester(async.eachOfLimit, notId, notId); function _findGetResult(v, x) { return x; } async.detect = _createTester(async.eachOf, identity, _findGetResult); async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult); async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult); async.sortBy = function (arr, iterator, callback) { async.map(arr, function (x, callback) { iterator(x, function (err, criteria) { if (err) { callback(err); } else { callback(null, {value: x, criteria: criteria}); } }); }, function (err, results) { if (err) { return callback(err); } else { callback(null, _map(results.sort(comparator), function (x) { return x.value; })); } }); function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } }; async.auto = function (tasks, concurrency, callback) { if (typeof arguments[1] === 'function') { // concurrency is optional, shift the args. callback = concurrency; concurrency = null; } callback = _once(callback || noop); var keys = _keys(tasks); var remainingTasks = keys.length; if (!remainingTasks) { return callback(null); } if (!concurrency) { concurrency = remainingTasks; } var results = {}; var runningTasks = 0; var hasError = false; var listeners = []; function addListener(fn) { listeners.unshift(fn); } function removeListener(fn) { var idx = _indexOf(listeners, fn); if (idx >= 0) listeners.splice(idx, 1); } function taskComplete() { remainingTasks--; _arrayEach(listeners.slice(0), function (fn) { fn(); }); } addListener(function () { if (!remainingTasks) { callback(null, results); } }); _arrayEach(keys, function (k) { if (hasError) return; var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; var taskCallback = _restParam(function(err, args) { runningTasks--; if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _forEachOf(results, function(val, rkey) { safeResults[rkey] = val; }); safeResults[k] = args; hasError = true; callback(err, safeResults); } else { results[k] = args; async.setImmediate(taskComplete); } }); var requires = task.slice(0, task.length - 1); // prevent dead-locks var len = requires.length; var dep; while (len--) { if (!(dep = tasks[requires[len]])) { throw new Error('Has nonexistent dependency in ' + requires.join(', ')); } if (_isArray(dep) && _indexOf(dep, k) >= 0) { throw new Error('Has cyclic dependencies'); } } function ready() { return runningTasks < concurrency && _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); } if (ready()) { runningTasks++; task[task.length - 1](taskCallback, results); } else { addListener(listener); } function listener() { if (ready()) { runningTasks++; removeListener(listener); task[task.length - 1](taskCallback, results); } } }); }; async.retry = function(times, task, callback) { var DEFAULT_TIMES = 5; var DEFAULT_INTERVAL = 0; var attempts = []; var opts = { times: DEFAULT_TIMES, interval: DEFAULT_INTERVAL }; function parseTimes(acc, t){ if(typeof t === 'number'){ acc.times = parseInt(t, 10) || DEFAULT_TIMES; } else if(typeof t === 'object'){ acc.times = parseInt(t.times, 10) || DEFAULT_TIMES; acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL; } else { throw new Error('Unsupported argument type for \'times\': ' + typeof t); } } var length = arguments.length; if (length < 1 || length > 3) { throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)'); } else if (length <= 2 && typeof times === 'function') { callback = task; task = times; } if (typeof times !== 'function') { parseTimes(opts, times); } opts.callback = callback; opts.task = task; function wrappedTask(wrappedCallback, wrappedResults) { function retryAttempt(task, finalAttempt) { return function(seriesCallback) { task(function(err, result){ seriesCallback(!err || finalAttempt, {err: err, result: result}); }, wrappedResults); }; } function retryInterval(interval){ return function(seriesCallback){ setTimeout(function(){ seriesCallback(null); }, interval); }; } while (opts.times) { var finalAttempt = !(opts.times-=1); attempts.push(retryAttempt(opts.task, finalAttempt)); if(!finalAttempt && opts.interval > 0){ attempts.push(retryInterval(opts.interval)); } } async.series(attempts, function(done, data){ data = data[data.length - 1]; (wrappedCallback || opts.callback)(data.err, data.result); }); } // If a callback is passed, run this as a controll flow return opts.callback ? wrappedTask() : wrappedTask; }; async.waterfall = function (tasks, callback) { callback = _once(callback || noop); if (!_isArray(tasks)) { var err = new Error('First argument to waterfall must be an array of functions'); return callback(err); } if (!tasks.length) { return callback(); } function wrapIterator(iterator) { return _restParam(function (err, args) { if (err) { callback.apply(null, [err].concat(args)); } else { var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } ensureAsync(iterator).apply(null, args); } }); } wrapIterator(async.iterator(tasks))(); }; function _parallel(eachfn, tasks, callback) { callback = callback || noop; var results = _isArrayLike(tasks) ? [] : {}; eachfn(tasks, function (task, key, callback) { task(_restParam(function (err, args) { if (args.length <= 1) { args = args[0]; } results[key] = args; callback(err); })); }, function (err) { callback(err, results); }); } async.parallel = function (tasks, callback) { _parallel(async.eachOf, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel(_eachOfLimit(limit), tasks, callback); }; async.series = function(tasks, callback) { _parallel(async.eachOfSeries, tasks, callback); }; async.iterator = function (tasks) { function makeCallback(index) { function fn() { if (tasks.length) { tasks[index].apply(null, arguments); } return fn.next(); } fn.next = function () { return (index < tasks.length - 1) ? makeCallback(index + 1): null; }; return fn; } return makeCallback(0); }; async.apply = _restParam(function (fn, args) { return _restParam(function (callArgs) { return fn.apply( null, args.concat(callArgs) ); }); }); function _concat(eachfn, arr, fn, callback) { var result = []; eachfn(arr, function (x, index, cb) { fn(x, function (err, y) { result = result.concat(y || []); cb(err); }); }, function (err) { callback(err, result); }); } async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { callback = callback || noop; if (test()) { var next = _restParam(function(err, args) { if (err) { callback(err); } else if (test.apply(this, args)) { iterator(next); } else { callback.apply(null, [null].concat(args)); } }); iterator(next); } else { callback(null); } }; async.doWhilst = function (iterator, test, callback) { var calls = 0; return async.whilst(function() { return ++calls <= 1 || test.apply(this, arguments); }, iterator, callback); }; async.until = function (test, iterator, callback) { return async.whilst(function() { return !test.apply(this, arguments); }, iterator, callback); }; async.doUntil = function (iterator, test, callback) { return async.doWhilst(iterator, function() { return !test.apply(this, arguments); }, callback); }; async.during = function (test, iterator, callback) { callback = callback || noop; var next = _restParam(function(err, args) { if (err) { callback(err); } else { args.push(check); test.apply(this, args); } }); var check = function(err, truth) { if (err) { callback(err); } else if (truth) { iterator(next); } else { callback(null); } }; test(check); }; async.doDuring = function (iterator, test, callback) { var calls = 0; async.during(function(next) { if (calls++ < 1) { next(null, true); } else { test.apply(this, arguments); } }, iterator, callback); }; function _queue(worker, concurrency, payload) { if (concurrency == null) { concurrency = 1; } else if(concurrency === 0) { throw new Error('Concurrency must not be zero'); } function _insert(q, data, pos, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0 && q.idle()) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, callback: callback || noop }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.tasks.length === q.concurrency) { q.saturated(); } }); async.setImmediate(q.process); } function _next(q, tasks) { return function(){ workers -= 1; var removed = false; var args = arguments; _arrayEach(tasks, function (task) { _arrayEach(workersList, function (worker, index) { if (worker === task && !removed) { workersList.splice(index, 1); removed = true; } }); task.callback.apply(task, args); }); if (q.tasks.length + workers === 0) { q.drain(); } q.process(); }; } var workers = 0; var workersList = []; var q = { tasks: [], concurrency: concurrency, payload: payload, saturated: noop, empty: noop, drain: noop, started: false, paused: false, push: function (data, callback) { _insert(q, data, false, callback); }, kill: function () { q.drain = noop; q.tasks = []; }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { while(!q.paused && workers < q.concurrency && q.tasks.length){ var tasks = q.payload ? q.tasks.splice(0, q.payload) : q.tasks.splice(0, q.tasks.length); var data = _map(tasks, function (task) { return task.data; }); if (q.tasks.length === 0) { q.empty(); } workers += 1; workersList.push(tasks[0]); var cb = only_once(_next(q, tasks)); worker(data, cb); } }, length: function () { return q.tasks.length; }, running: function () { return workers; }, workersList: function () { return workersList; }, idle: function() { return q.tasks.length + workers === 0; }, pause: function () { q.paused = true; }, resume: function () { if (q.paused === false) { return; } q.paused = false; var resumeCount = Math.min(q.concurrency, q.tasks.length); // Need to call q.process once per concurrent // worker to preserve full concurrency after pause for (var w = 1; w <= resumeCount; w++) { async.setImmediate(q.process); } } }; return q; } async.queue = function (worker, concurrency) { var q = _queue(function (items, cb) { worker(items[0], cb); }, concurrency, 1); return q; }; async.priorityQueue = function (worker, concurrency) { function _compareTasks(a, b){ return a.priority - b.priority; } function _binarySearch(sequence, item, compare) { var beg = -1, end = sequence.length - 1; while (beg < end) { var mid = beg + ((end - beg + 1) >>> 1); if (compare(item, sequence[mid]) >= 0) { beg = mid; } else { end = mid - 1; } } return beg; } function _insert(q, data, priority, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, priority: priority, callback: typeof callback === 'function' ? callback : noop }; q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); if (q.tasks.length === q.concurrency) { q.saturated(); } async.setImmediate(q.process); }); } // Start with a normal queue var q = async.queue(worker, concurrency); // Override push to accept second parameter representing priority q.push = function (data, priority, callback) { _insert(q, data, priority, callback); }; // Remove unshift function delete q.unshift; return q; }; async.cargo = function (worker, payload) { return _queue(worker, 1, payload); }; function _console_fn(name) { return _restParam(function (fn, args) { fn.apply(null, args.concat([_restParam(function (err, args) { if (typeof console === 'object') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _arrayEach(args, function (x) { console[name](x); }); } } })])); }); } async.log = _console_fn('log'); async.dir = _console_fn('dir'); /*async.info = _console_fn('info'); async.warn = _console_fn('warn'); async.error = _console_fn('error');*/ async.memoize = function (fn, hasher) { var memo = {}; var queues = {}; var has = Object.prototype.hasOwnProperty; hasher = hasher || identity; var memoized = _restParam(function memoized(args) { var callback = args.pop(); var key = hasher.apply(null, args); if (has.call(memo, key)) { async.setImmediate(function () { callback.apply(null, memo[key]); }); } else if (has.call(queues, key)) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([_restParam(function (args) { memo[key] = args; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, args); } })])); } }); memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; function _times(mapper) { return function (count, iterator, callback) { mapper(_range(count), iterator, callback); }; } async.times = _times(async.map); async.timesSeries = _times(async.mapSeries); async.timesLimit = function (count, limit, iterator, callback) { return async.mapLimit(_range(count), limit, iterator, callback); }; async.seq = function (/* functions... */) { var fns = arguments; return _restParam(function (args) { var that = this; var callback = args[args.length - 1]; if (typeof callback == 'function') { args.pop(); } else { callback = noop; } async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([_restParam(function (err, nextargs) { cb(err, nextargs); })])); }, function (err, results) { callback.apply(that, [err].concat(results)); }); }); }; async.compose = function (/* functions... */) { return async.seq.apply(null, Array.prototype.reverse.call(arguments)); }; function _applyEach(eachfn) { return _restParam(function(fns, args) { var go = _restParam(function(args) { var that = this; var callback = args.pop(); return eachfn(fns, function (fn, _, cb) { fn.apply(that, args.concat([cb])); }, callback); }); if (args.length) { return go.apply(this, args); } else { return go; } }); } async.applyEach = _applyEach(async.eachOf); async.applyEachSeries = _applyEach(async.eachOfSeries); async.forever = function (fn, callback) { var done = only_once(callback || noop); var task = ensureAsync(fn); function next(err) { if (err) { return done(err); } task(next); } next(); }; function ensureAsync(fn) { return _restParam(function (args) { var callback = args.pop(); args.push(function () { var innerArgs = arguments; if (sync) { async.setImmediate(function () { callback.apply(null, innerArgs); }); } else { callback.apply(null, innerArgs); } }); var sync = true; fn.apply(this, args); sync = false; }); } async.ensureAsync = ensureAsync; async.constant = _restParam(function(values) { var args = [null].concat(values); return function (callback) { return callback.apply(this, args); }; }); async.wrapSync = async.asyncify = function asyncify(func) { return _restParam(function (args) { var callback = args.pop(); var result; try { result = func.apply(this, args); } catch (e) { return callback(e); } // if result is Promise object if (_isObject(result) && typeof result.then === "function") { result.then(function(value) { callback(null, value); })["catch"](function(err) { callback(err.message ? err : new Error(err)); }); } else { callback(null, result); } }); }; // Node.js if (typeof module === 'object' && module.exports) { module.exports = async; } // AMD / RequireJS else if (typeof define === 'function' && define.amd) { define([], function () { return async; }); } // included directly via <script> tag else { root.async = async; } }()); }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":93}],42:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Lookup tables var SBOX = []; var INV_SBOX = []; var SUB_MIX_0 = []; var SUB_MIX_1 = []; var SUB_MIX_2 = []; var SUB_MIX_3 = []; var INV_SUB_MIX_0 = []; var INV_SUB_MIX_1 = []; var INV_SUB_MIX_2 = []; var INV_SUB_MIX_3 = []; // Compute lookup tables (function () { // Compute double table var d = []; for (var i = 0; i < 256; i++) { if (i < 128) { d[i] = i << 1; } else { d[i] = (i << 1) ^ 0x11b; } } // Walk GF(2^8) var x = 0; var xi = 0; for (var i = 0; i < 256; i++) { // Compute sbox var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; SBOX[x] = sx; INV_SBOX[sx] = x; // Compute multiplication var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; // Compute sub bytes, mix columns tables var t = (d[sx] * 0x101) ^ (sx * 0x1010100); SUB_MIX_0[x] = (t << 24) | (t >>> 8); SUB_MIX_1[x] = (t << 16) | (t >>> 16); SUB_MIX_2[x] = (t << 8) | (t >>> 24); SUB_MIX_3[x] = t; // Compute inv sub bytes, inv mix columns tables var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); INV_SUB_MIX_3[sx] = t; // Compute next counter if (!x) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } }()); // Precomputed Rcon lookup var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; /** * AES block cipher algorithm. */ var AES = C_algo.AES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySize = key.sigBytes / 4; // Compute number of rounds var nRounds = this._nRounds = keySize + 6 // Compute number of key schedule rows var ksRows = (nRounds + 1) * 4; // Compute key schedule var keySchedule = this._keySchedule = []; for (var ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { keySchedule[ksRow] = keyWords[ksRow]; } else { var t = keySchedule[ksRow - 1]; if (!(ksRow % keySize)) { // Rot word t = (t << 8) | (t >>> 24); // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; // Mix Rcon t ^= RCON[(ksRow / keySize) | 0] << 24; } else if (keySize > 6 && ksRow % keySize == 4) { // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; } keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; } } // Compute inv key schedule var invKeySchedule = this._invKeySchedule = []; for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { var ksRow = ksRows - invKsRow; if (invKsRow % 4) { var t = keySchedule[ksRow]; } else { var t = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t; } else { invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; } } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); }, decryptBlock: function (M, offset) { // Swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); // Inv swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; }, _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { // Shortcut var nRounds = this._nRounds; // Get input, add round key var s0 = M[offset] ^ keySchedule[0]; var s1 = M[offset + 1] ^ keySchedule[1]; var s2 = M[offset + 2] ^ keySchedule[2]; var s3 = M[offset + 3] ^ keySchedule[3]; // Key schedule row counter var ksRow = 4; // Rounds for (var round = 1; round < nRounds; round++) { // Shift rows, sub bytes, mix columns, add round key var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; // Update state s0 = t0; s1 = t1; s2 = t2; s3 = t3; } // Shift rows, sub bytes, add round key var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; // Set output M[offset] = t0; M[offset + 1] = t1; M[offset + 2] = t2; M[offset + 3] = t3; }, keySize: 256/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); */ C.AES = BlockCipher._createHelper(AES); }()); return CryptoJS.AES; })); },{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],43:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher core components. */ CryptoJS.lib.Cipher || (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var Base64 = C_enc.Base64; var C_algo = C.algo; var EvpKDF = C_algo.EvpKDF; /** * Abstract base cipher template. * * @property {number} keySize This cipher's key size. Default: 4 (128 bits) * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. */ var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ /** * Configuration options. * * @property {WordArray} iv The IV to use for this operation. */ cfg: Base.extend(), /** * Creates this cipher in encryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); */ createEncryptor: function (key, cfg) { return this.create(this._ENC_XFORM_MODE, key, cfg); }, /** * Creates this cipher in decryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); */ createDecryptor: function (key, cfg) { return this.create(this._DEC_XFORM_MODE, key, cfg); }, /** * Initializes a newly created cipher. * * @param {number} xformMode Either the encryption or decryption transormation mode constant. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @example * * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); */ init: function (xformMode, key, cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Store transform mode and key this._xformMode = xformMode; this._key = key; // Set initial values this.reset(); }, /** * Resets this cipher to its initial state. * * @example * * cipher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-cipher logic this._doReset(); }, /** * Adds data to be encrypted or decrypted. * * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. * * @return {WordArray} The data after processing. * * @example * * var encrypted = cipher.process('data'); * var encrypted = cipher.process(wordArray); */ process: function (dataUpdate) { // Append this._append(dataUpdate); // Process available blocks return this._process(); }, /** * Finalizes the encryption or decryption process. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. * * @return {WordArray} The data after final processing. * * @example * * var encrypted = cipher.finalize(); * var encrypted = cipher.finalize('data'); * var encrypted = cipher.finalize(wordArray); */ finalize: function (dataUpdate) { // Final data update if (dataUpdate) { this._append(dataUpdate); } // Perform concrete-cipher logic var finalProcessedData = this._doFinalize(); return finalProcessedData; }, keySize: 128/32, ivSize: 128/32, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, /** * Creates shortcut functions to a cipher's object interface. * * @param {Cipher} cipher The cipher to create a helper for. * * @return {Object} An object with encrypt and decrypt shortcut functions. * * @static * * @example * * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); */ _createHelper: (function () { function selectCipherStrategy(key) { if (typeof key == 'string') { return PasswordBasedCipher; } else { return SerializableCipher; } } return function (cipher) { return { encrypt: function (message, key, cfg) { return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); }, decrypt: function (ciphertext, key, cfg) { return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); } }; }; }()) }); /** * Abstract base stream cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) */ var StreamCipher = C_lib.StreamCipher = Cipher.extend({ _doFinalize: function () { // Process partial blocks var finalProcessedBlocks = this._process(!!'flush'); return finalProcessedBlocks; }, blockSize: 1 }); /** * Mode namespace. */ var C_mode = C.mode = {}; /** * Abstract base block cipher mode template. */ var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ /** * Creates this mode for encryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); */ createEncryptor: function (cipher, iv) { return this.Encryptor.create(cipher, iv); }, /** * Creates this mode for decryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); */ createDecryptor: function (cipher, iv) { return this.Decryptor.create(cipher, iv); }, /** * Initializes a newly created mode. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @example * * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); */ init: function (cipher, iv) { this._cipher = cipher; this._iv = iv; } }); /** * Cipher Block Chaining mode. */ var CBC = C_mode.CBC = (function () { /** * Abstract base CBC mode. */ var CBC = BlockCipherMode.extend(); /** * CBC encryptor. */ CBC.Encryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // XOR and encrypt xorBlock.call(this, words, offset, blockSize); cipher.encryptBlock(words, offset); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); /** * CBC decryptor. */ CBC.Decryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); // Decrypt and XOR cipher.decryptBlock(words, offset); xorBlock.call(this, words, offset, blockSize); // This block becomes the previous block this._prevBlock = thisBlock; } }); function xorBlock(words, offset, blockSize) { // Shortcut var iv = this._iv; // Choose mixing block if (iv) { var block = iv; // Remove IV for subsequent blocks this._iv = undefined; } else { var block = this._prevBlock; } // XOR blocks for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } } return CBC; }()); /** * Padding namespace. */ var C_pad = C.pad = {}; /** * PKCS #5/7 padding strategy. */ var Pkcs7 = C_pad.Pkcs7 = { /** * Pads data using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to pad. * @param {number} blockSize The multiple that the data should be padded to. * * @static * * @example * * CryptoJS.pad.Pkcs7.pad(wordArray, 4); */ pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Create padding word var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; // Create padding var paddingWords = []; for (var i = 0; i < nPaddingBytes; i += 4) { paddingWords.push(paddingWord); } var padding = WordArray.create(paddingWords, nPaddingBytes); // Add padding data.concat(padding); }, /** * Unpads data that had been padded using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to unpad. * * @static * * @example * * CryptoJS.pad.Pkcs7.unpad(wordArray); */ unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; /** * Abstract base block cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) */ var BlockCipher = C_lib.BlockCipher = Cipher.extend({ /** * Configuration options. * * @property {Mode} mode The block mode to use. Default: CBC * @property {Padding} padding The padding strategy to use. Default: Pkcs7 */ cfg: Cipher.cfg.extend({ mode: CBC, padding: Pkcs7 }), reset: function () { // Reset cipher Cipher.reset.call(this); // Shortcuts var cfg = this.cfg; var iv = cfg.iv; var mode = cfg.mode; // Reset block mode if (this._xformMode == this._ENC_XFORM_MODE) { var modeCreator = mode.createEncryptor; } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { var modeCreator = mode.createDecryptor; // Keep at least one block in the buffer for unpadding this._minBufferSize = 1; } this._mode = modeCreator.call(mode, this, iv && iv.words); }, _doProcessBlock: function (words, offset) { this._mode.processBlock(words, offset); }, _doFinalize: function () { // Shortcut var padding = this.cfg.padding; // Finalize if (this._xformMode == this._ENC_XFORM_MODE) { // Pad data padding.pad(this._data, this.blockSize); // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); // Unpad data padding.unpad(finalProcessedBlocks); } return finalProcessedBlocks; }, blockSize: 128/32 }); /** * A collection of cipher parameters. * * @property {WordArray} ciphertext The raw ciphertext. * @property {WordArray} key The key to this ciphertext. * @property {WordArray} iv The IV used in the ciphering operation. * @property {WordArray} salt The salt used with a key derivation function. * @property {Cipher} algorithm The cipher algorithm. * @property {Mode} mode The block mode used in the ciphering operation. * @property {Padding} padding The padding scheme used in the ciphering operation. * @property {number} blockSize The block size of the cipher. * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. */ var CipherParams = C_lib.CipherParams = Base.extend({ /** * Initializes a newly created cipher params object. * * @param {Object} cipherParams An object with any of the possible cipher parameters. * * @example * * var cipherParams = CryptoJS.lib.CipherParams.create({ * ciphertext: ciphertextWordArray, * key: keyWordArray, * iv: ivWordArray, * salt: saltWordArray, * algorithm: CryptoJS.algo.AES, * mode: CryptoJS.mode.CBC, * padding: CryptoJS.pad.PKCS7, * blockSize: 4, * formatter: CryptoJS.format.OpenSSL * }); */ init: function (cipherParams) { this.mixIn(cipherParams); }, /** * Converts this cipher params object to a string. * * @param {Format} formatter (Optional) The formatting strategy to use. * * @return {string} The stringified cipher params. * * @throws Error If neither the formatter nor the default formatter is set. * * @example * * var string = cipherParams + ''; * var string = cipherParams.toString(); * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ toString: function (formatter) { return (formatter || this.formatter).stringify(this); } }); /** * Format namespace. */ var C_format = C.format = {}; /** * OpenSSL formatting strategy. */ var OpenSSLFormatter = C_format.OpenSSL = { /** * Converts a cipher params object to an OpenSSL-compatible string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The OpenSSL-compatible string. * * @static * * @example * * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); */ stringify: function (cipherParams) { // Shortcuts var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; // Format if (salt) { var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); } else { var wordArray = ciphertext; } return wordArray.toString(Base64); }, /** * Converts an OpenSSL-compatible string to a cipher params object. * * @param {string} openSSLStr The OpenSSL-compatible string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); */ parse: function (openSSLStr) { // Parse base64 var ciphertext = Base64.parse(openSSLStr); // Shortcut var ciphertextWords = ciphertext.words; // Test for salt if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { // Extract salt var salt = WordArray.create(ciphertextWords.slice(2, 4)); // Remove salt from ciphertext ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext: ciphertext, salt: salt }); } }; /** * A cipher wrapper that returns ciphertext as a serializable cipher params object. */ var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** * Configuration options. * * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } } }); /** * Key derivation function namespace. */ var C_kdf = C.kdf = {}; /** * OpenSSL key derivation function. */ var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); } }; /** * A serializable cipher wrapper that derives the key from a password, * and returns ciphertext as a serializable cipher params object. */ var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }()); })); },{"./core":44}],44:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD define([], factory); } else { // Global (browser) root.CryptoJS = factory(); } }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { function F() {} return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn F.prototype = this; var subtype = new F(); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init')) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); },{}],45:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex != -1) { base64StrLength = paddingIndex; } } // Convert var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); var bitsCombined = bits1 | bits2; words[nBytes >>> 2] |= (bitsCombined) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }()); return CryptoJS.enc.Base64; })); },{"./core":44}],46:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * UTF-16 BE encoding strategy. */ var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { /** * Converts a word array to a UTF-16 BE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 BE string. * * @static * * @example * * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 BE string to a word array. * * @param {string} utf16Str The UTF-16 BE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); } return WordArray.create(words, utf16StrLength * 2); } }; /** * UTF-16 LE encoding strategy. */ C_enc.Utf16LE = { /** * Converts a word array to a UTF-16 LE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 LE string. * * @static * * @example * * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 LE string to a word array. * * @param {string} utf16Str The UTF-16 LE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); } return WordArray.create(words, utf16StrLength * 2); } }; function swapEndian(word) { return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); } }()); return CryptoJS.enc.Utf16; })); },{"./core":44}],47:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var MD5 = C_algo.MD5; /** * This key derivation function is meant to conform with EVP_BytesToKey. * www.openssl.org/docs/crypto/EVP_BytesToKey.html */ var EvpKDF = C_algo.EvpKDF = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hash algorithm to use. Default: MD5 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: MD5, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.EvpKDF.create(); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init hasher var hasher = cfg.hasher.create(); // Initial values var derivedKey = WordArray.create(); // Shortcuts var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } var block = hasher.update(password).finalize(salt); hasher.reset(); // Iterations for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.EvpKDF(password, salt); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); */ C.EvpKDF = function (password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); }; }()); return CryptoJS.EvpKDF; })); },{"./core":44,"./hmac":49,"./sha1":68}],48:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var CipherParams = C_lib.CipherParams; var C_enc = C.enc; var Hex = C_enc.Hex; var C_format = C.format; var HexFormatter = C_format.Hex = { /** * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The hexadecimally encoded string. * * @static * * @example * * var hexString = CryptoJS.format.Hex.stringify(cipherParams); */ stringify: function (cipherParams) { return cipherParams.ciphertext.toString(Hex); }, /** * Converts a hexadecimally encoded ciphertext string to a cipher params object. * * @param {string} input The hexadecimally encoded string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.Hex.parse(hexString); */ parse: function (input) { var ciphertext = Hex.parse(input); return CipherParams.create({ ciphertext: ciphertext }); } }; }()); return CryptoJS.format.Hex; })); },{"./cipher-core":43,"./core":44}],49:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var C_algo = C.algo; /** * HMAC algorithm. */ var HMAC = C_algo.HMAC = Base.extend({ /** * Initializes a newly created HMAC. * * @param {Hasher} hasher The hash algorithm to use. * @param {WordArray|string} key The secret key. * * @example * * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); */ init: function (hasher, key) { // Init hasher hasher = this._hasher = new hasher.init(); // Convert string to WordArray, else assume WordArray already if (typeof key == 'string') { key = Utf8.parse(key); } // Shortcuts var hasherBlockSize = hasher.blockSize; var hasherBlockSizeBytes = hasherBlockSize * 4; // Allow arbitrary length keys if (key.sigBytes > hasherBlockSizeBytes) { key = hasher.finalize(key); } // Clamp excess bits key.clamp(); // Clone key for inner and outer pads var oKey = this._oKey = key.clone(); var iKey = this._iKey = key.clone(); // Shortcuts var oKeyWords = oKey.words; var iKeyWords = iKey.words; // XOR keys with pad constants for (var i = 0; i < hasherBlockSize; i++) { oKeyWords[i] ^= 0x5c5c5c5c; iKeyWords[i] ^= 0x36363636; } oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; // Set initial values this.reset(); }, /** * Resets this HMAC to its initial state. * * @example * * hmacHasher.reset(); */ reset: function () { // Shortcut var hasher = this._hasher; // Reset hasher.reset(); hasher.update(this._iKey); }, /** * Updates this HMAC with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {HMAC} This HMAC instance. * * @example * * hmacHasher.update('message'); * hmacHasher.update(wordArray); */ update: function (messageUpdate) { this._hasher.update(messageUpdate); // Chainable return this; }, /** * Finalizes the HMAC computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The HMAC. * * @example * * var hmac = hmacHasher.finalize(); * var hmac = hmacHasher.finalize('message'); * var hmac = hmacHasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Shortcut var hasher = this._hasher; // Compute HMAC var innerHash = hasher.finalize(messageUpdate); hasher.reset(); var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); return hmac; } }); }()); })); },{"./core":44}],50:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory); } else { // Global (browser) root.CryptoJS = factory(root.CryptoJS); } }(this, function (CryptoJS) { return CryptoJS; })); },{"./aes":42,"./cipher-core":43,"./core":44,"./enc-base64":45,"./enc-utf16":46,"./evpkdf":47,"./format-hex":48,"./hmac":49,"./lib-typedarrays":51,"./md5":52,"./mode-cfb":53,"./mode-ctr":55,"./mode-ctr-gladman":54,"./mode-ecb":56,"./mode-ofb":57,"./pad-ansix923":58,"./pad-iso10126":59,"./pad-iso97971":60,"./pad-nopadding":61,"./pad-zeropadding":62,"./pbkdf2":63,"./rabbit":65,"./rabbit-legacy":64,"./rc4":66,"./ripemd160":67,"./sha1":68,"./sha224":69,"./sha256":70,"./sha3":71,"./sha384":72,"./sha512":73,"./tripledes":74,"./x64-core":75}],51:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Check if typed arrays are supported if (typeof ArrayBuffer != 'function') { return; } // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; // Reference original init var superInit = WordArray.init; // Augment WordArray.init to handle typed arrays var subInit = WordArray.init = function (typedArray) { // Convert buffers to uint8 if (typedArray instanceof ArrayBuffer) { typedArray = new Uint8Array(typedArray); } // Convert other array views to uint8 if ( typedArray instanceof Int8Array || (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array ) { typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); } // Handle Uint8Array if (typedArray instanceof Uint8Array) { // Shortcut var typedArrayByteLength = typedArray.byteLength; // Extract bytes var words = []; for (var i = 0; i < typedArrayByteLength; i++) { words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); } // Initialize this word array superInit.call(this, words, typedArrayByteLength); } else { // Else call normal init superInit.apply(this, arguments); } }; subInit.prototype = WordArray; }()); return CryptoJS.lib.WordArray; })); },{"./core":44}],52:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var T = []; // Compute constants (function () { for (var i = 0; i < 64; i++) { T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; } }()); /** * MD5 hash algorithm. */ var MD5 = C_algo.MD5 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 ]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcuts var H = this._hash.words; var M_offset_0 = M[offset + 0]; var M_offset_1 = M[offset + 1]; var M_offset_2 = M[offset + 2]; var M_offset_3 = M[offset + 3]; var M_offset_4 = M[offset + 4]; var M_offset_5 = M[offset + 5]; var M_offset_6 = M[offset + 6]; var M_offset_7 = M[offset + 7]; var M_offset_8 = M[offset + 8]; var M_offset_9 = M[offset + 9]; var M_offset_10 = M[offset + 10]; var M_offset_11 = M[offset + 11]; var M_offset_12 = M[offset + 12]; var M_offset_13 = M[offset + 13]; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; // Working varialbes var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; // Computation a = FF(a, b, c, d, M_offset_0, 7, T[0]); d = FF(d, a, b, c, M_offset_1, 12, T[1]); c = FF(c, d, a, b, M_offset_2, 17, T[2]); b = FF(b, c, d, a, M_offset_3, 22, T[3]); a = FF(a, b, c, d, M_offset_4, 7, T[4]); d = FF(d, a, b, c, M_offset_5, 12, T[5]); c = FF(c, d, a, b, M_offset_6, 17, T[6]); b = FF(b, c, d, a, M_offset_7, 22, T[7]); a = FF(a, b, c, d, M_offset_8, 7, T[8]); d = FF(d, a, b, c, M_offset_9, 12, T[9]); c = FF(c, d, a, b, M_offset_10, 17, T[10]); b = FF(b, c, d, a, M_offset_11, 22, T[11]); a = FF(a, b, c, d, M_offset_12, 7, T[12]); d = FF(d, a, b, c, M_offset_13, 12, T[13]); c = FF(c, d, a, b, M_offset_14, 17, T[14]); b = FF(b, c, d, a, M_offset_15, 22, T[15]); a = GG(a, b, c, d, M_offset_1, 5, T[16]); d = GG(d, a, b, c, M_offset_6, 9, T[17]); c = GG(c, d, a, b, M_offset_11, 14, T[18]); b = GG(b, c, d, a, M_offset_0, 20, T[19]); a = GG(a, b, c, d, M_offset_5, 5, T[20]); d = GG(d, a, b, c, M_offset_10, 9, T[21]); c = GG(c, d, a, b, M_offset_15, 14, T[22]); b = GG(b, c, d, a, M_offset_4, 20, T[23]); a = GG(a, b, c, d, M_offset_9, 5, T[24]); d = GG(d, a, b, c, M_offset_14, 9, T[25]); c = GG(c, d, a, b, M_offset_3, 14, T[26]); b = GG(b, c, d, a, M_offset_8, 20, T[27]); a = GG(a, b, c, d, M_offset_13, 5, T[28]); d = GG(d, a, b, c, M_offset_2, 9, T[29]); c = GG(c, d, a, b, M_offset_7, 14, T[30]); b = GG(b, c, d, a, M_offset_12, 20, T[31]); a = HH(a, b, c, d, M_offset_5, 4, T[32]); d = HH(d, a, b, c, M_offset_8, 11, T[33]); c = HH(c, d, a, b, M_offset_11, 16, T[34]); b = HH(b, c, d, a, M_offset_14, 23, T[35]); a = HH(a, b, c, d, M_offset_1, 4, T[36]); d = HH(d, a, b, c, M_offset_4, 11, T[37]); c = HH(c, d, a, b, M_offset_7, 16, T[38]); b = HH(b, c, d, a, M_offset_10, 23, T[39]); a = HH(a, b, c, d, M_offset_13, 4, T[40]); d = HH(d, a, b, c, M_offset_0, 11, T[41]); c = HH(c, d, a, b, M_offset_3, 16, T[42]); b = HH(b, c, d, a, M_offset_6, 23, T[43]); a = HH(a, b, c, d, M_offset_9, 4, T[44]); d = HH(d, a, b, c, M_offset_12, 11, T[45]); c = HH(c, d, a, b, M_offset_15, 16, T[46]); b = HH(b, c, d, a, M_offset_2, 23, T[47]); a = II(a, b, c, d, M_offset_0, 6, T[48]); d = II(d, a, b, c, M_offset_7, 10, T[49]); c = II(c, d, a, b, M_offset_14, 15, T[50]); b = II(b, c, d, a, M_offset_5, 21, T[51]); a = II(a, b, c, d, M_offset_12, 6, T[52]); d = II(d, a, b, c, M_offset_3, 10, T[53]); c = II(c, d, a, b, M_offset_10, 15, T[54]); b = II(b, c, d, a, M_offset_1, 21, T[55]); a = II(a, b, c, d, M_offset_8, 6, T[56]); d = II(d, a, b, c, M_offset_15, 10, T[57]); c = II(c, d, a, b, M_offset_6, 15, T[58]); b = II(b, c, d, a, M_offset_13, 21, T[59]); a = II(a, b, c, d, M_offset_4, 6, T[60]); d = II(d, a, b, c, M_offset_11, 10, T[61]); c = II(c, d, a, b, M_offset_2, 15, T[62]); b = II(b, c, d, a, M_offset_9, 21, T[63]); // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); var nBitsTotalL = nBitsTotal; dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) ); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 4; i++) { // Shortcut var H_i = H[i]; H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function FF(a, b, c, d, x, s, t) { var n = a + ((b & c) | (~b & d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function GG(a, b, c, d, x, s, t) { var n = a + ((b & d) | (c & ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function HH(a, b, c, d, x, s, t) { var n = a + (b ^ c ^ d) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function II(a, b, c, d, x, s, t) { var n = a + (c ^ (b | ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.MD5('message'); * var hash = CryptoJS.MD5(wordArray); */ C.MD5 = Hasher._createHelper(MD5); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacMD5(message, key); */ C.HmacMD5 = Hasher._createHmacHelper(MD5); }(Math)); return CryptoJS.MD5; })); },{"./core":44}],53:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher Feedback block mode. */ CryptoJS.mode.CFB = (function () { var CFB = CryptoJS.lib.BlockCipherMode.extend(); CFB.Encryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); CFB.Decryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // This block becomes the previous block this._prevBlock = thisBlock; } }); function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { // Shortcut var iv = this._iv; // Generate keystream if (iv) { var keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } else { var keystream = this._prevBlock; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } return CFB; }()); return CryptoJS.mode.CFB; })); },{"./cipher-core":43,"./core":44}],54:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve * Counter block mode compatible with Dr Brian Gladman fileenc.c * derived from CryptoJS.mode.CTR * Jan Hruby jhruby.web@gmail.com */ CryptoJS.mode.CTRGladman = (function () { var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); function incWord(word) { if (((word >> 24) & 0xff) === 0xff) { //overflow var b1 = (word >> 16)&0xff; var b2 = (word >> 8)&0xff; var b3 = word & 0xff; if (b1 === 0xff) // overflow b1 { b1 = 0; if (b2 === 0xff) { b2 = 0; if (b3 === 0xff) { b3 = 0; } else { ++b3; } } else { ++b2; } } else { ++b1; } word = 0; word += (b1 << 16); word += (b2 << 8); word += b3; } else { word += (0x01 << 24); } return word; } function incCounter(counter) { if ((counter[0] = incWord(counter[0])) === 0) { // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 counter[1] = incWord(counter[1]); } return counter; } var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } incCounter(counter); var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTRGladman.Decryptor = Encryptor; return CTRGladman; }()); return CryptoJS.mode.CTRGladman; })); },{"./cipher-core":43,"./core":44}],55:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Counter block mode. */ CryptoJS.mode.CTR = (function () { var CTR = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = CTR.Encryptor = CTR.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Increment counter counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTR.Decryptor = Encryptor; return CTR; }()); return CryptoJS.mode.CTR; })); },{"./cipher-core":43,"./core":44}],56:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Electronic Codebook block mode. */ CryptoJS.mode.ECB = (function () { var ECB = CryptoJS.lib.BlockCipherMode.extend(); ECB.Encryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.encryptBlock(words, offset); } }); ECB.Decryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.decryptBlock(words, offset); } }); return ECB; }()); return CryptoJS.mode.ECB; })); },{"./cipher-core":43,"./core":44}],57:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Output Feedback block mode. */ CryptoJS.mode.OFB = (function () { var OFB = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = OFB.Encryptor = OFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var keystream = this._keystream; // Generate keystream if (iv) { keystream = this._keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); OFB.Decryptor = Encryptor; return OFB; }()); return CryptoJS.mode.OFB; })); },{"./cipher-core":43,"./core":44}],58:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ANSI X.923 padding strategy. */ CryptoJS.pad.AnsiX923 = { pad: function (data, blockSize) { // Shortcuts var dataSigBytes = data.sigBytes; var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; // Compute last byte position var lastBytePos = dataSigBytes + nPaddingBytes - 1; // Pad data.clamp(); data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); data.sigBytes += nPaddingBytes; }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Ansix923; })); },{"./cipher-core":43,"./core":44}],59:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO 10126 padding strategy. */ CryptoJS.pad.Iso10126 = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Pad data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Iso10126; })); },{"./cipher-core":43,"./core":44}],60:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO/IEC 9797-1 Padding Method 2. */ CryptoJS.pad.Iso97971 = { pad: function (data, blockSize) { // Add 0x80 byte data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); // Zero pad the rest CryptoJS.pad.ZeroPadding.pad(data, blockSize); }, unpad: function (data) { // Remove zero padding CryptoJS.pad.ZeroPadding.unpad(data); // Remove one more byte -- the 0x80 byte data.sigBytes--; } }; return CryptoJS.pad.Iso97971; })); },{"./cipher-core":43,"./core":44}],61:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":43,"./core":44}],62:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Zero padding strategy. */ CryptoJS.pad.ZeroPadding = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Pad data.clamp(); data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); }, unpad: function (data) { // Shortcut var dataWords = data.words; // Unpad var i = data.sigBytes - 1; while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { i--; } data.sigBytes = i + 1; } }; return CryptoJS.pad.ZeroPadding; })); },{"./cipher-core":43,"./core":44}],63:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA1 = C_algo.SHA1; var HMAC = C_algo.HMAC; /** * Password-Based Key Derivation Function 2 algorithm. */ var PBKDF2 = C_algo.PBKDF2 = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hasher to use. Default: SHA1 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: SHA1, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.PBKDF2.create(); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init HMAC var hmac = HMAC.create(cfg.hasher, password); // Initial values var derivedKey = WordArray.create(); var blockIndex = WordArray.create([0x00000001]); // Shortcuts var derivedKeyWords = derivedKey.words; var blockIndexWords = blockIndex.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { var block = hmac.update(salt).finalize(blockIndex); hmac.reset(); // Shortcuts var blockWords = block.words; var blockWordsLength = blockWords.length; // Iterations var intermediate = block; for (var i = 1; i < iterations; i++) { intermediate = hmac.finalize(intermediate); hmac.reset(); // Shortcut var intermediateWords = intermediate.words; // XOR intermediate with block for (var j = 0; j < blockWordsLength; j++) { blockWords[j] ^= intermediateWords[j]; } } derivedKey.concat(block); blockIndexWords[0]++; } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.PBKDF2(password, salt); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); */ C.PBKDF2 = function (password, salt, cfg) { return PBKDF2.create(cfg).compute(password, salt); }; }()); return CryptoJS.PBKDF2; })); },{"./core":44,"./hmac":49,"./sha1":68}],64:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm. * * This is a legacy version that neglected to convert the key to little-endian. * This error doesn't affect the cipher's security, * but it does affect its compatibility with other implementations. */ var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); */ C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); }()); return CryptoJS.RabbitLegacy; })); },{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],65:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm */ var Rabbit = C_algo.Rabbit = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Swap endian for (var i = 0; i < 4; i++) { K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); } // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); */ C.Rabbit = StreamCipher._createHelper(Rabbit); }()); return CryptoJS.Rabbit; })); },{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],66:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; /** * RC4 stream cipher algorithm. */ var RC4 = C_algo.RC4 = StreamCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySigBytes = key.sigBytes; // Init sbox var S = this._S = []; for (var i = 0; i < 256; i++) { S[i] = i; } // Key setup for (var i = 0, j = 0; i < 256; i++) { var keyByteIndex = i % keySigBytes; var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; j = (j + S[i] + keyByte) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; } // Counters this._i = this._j = 0; }, _doProcessBlock: function (M, offset) { M[offset] ^= generateKeystreamWord.call(this); }, keySize: 256/32, ivSize: 0 }); function generateKeystreamWord() { // Shortcuts var S = this._S; var i = this._i; var j = this._j; // Generate keystream word var keystreamWord = 0; for (var n = 0; n < 4; n++) { i = (i + 1) % 256; j = (j + S[i]) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); } // Update counters this._i = i; this._j = j; return keystreamWord; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); */ C.RC4 = StreamCipher._createHelper(RC4); /** * Modified RC4 stream cipher algorithm. */ var RC4Drop = C_algo.RC4Drop = RC4.extend({ /** * Configuration options. * * @property {number} drop The number of keystream words to drop. Default 192 */ cfg: RC4.cfg.extend({ drop: 192 }), _doReset: function () { RC4._doReset.call(this); // Drop for (var i = this.cfg.drop; i > 0; i--) { generateKeystreamWord.call(this); } } }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); */ C.RC4Drop = StreamCipher._createHelper(RC4Drop); }()); return CryptoJS.RC4; })); },{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],67:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var _zl = WordArray.create([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); var _zr = WordArray.create([ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); var _sl = WordArray.create([ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); var _sr = WordArray.create([ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); /** * RIPEMD160 hash algorithm. */ var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ _doReset: function () { this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; // Swap M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcut var H = this._hash.words; var hl = _hl.words; var hr = _hr.words; var zl = _zl.words; var zr = _zr.words; var sl = _sl.words; var sr = _sr.words; // Working variables var al, bl, cl, dl, el; var ar, br, cr, dr, er; ar = al = H[0]; br = bl = H[1]; cr = cl = H[2]; dr = dl = H[3]; er = el = H[4]; // Computation var t; for (var i = 0; i < 80; i += 1) { t = (al + M[offset+zl[i]])|0; if (i<16){ t += f1(bl,cl,dl) + hl[0]; } else if (i<32) { t += f2(bl,cl,dl) + hl[1]; } else if (i<48) { t += f3(bl,cl,dl) + hl[2]; } else if (i<64) { t += f4(bl,cl,dl) + hl[3]; } else {// if (i<80) { t += f5(bl,cl,dl) + hl[4]; } t = t|0; t = rotl(t,sl[i]); t = (t+el)|0; al = el; el = dl; dl = rotl(cl, 10); cl = bl; bl = t; t = (ar + M[offset+zr[i]])|0; if (i<16){ t += f5(br,cr,dr) + hr[0]; } else if (i<32) { t += f4(br,cr,dr) + hr[1]; } else if (i<48) { t += f3(br,cr,dr) + hr[2]; } else if (i<64) { t += f2(br,cr,dr) + hr[3]; } else {// if (i<80) { t += f1(br,cr,dr) + hr[4]; } t = t|0; t = rotl(t,sr[i]) ; t = (t+er)|0; ar = er; er = dr; dr = rotl(cr, 10); cr = br; br = t; } // Intermediate hash value t = (H[1] + cl + dr)|0; H[1] = (H[2] + dl + er)|0; H[2] = (H[3] + el + ar)|0; H[3] = (H[4] + al + br)|0; H[4] = (H[0] + bl + cr)|0; H[0] = t; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 5; i++) { // Shortcut var H_i = H[i]; // Swap H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function f1(x, y, z) { return ((x) ^ (y) ^ (z)); } function f2(x, y, z) { return (((x)&(y)) | ((~x)&(z))); } function f3(x, y, z) { return (((x) | (~(y))) ^ (z)); } function f4(x, y, z) { return (((x) & (z)) | ((y)&(~(z)))); } function f5(x, y, z) { return ((x) ^ ((y) |(~(z)))); } function rotl(x,n) { return (x<<n) | (x>>>(32-n)); } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.RIPEMD160('message'); * var hash = CryptoJS.RIPEMD160(wordArray); */ C.RIPEMD160 = Hasher._createHelper(RIPEMD160); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacRIPEMD160(message, key); */ C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); }(Math)); return CryptoJS.RIPEMD160; })); },{"./core":44}],68:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Reusable object var W = []; /** * SHA-1 hash algorithm. */ var SHA1 = C_algo.SHA1 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; // Computation for (var i = 0; i < 80; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; W[i] = (n << 1) | (n >>> 31); } var t = ((a << 5) | (a >>> 27)) + e + W[i]; if (i < 20) { t += ((b & c) | (~b & d)) + 0x5a827999; } else if (i < 40) { t += (b ^ c ^ d) + 0x6ed9eba1; } else if (i < 60) { t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; } else /* if (i < 80) */ { t += (b ^ c ^ d) - 0x359d3e2a; } e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA1('message'); * var hash = CryptoJS.SHA1(wordArray); */ C.SHA1 = Hasher._createHelper(SHA1); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA1(message, key); */ C.HmacSHA1 = Hasher._createHmacHelper(SHA1); }()); return CryptoJS.SHA1; })); },{"./core":44}],69:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha256"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA256 = C_algo.SHA256; /** * SHA-224 hash algorithm. */ var SHA224 = C_algo.SHA224 = SHA256.extend({ _doReset: function () { this._hash = new WordArray.init([ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]); }, _doFinalize: function () { var hash = SHA256._doFinalize.call(this); hash.sigBytes -= 4; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA224('message'); * var hash = CryptoJS.SHA224(wordArray); */ C.SHA224 = SHA256._createHelper(SHA224); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA224(message, key); */ C.HmacSHA224 = SHA256._createHmacHelper(SHA224); }()); return CryptoJS.SHA224; })); },{"./core":44,"./sha256":70}],70:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Initialization and round constants tables var H = []; var K = []; // Compute constants (function () { function isPrime(n) { var sqrtN = Math.sqrt(n); for (var factor = 2; factor <= sqrtN; factor++) { if (!(n % factor)) { return false; } } return true; } function getFractionalBits(n) { return ((n - (n | 0)) * 0x100000000) | 0; } var n = 2; var nPrime = 0; while (nPrime < 64) { if (isPrime(n)) { if (nPrime < 8) { H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); } K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); nPrime++; } n++; } }()); // Reusable object var W = []; /** * SHA-256 hash algorithm. */ var SHA256 = C_algo.SHA256 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init(H.slice(0)); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; var f = H[5]; var g = H[6]; var h = H[7]; // Computation for (var i = 0; i < 64; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var gamma0x = W[i - 15]; var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ ((gamma0x << 14) | (gamma0x >>> 18)) ^ (gamma0x >>> 3); var gamma1x = W[i - 2]; var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ ((gamma1x << 13) | (gamma1x >>> 19)) ^ (gamma1x >>> 10); W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; } var ch = (e & f) ^ (~e & g); var maj = (a & b) ^ (a & c) ^ (b & c); var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); var t1 = h + sigma1 + ch + K[i] + W[i]; var t2 = sigma0 + maj; h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA256('message'); * var hash = CryptoJS.SHA256(wordArray); */ C.SHA256 = Hasher._createHelper(SHA256); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA256(message, key); */ C.HmacSHA256 = Hasher._createHmacHelper(SHA256); }(Math)); return CryptoJS.SHA256; })); },{"./core":44}],71:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var C_algo = C.algo; // Constants tables var RHO_OFFSETS = []; var PI_INDEXES = []; var ROUND_CONSTANTS = []; // Compute Constants (function () { // Compute rho offset constants var x = 1, y = 0; for (var t = 0; t < 24; t++) { RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; var newX = y % 5; var newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } // Compute pi index constants for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; } } // Compute round constants var LFSR = 0x01; for (var i = 0; i < 24; i++) { var roundConstantMsw = 0; var roundConstantLsw = 0; for (var j = 0; j < 7; j++) { if (LFSR & 0x01) { var bitPosition = (1 << j) - 1; if (bitPosition < 32) { roundConstantLsw ^= 1 << bitPosition; } else /* if (bitPosition >= 32) */ { roundConstantMsw ^= 1 << (bitPosition - 32); } } // Compute next LFSR if (LFSR & 0x80) { // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 LFSR = (LFSR << 1) ^ 0x71; } else { LFSR <<= 1; } } ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); } }()); // Reusable objects for temporary values var T = []; (function () { for (var i = 0; i < 25; i++) { T[i] = X64Word.create(); } }()); /** * SHA-3 hash algorithm. */ var SHA3 = C_algo.SHA3 = Hasher.extend({ /** * Configuration options. * * @property {number} outputLength * The desired number of bits in the output hash. * Only values permitted are: 224, 256, 384, 512. * Default: 512 */ cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function () { var state = this._state = [] for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function (M, offset) { // Shortcuts var state = this._state; var nBlockSizeLanes = this.blockSize / 2; // Absorb for (var i = 0; i < nBlockSizeLanes; i++) { // Shortcuts var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; // Swap endian M2i = ( (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) ); M2i1 = ( (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) ); // Absorb message into state var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } // Rounds for (var round = 0; round < 24; round++) { // Theta for (var x = 0; x < 5; x++) { // Mix column lanes var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } // Temporary values var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { // Shortcuts var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; // Mix surrounding columns var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } // Rho Pi for (var laneIndex = 1; laneIndex < 25; laneIndex++) { // Shortcuts var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; // Rotate lanes if (rhoOffset < 32) { var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); } else /* if (rhoOffset >= 32) */ { var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); } // Transpose lanes var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } // Rho pi at x = y = 0 var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; // Chi for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // Shortcuts var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[((x + 1) % 5) + 5 * y]; var Tx2Lane = T[((x + 2) % 5) + 5 * y]; // Mix rows lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); } } // Iota var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low;; } }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; // Add padding dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Shortcuts var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; // Squeeze var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { // Shortcuts var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; // Swap endian laneMsw = ( (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) ); laneLsw = ( (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) ); // Squeeze state to retrieve hash hashWords.push(laneLsw); hashWords.push(laneMsw); } // Return final computed hash return new WordArray.init(hashWords, outputLengthBytes); }, clone: function () { var clone = Hasher.clone.call(this); var state = clone._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA3('message'); * var hash = CryptoJS.SHA3(wordArray); */ C.SHA3 = Hasher._createHelper(SHA3); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA3(message, key); */ C.HmacSHA3 = Hasher._createHmacHelper(SHA3); }(Math)); return CryptoJS.SHA3; })); },{"./core":44,"./x64-core":75}],72:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./sha512"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; var SHA512 = C_algo.SHA512; /** * SHA-384 hash algorithm. */ var SHA384 = C_algo.SHA384 = SHA512.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) ]); }, _doFinalize: function () { var hash = SHA512._doFinalize.call(this); hash.sigBytes -= 16; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA384('message'); * var hash = CryptoJS.SHA384(wordArray); */ C.SHA384 = SHA512._createHelper(SHA384); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA384(message, key); */ C.HmacSHA384 = SHA512._createHmacHelper(SHA384); }()); return CryptoJS.SHA384; })); },{"./core":44,"./sha512":73,"./x64-core":75}],73:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; function X64Word_create() { return X64Word.create.apply(X64Word, arguments); } // Constants var K = [ X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) ]; // Reusable objects var W = []; (function () { for (var i = 0; i < 80; i++) { W[i] = X64Word_create(); } }()); /** * SHA-512 hash algorithm. */ var SHA512 = C_algo.SHA512 = Hasher.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) ]); }, _doProcessBlock: function (M, offset) { // Shortcuts var H = this._hash.words; var H0 = H[0]; var H1 = H[1]; var H2 = H[2]; var H3 = H[3]; var H4 = H[4]; var H5 = H[5]; var H6 = H[6]; var H7 = H[7]; var H0h = H0.high; var H0l = H0.low; var H1h = H1.high; var H1l = H1.low; var H2h = H2.high; var H2l = H2.low; var H3h = H3.high; var H3l = H3.low; var H4h = H4.high; var H4l = H4.low; var H5h = H5.high; var H5l = H5.low; var H6h = H6.high; var H6l = H6.low; var H7h = H7.high; var H7l = H7.low; // Working variables var ah = H0h; var al = H0l; var bh = H1h; var bl = H1l; var ch = H2h; var cl = H2l; var dh = H3h; var dl = H3l; var eh = H4h; var el = H4l; var fh = H5h; var fl = H5l; var gh = H6h; var gl = H6l; var hh = H7h; var hl = H7l; // Rounds for (var i = 0; i < 80; i++) { // Shortcut var Wi = W[i]; // Extend message if (i < 16) { var Wih = Wi.high = M[offset + i * 2] | 0; var Wil = Wi.low = M[offset + i * 2 + 1] | 0; } else { // Gamma0 var gamma0x = W[i - 15]; var gamma0xh = gamma0x.high; var gamma0xl = gamma0x.low; var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); // Gamma1 var gamma1x = W[i - 2]; var gamma1xh = gamma1x.high; var gamma1xl = gamma1x.low; var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] var Wi7 = W[i - 7]; var Wi7h = Wi7.high; var Wi7l = Wi7.low; var Wi16 = W[i - 16]; var Wi16h = Wi16.high; var Wi16l = Wi16.low; var Wil = gamma0l + Wi7l; var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); var Wil = Wil + gamma1l; var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); var Wil = Wil + Wi16l; var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); Wi.high = Wih; Wi.low = Wil; } var chh = (eh & fh) ^ (~eh & gh); var chl = (el & fl) ^ (~el & gl); var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); var majl = (al & bl) ^ (al & cl) ^ (bl & cl); var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); // t1 = h + sigma1 + ch + K[i] + W[i] var Ki = K[i]; var Kih = Ki.high; var Kil = Ki.low; var t1l = hl + sigma1l; var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); var t1l = t1l + chl; var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); var t1l = t1l + Kil; var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); var t1l = t1l + Wil; var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); // t2 = sigma0 + maj var t2l = sigma0l + majl; var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); // Update working variables hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; el = (dl + t1l) | 0; eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; al = (t1l + t2l) | 0; ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; } // Intermediate hash value H0l = H0.low = (H0l + al); H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); H1l = H1.low = (H1l + bl); H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); H2l = H2.low = (H2l + cl); H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); H3l = H3.low = (H3l + dl); H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); H4l = H4.low = (H4l + el); H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); H5l = H5.low = (H5l + fl); H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); H6l = H6.low = (H6l + gl); H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); H7l = H7.low = (H7l + hl); H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Convert hash to 32-bit word array before returning var hash = this._hash.toX32(); // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; }, blockSize: 1024/32 }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA512('message'); * var hash = CryptoJS.SHA512(wordArray); */ C.SHA512 = Hasher._createHelper(SHA512); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA512(message, key); */ C.HmacSHA512 = Hasher._createHmacHelper(SHA512); }()); return CryptoJS.SHA512; })); },{"./core":44,"./x64-core":75}],74:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Permuted Choice 1 constants var PC1 = [ 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 ]; // Permuted Choice 2 constants var PC2 = [ 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 ]; // Cumulative bit shift constants var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; // SBOXes and round permutation constants var SBOX_P = [ { 0x0: 0x808200, 0x10000000: 0x8000, 0x20000000: 0x808002, 0x30000000: 0x2, 0x40000000: 0x200, 0x50000000: 0x808202, 0x60000000: 0x800202, 0x70000000: 0x800000, 0x80000000: 0x202, 0x90000000: 0x800200, 0xa0000000: 0x8200, 0xb0000000: 0x808000, 0xc0000000: 0x8002, 0xd0000000: 0x800002, 0xe0000000: 0x0, 0xf0000000: 0x8202, 0x8000000: 0x0, 0x18000000: 0x808202, 0x28000000: 0x8202, 0x38000000: 0x8000, 0x48000000: 0x808200, 0x58000000: 0x200, 0x68000000: 0x808002, 0x78000000: 0x2, 0x88000000: 0x800200, 0x98000000: 0x8200, 0xa8000000: 0x808000, 0xb8000000: 0x800202, 0xc8000000: 0x800002, 0xd8000000: 0x8002, 0xe8000000: 0x202, 0xf8000000: 0x800000, 0x1: 0x8000, 0x10000001: 0x2, 0x20000001: 0x808200, 0x30000001: 0x800000, 0x40000001: 0x808002, 0x50000001: 0x8200, 0x60000001: 0x200, 0x70000001: 0x800202, 0x80000001: 0x808202, 0x90000001: 0x808000, 0xa0000001: 0x800002, 0xb0000001: 0x8202, 0xc0000001: 0x202, 0xd0000001: 0x800200, 0xe0000001: 0x8002, 0xf0000001: 0x0, 0x8000001: 0x808202, 0x18000001: 0x808000, 0x28000001: 0x800000, 0x38000001: 0x200, 0x48000001: 0x8000, 0x58000001: 0x800002, 0x68000001: 0x2, 0x78000001: 0x8202, 0x88000001: 0x8002, 0x98000001: 0x800202, 0xa8000001: 0x202, 0xb8000001: 0x808200, 0xc8000001: 0x800200, 0xd8000001: 0x0, 0xe8000001: 0x8200, 0xf8000001: 0x808002 }, { 0x0: 0x40084010, 0x1000000: 0x4000, 0x2000000: 0x80000, 0x3000000: 0x40080010, 0x4000000: 0x40000010, 0x5000000: 0x40084000, 0x6000000: 0x40004000, 0x7000000: 0x10, 0x8000000: 0x84000, 0x9000000: 0x40004010, 0xa000000: 0x40000000, 0xb000000: 0x84010, 0xc000000: 0x80010, 0xd000000: 0x0, 0xe000000: 0x4010, 0xf000000: 0x40080000, 0x800000: 0x40004000, 0x1800000: 0x84010, 0x2800000: 0x10, 0x3800000: 0x40004010, 0x4800000: 0x40084010, 0x5800000: 0x40000000, 0x6800000: 0x80000, 0x7800000: 0x40080010, 0x8800000: 0x80010, 0x9800000: 0x0, 0xa800000: 0x4000, 0xb800000: 0x40080000, 0xc800000: 0x40000010, 0xd800000: 0x84000, 0xe800000: 0x40084000, 0xf800000: 0x4010, 0x10000000: 0x0, 0x11000000: 0x40080010, 0x12000000: 0x40004010, 0x13000000: 0x40084000, 0x14000000: 0x40080000, 0x15000000: 0x10, 0x16000000: 0x84010, 0x17000000: 0x4000, 0x18000000: 0x4010, 0x19000000: 0x80000, 0x1a000000: 0x80010, 0x1b000000: 0x40000010, 0x1c000000: 0x84000, 0x1d000000: 0x40004000, 0x1e000000: 0x40000000, 0x1f000000: 0x40084010, 0x10800000: 0x84010, 0x11800000: 0x80000, 0x12800000: 0x40080000, 0x13800000: 0x4000, 0x14800000: 0x40004000, 0x15800000: 0x40084010, 0x16800000: 0x10, 0x17800000: 0x40000000, 0x18800000: 0x40084000, 0x19800000: 0x40000010, 0x1a800000: 0x40004010, 0x1b800000: 0x80010, 0x1c800000: 0x0, 0x1d800000: 0x4010, 0x1e800000: 0x40080010, 0x1f800000: 0x84000 }, { 0x0: 0x104, 0x100000: 0x0, 0x200000: 0x4000100, 0x300000: 0x10104, 0x400000: 0x10004, 0x500000: 0x4000004, 0x600000: 0x4010104, 0x700000: 0x4010000, 0x800000: 0x4000000, 0x900000: 0x4010100, 0xa00000: 0x10100, 0xb00000: 0x4010004, 0xc00000: 0x4000104, 0xd00000: 0x10000, 0xe00000: 0x4, 0xf00000: 0x100, 0x80000: 0x4010100, 0x180000: 0x4010004, 0x280000: 0x0, 0x380000: 0x4000100, 0x480000: 0x4000004, 0x580000: 0x10000, 0x680000: 0x10004, 0x780000: 0x104, 0x880000: 0x4, 0x980000: 0x100, 0xa80000: 0x4010000, 0xb80000: 0x10104, 0xc80000: 0x10100, 0xd80000: 0x4000104, 0xe80000: 0x4010104, 0xf80000: 0x4000000, 0x1000000: 0x4010100, 0x1100000: 0x10004, 0x1200000: 0x10000, 0x1300000: 0x4000100, 0x1400000: 0x100, 0x1500000: 0x4010104, 0x1600000: 0x4000004, 0x1700000: 0x0, 0x1800000: 0x4000104, 0x1900000: 0x4000000, 0x1a00000: 0x4, 0x1b00000: 0x10100, 0x1c00000: 0x4010000, 0x1d00000: 0x104, 0x1e00000: 0x10104, 0x1f00000: 0x4010004, 0x1080000: 0x4000000, 0x1180000: 0x104, 0x1280000: 0x4010100, 0x1380000: 0x0, 0x1480000: 0x10004, 0x1580000: 0x4000100, 0x1680000: 0x100, 0x1780000: 0x4010004, 0x1880000: 0x10000, 0x1980000: 0x4010104, 0x1a80000: 0x10104, 0x1b80000: 0x4000004, 0x1c80000: 0x4000104, 0x1d80000: 0x4010000, 0x1e80000: 0x4, 0x1f80000: 0x10100 }, { 0x0: 0x80401000, 0x10000: 0x80001040, 0x20000: 0x401040, 0x30000: 0x80400000, 0x40000: 0x0, 0x50000: 0x401000, 0x60000: 0x80000040, 0x70000: 0x400040, 0x80000: 0x80000000, 0x90000: 0x400000, 0xa0000: 0x40, 0xb0000: 0x80001000, 0xc0000: 0x80400040, 0xd0000: 0x1040, 0xe0000: 0x1000, 0xf0000: 0x80401040, 0x8000: 0x80001040, 0x18000: 0x40, 0x28000: 0x80400040, 0x38000: 0x80001000, 0x48000: 0x401000, 0x58000: 0x80401040, 0x68000: 0x0, 0x78000: 0x80400000, 0x88000: 0x1000, 0x98000: 0x80401000, 0xa8000: 0x400000, 0xb8000: 0x1040, 0xc8000: 0x80000000, 0xd8000: 0x400040, 0xe8000: 0x401040, 0xf8000: 0x80000040, 0x100000: 0x400040, 0x110000: 0x401000, 0x120000: 0x80000040, 0x130000: 0x0, 0x140000: 0x1040, 0x150000: 0x80400040, 0x160000: 0x80401000, 0x170000: 0x80001040, 0x180000: 0x80401040, 0x190000: 0x80000000, 0x1a0000: 0x80400000, 0x1b0000: 0x401040, 0x1c0000: 0x80001000, 0x1d0000: 0x400000, 0x1e0000: 0x40, 0x1f0000: 0x1000, 0x108000: 0x80400000, 0x118000: 0x80401040, 0x128000: 0x0, 0x138000: 0x401000, 0x148000: 0x400040, 0x158000: 0x80000000, 0x168000: 0x80001040, 0x178000: 0x40, 0x188000: 0x80000040, 0x198000: 0x1000, 0x1a8000: 0x80001000, 0x1b8000: 0x80400040, 0x1c8000: 0x1040, 0x1d8000: 0x80401000, 0x1e8000: 0x400000, 0x1f8000: 0x401040 }, { 0x0: 0x80, 0x1000: 0x1040000, 0x2000: 0x40000, 0x3000: 0x20000000, 0x4000: 0x20040080, 0x5000: 0x1000080, 0x6000: 0x21000080, 0x7000: 0x40080, 0x8000: 0x1000000, 0x9000: 0x20040000, 0xa000: 0x20000080, 0xb000: 0x21040080, 0xc000: 0x21040000, 0xd000: 0x0, 0xe000: 0x1040080, 0xf000: 0x21000000, 0x800: 0x1040080, 0x1800: 0x21000080, 0x2800: 0x80, 0x3800: 0x1040000, 0x4800: 0x40000, 0x5800: 0x20040080, 0x6800: 0x21040000, 0x7800: 0x20000000, 0x8800: 0x20040000, 0x9800: 0x0, 0xa800: 0x21040080, 0xb800: 0x1000080, 0xc800: 0x20000080, 0xd800: 0x21000000, 0xe800: 0x1000000, 0xf800: 0x40080, 0x10000: 0x40000, 0x11000: 0x80, 0x12000: 0x20000000, 0x13000: 0x21000080, 0x14000: 0x1000080, 0x15000: 0x21040000, 0x16000: 0x20040080, 0x17000: 0x1000000, 0x18000: 0x21040080, 0x19000: 0x21000000, 0x1a000: 0x1040000, 0x1b000: 0x20040000, 0x1c000: 0x40080, 0x1d000: 0x20000080, 0x1e000: 0x0, 0x1f000: 0x1040080, 0x10800: 0x21000080, 0x11800: 0x1000000, 0x12800: 0x1040000, 0x13800: 0x20040080, 0x14800: 0x20000000, 0x15800: 0x1040080, 0x16800: 0x80, 0x17800: 0x21040000, 0x18800: 0x40080, 0x19800: 0x21040080, 0x1a800: 0x0, 0x1b800: 0x21000000, 0x1c800: 0x1000080, 0x1d800: 0x40000, 0x1e800: 0x20040000, 0x1f800: 0x20000080 }, { 0x0: 0x10000008, 0x100: 0x2000, 0x200: 0x10200000, 0x300: 0x10202008, 0x400: 0x10002000, 0x500: 0x200000, 0x600: 0x200008, 0x700: 0x10000000, 0x800: 0x0, 0x900: 0x10002008, 0xa00: 0x202000, 0xb00: 0x8, 0xc00: 0x10200008, 0xd00: 0x202008, 0xe00: 0x2008, 0xf00: 0x10202000, 0x80: 0x10200000, 0x180: 0x10202008, 0x280: 0x8, 0x380: 0x200000, 0x480: 0x202008, 0x580: 0x10000008, 0x680: 0x10002000, 0x780: 0x2008, 0x880: 0x200008, 0x980: 0x2000, 0xa80: 0x10002008, 0xb80: 0x10200008, 0xc80: 0x0, 0xd80: 0x10202000, 0xe80: 0x202000, 0xf80: 0x10000000, 0x1000: 0x10002000, 0x1100: 0x10200008, 0x1200: 0x10202008, 0x1300: 0x2008, 0x1400: 0x200000, 0x1500: 0x10000000, 0x1600: 0x10000008, 0x1700: 0x202000, 0x1800: 0x202008, 0x1900: 0x0, 0x1a00: 0x8, 0x1b00: 0x10200000, 0x1c00: 0x2000, 0x1d00: 0x10002008, 0x1e00: 0x10202000, 0x1f00: 0x200008, 0x1080: 0x8, 0x1180: 0x202000, 0x1280: 0x200000, 0x1380: 0x10000008, 0x1480: 0x10002000, 0x1580: 0x2008, 0x1680: 0x10202008, 0x1780: 0x10200000, 0x1880: 0x10202000, 0x1980: 0x10200008, 0x1a80: 0x2000, 0x1b80: 0x202008, 0x1c80: 0x200008, 0x1d80: 0x0, 0x1e80: 0x10000000, 0x1f80: 0x10002008 }, { 0x0: 0x100000, 0x10: 0x2000401, 0x20: 0x400, 0x30: 0x100401, 0x40: 0x2100401, 0x50: 0x0, 0x60: 0x1, 0x70: 0x2100001, 0x80: 0x2000400, 0x90: 0x100001, 0xa0: 0x2000001, 0xb0: 0x2100400, 0xc0: 0x2100000, 0xd0: 0x401, 0xe0: 0x100400, 0xf0: 0x2000000, 0x8: 0x2100001, 0x18: 0x0, 0x28: 0x2000401, 0x38: 0x2100400, 0x48: 0x100000, 0x58: 0x2000001, 0x68: 0x2000000, 0x78: 0x401, 0x88: 0x100401, 0x98: 0x2000400, 0xa8: 0x2100000, 0xb8: 0x100001, 0xc8: 0x400, 0xd8: 0x2100401, 0xe8: 0x1, 0xf8: 0x100400, 0x100: 0x2000000, 0x110: 0x100000, 0x120: 0x2000401, 0x130: 0x2100001, 0x140: 0x100001, 0x150: 0x2000400, 0x160: 0x2100400, 0x170: 0x100401, 0x180: 0x401, 0x190: 0x2100401, 0x1a0: 0x100400, 0x1b0: 0x1, 0x1c0: 0x0, 0x1d0: 0x2100000, 0x1e0: 0x2000001, 0x1f0: 0x400, 0x108: 0x100400, 0x118: 0x2000401, 0x128: 0x2100001, 0x138: 0x1, 0x148: 0x2000000, 0x158: 0x100000, 0x168: 0x401, 0x178: 0x2100400, 0x188: 0x2000001, 0x198: 0x2100000, 0x1a8: 0x0, 0x1b8: 0x2100401, 0x1c8: 0x100401, 0x1d8: 0x400, 0x1e8: 0x2000400, 0x1f8: 0x100001 }, { 0x0: 0x8000820, 0x1: 0x20000, 0x2: 0x8000000, 0x3: 0x20, 0x4: 0x20020, 0x5: 0x8020820, 0x6: 0x8020800, 0x7: 0x800, 0x8: 0x8020000, 0x9: 0x8000800, 0xa: 0x20800, 0xb: 0x8020020, 0xc: 0x820, 0xd: 0x0, 0xe: 0x8000020, 0xf: 0x20820, 0x80000000: 0x800, 0x80000001: 0x8020820, 0x80000002: 0x8000820, 0x80000003: 0x8000000, 0x80000004: 0x8020000, 0x80000005: 0x20800, 0x80000006: 0x20820, 0x80000007: 0x20, 0x80000008: 0x8000020, 0x80000009: 0x820, 0x8000000a: 0x20020, 0x8000000b: 0x8020800, 0x8000000c: 0x0, 0x8000000d: 0x8020020, 0x8000000e: 0x8000800, 0x8000000f: 0x20000, 0x10: 0x20820, 0x11: 0x8020800, 0x12: 0x20, 0x13: 0x800, 0x14: 0x8000800, 0x15: 0x8000020, 0x16: 0x8020020, 0x17: 0x20000, 0x18: 0x0, 0x19: 0x20020, 0x1a: 0x8020000, 0x1b: 0x8000820, 0x1c: 0x8020820, 0x1d: 0x20800, 0x1e: 0x820, 0x1f: 0x8000000, 0x80000010: 0x20000, 0x80000011: 0x800, 0x80000012: 0x8020020, 0x80000013: 0x20820, 0x80000014: 0x20, 0x80000015: 0x8020000, 0x80000016: 0x8000000, 0x80000017: 0x8000820, 0x80000018: 0x8020820, 0x80000019: 0x8000020, 0x8000001a: 0x8000800, 0x8000001b: 0x0, 0x8000001c: 0x20800, 0x8000001d: 0x820, 0x8000001e: 0x20020, 0x8000001f: 0x8020800 } ]; // Masks that select the SBOX input var SBOX_MASK = [ 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f ]; /** * DES block cipher algorithm. */ var DES = C_algo.DES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Select 56 bits according to PC1 var keyBits = []; for (var i = 0; i < 56; i++) { var keyBitPos = PC1[i] - 1; keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; } // Assemble 16 subkeys var subKeys = this._subKeys = []; for (var nSubKey = 0; nSubKey < 16; nSubKey++) { // Create subkey var subKey = subKeys[nSubKey] = []; // Shortcut var bitShift = BIT_SHIFTS[nSubKey]; // Select 48 bits according to PC2 for (var i = 0; i < 24; i++) { // Select from the left 28 key bits subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); // Select from the right 28 key bits subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); } // Since each subkey is applied to an expanded 32-bit input, // the subkey can be broken into 8 values scaled to 32-bits, // which allows the key to be used without expansion subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); for (var i = 1; i < 7; i++) { subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); } subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); } // Compute inverse subkeys var invSubKeys = this._invSubKeys = []; for (var i = 0; i < 16; i++) { invSubKeys[i] = subKeys[15 - i]; } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._subKeys); }, decryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._invSubKeys); }, _doCryptBlock: function (M, offset, subKeys) { // Get input this._lBlock = M[offset]; this._rBlock = M[offset + 1]; // Initial permutation exchangeLR.call(this, 4, 0x0f0f0f0f); exchangeLR.call(this, 16, 0x0000ffff); exchangeRL.call(this, 2, 0x33333333); exchangeRL.call(this, 8, 0x00ff00ff); exchangeLR.call(this, 1, 0x55555555); // Rounds for (var round = 0; round < 16; round++) { // Shortcuts var subKey = subKeys[round]; var lBlock = this._lBlock; var rBlock = this._rBlock; // Feistel function var f = 0; for (var i = 0; i < 8; i++) { f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; } this._lBlock = rBlock; this._rBlock = lBlock ^ f; } // Undo swap from last round var t = this._lBlock; this._lBlock = this._rBlock; this._rBlock = t; // Final permutation exchangeLR.call(this, 1, 0x55555555); exchangeRL.call(this, 8, 0x00ff00ff); exchangeRL.call(this, 2, 0x33333333); exchangeLR.call(this, 16, 0x0000ffff); exchangeLR.call(this, 4, 0x0f0f0f0f); // Set output M[offset] = this._lBlock; M[offset + 1] = this._rBlock; }, keySize: 64/32, ivSize: 64/32, blockSize: 64/32 }); // Swap bits across the left and right words function exchangeLR(offset, mask) { var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; this._rBlock ^= t; this._lBlock ^= t << offset; } function exchangeRL(offset, mask) { var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; this._lBlock ^= t; this._rBlock ^= t << offset; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); */ C.DES = BlockCipher._createHelper(DES); /** * Triple-DES block cipher algorithm. */ var TripleDES = C_algo.TripleDES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Create DES instances this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); }, encryptBlock: function (M, offset) { this._des1.encryptBlock(M, offset); this._des2.decryptBlock(M, offset); this._des3.encryptBlock(M, offset); }, decryptBlock: function (M, offset) { this._des3.decryptBlock(M, offset); this._des2.encryptBlock(M, offset); this._des1.decryptBlock(M, offset); }, keySize: 192/32, ivSize: 64/32, blockSize: 64/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); */ C.TripleDES = BlockCipher._createHelper(TripleDES); }()); return CryptoJS.TripleDES; })); },{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],75:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var X32WordArray = C_lib.WordArray; /** * x64 namespace. */ var C_x64 = C.x64 = {}; /** * A 64-bit word. */ var X64Word = C_x64.Word = Base.extend({ /** * Initializes a newly created 64-bit word. * * @param {number} high The high 32 bits. * @param {number} low The low 32 bits. * * @example * * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); */ init: function (high, low) { this.high = high; this.low = low; } /** * Bitwise NOTs this word. * * @return {X64Word} A new x64-Word object after negating. * * @example * * var negated = x64Word.not(); */ // not: function () { // var high = ~this.high; // var low = ~this.low; // return X64Word.create(high, low); // }, /** * Bitwise ANDs this word with the passed word. * * @param {X64Word} word The x64-Word to AND with this word. * * @return {X64Word} A new x64-Word object after ANDing. * * @example * * var anded = x64Word.and(anotherX64Word); */ // and: function (word) { // var high = this.high & word.high; // var low = this.low & word.low; // return X64Word.create(high, low); // }, /** * Bitwise ORs this word with the passed word. * * @param {X64Word} word The x64-Word to OR with this word. * * @return {X64Word} A new x64-Word object after ORing. * * @example * * var ored = x64Word.or(anotherX64Word); */ // or: function (word) { // var high = this.high | word.high; // var low = this.low | word.low; // return X64Word.create(high, low); // }, /** * Bitwise XORs this word with the passed word. * * @param {X64Word} word The x64-Word to XOR with this word. * * @return {X64Word} A new x64-Word object after XORing. * * @example * * var xored = x64Word.xor(anotherX64Word); */ // xor: function (word) { // var high = this.high ^ word.high; // var low = this.low ^ word.low; // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the left. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftL(25); */ // shiftL: function (n) { // if (n < 32) { // var high = (this.high << n) | (this.low >>> (32 - n)); // var low = this.low << n; // } else { // var high = this.low << (n - 32); // var low = 0; // } // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the right. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftR(7); */ // shiftR: function (n) { // if (n < 32) { // var low = (this.low >>> n) | (this.high << (32 - n)); // var high = this.high >>> n; // } else { // var low = this.high >>> (n - 32); // var high = 0; // } // return X64Word.create(high, low); // }, /** * Rotates this word n bits to the left. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotL(25); */ // rotL: function (n) { // return this.shiftL(n).or(this.shiftR(64 - n)); // }, /** * Rotates this word n bits to the right. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotR(7); */ // rotR: function (n) { // return this.shiftR(n).or(this.shiftL(64 - n)); // }, /** * Adds this word with the passed word. * * @param {X64Word} word The x64-Word to add with this word. * * @return {X64Word} A new x64-Word object after adding. * * @example * * var added = x64Word.add(anotherX64Word); */ // add: function (word) { // var low = (this.low + word.low) | 0; // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; // var high = (this.high + word.high + carry) | 0; // return X64Word.create(high, low); // } }); /** * An array of 64-bit words. * * @property {Array} words The array of CryptoJS.x64.Word objects. * @property {number} sigBytes The number of significant bytes in this word array. */ var X64WordArray = C_x64.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.x64.WordArray.create(); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ]); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ], 10); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } }, /** * Converts this 64-bit word array to a 32-bit word array. * * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. * * @example * * var x32WordArray = x64WordArray.toX32(); */ toX32: function () { // Shortcuts var x64Words = this.words; var x64WordsLength = x64Words.length; // Convert var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); }, /** * Creates a copy of this word array. * * @return {X64WordArray} The clone. * * @example * * var clone = x64WordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); // Clone "words" array var words = clone.words = this.words.slice(0); // Clone each X64Word object var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone; } }); }()); return CryptoJS; })); },{"./core":44}],76:[function(_dereq_,module,exports){ (function (process,global){ /*! localForage -- Offline Storage, Improved Version 1.4.0 https://mozilla.github.io/localForage (c) 2013-2015 Mozilla, Apache License 2.0 */ (function() { var define, requireModule, _dereq_, requirejs; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requirejs = _dereq_ = requireModule = function(name) { requirejs._eak_seen = registry; if (seen[name]) { return seen[name]; } seen[name] = {}; if (!registry[name]) { throw new Error("Could not find module " + name); } var mod = registry[name], deps = mod.deps, callback = mod.callback, reified = [], exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(resolve(deps[i]))); } } var value = callback.apply(this, reified); return seen[name] = exports || value; function resolve(child) { if (child.charAt(0) !== '.') { return child; } var parts = child.split("/"); var parentBase = name.split("/").slice(0, -1); for (var i=0, l=parts.length; i<l; i++) { var part = parts[i]; if (part === '..') { parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join("/"); } }; })(); define("promise/all", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; var isFunction = __dependency1__.isFunction; /** Returns a promise that is fulfilled when all the given promises have been fulfilled, or rejected if any of them become rejected. The return promise is fulfilled with an array that gives all the values in the order they were passed in the `promises` array argument. Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.resolve(2); var promise3 = RSVP.resolve(3); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `RSVP.all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.reject(new Error("2")); var promise3 = RSVP.reject(new Error("3")); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @for RSVP @param {Array} promises @param {String} label @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. */ function all(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to all.'); } return new Promise(function(resolve, reject) { var results = [], remaining = promises.length, promise; if (remaining === 0) { resolve([]); } function resolver(index) { return function(value) { resolveAll(index, value); }; } function resolveAll(index, value) { results[index] = value; if (--remaining === 0) { resolve(results); } } for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && isFunction(promise.then)) { promise.then(resolver(i), reject); } else { resolveAll(i, promise); } } }); } __exports__.all = all; }); define("promise/asap", ["exports"], function(__exports__) { "use strict"; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this); // node function useNextTick() { return function() { process.nextTick(flush); }; } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } function useSetTimeout() { return function() { local.setTimeout(flush, 1); }; } var queue = []; function flush() { for (var i = 0; i < queue.length; i++) { var tuple = queue[i]; var callback = tuple[0], arg = tuple[1]; callback(arg); } queue = []; } var scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else { scheduleFlush = useSetTimeout(); } function asap(callback, arg) { var length = queue.push([callback, arg]); if (length === 1) { // If length is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. scheduleFlush(); } } __exports__.asap = asap; }); define("promise/config", ["exports"], function(__exports__) { "use strict"; var config = { instrument: false }; function configure(name, value) { if (arguments.length === 2) { config[name] = value; } else { return config[name]; } } __exports__.config = config; __exports__.configure = configure; }); define("promise/polyfill", ["./promise","./utils","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /*global self*/ var RSVPPromise = __dependency1__.Promise; var isFunction = __dependency2__.isFunction; function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = RSVPPromise; } } __exports__.polyfill = polyfill; }); define("promise/promise", ["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __exports__) { "use strict"; var config = __dependency1__.config; var configure = __dependency1__.configure; var objectOrFunction = __dependency2__.objectOrFunction; var isFunction = __dependency2__.isFunction; var now = __dependency2__.now; var all = __dependency3__.all; var race = __dependency4__.race; var staticResolve = __dependency5__.resolve; var staticReject = __dependency6__.reject; var asap = __dependency7__.asap; var counter = 0; config.async = asap; // default async is asap; function Promise(resolver) { if (!isFunction(resolver)) { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } if (!(this instanceof Promise)) { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } this._subscribers = []; invokeResolver(resolver, this); } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch(e) { rejectPromise(e); } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value, error, succeeded, failed; if (hasCallback) { try { value = callback(detail); succeeded = true; } catch(e) { failed = true; error = e; } } else { value = detail; succeeded = true; } if (handleThenable(promise, value)) { return; } else if (hasCallback && succeeded) { resolve(promise, value); } else if (failed) { reject(promise, error); } else if (settled === FULFILLED) { resolve(promise, value); } else if (settled === REJECTED) { reject(promise, value); } } var PENDING = void 0; var SEALED = 0; var FULFILLED = 1; var REJECTED = 2; function subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; subscribers[length] = child; subscribers[length + FULFILLED] = onFulfillment; subscribers[length + REJECTED] = onRejection; } function publish(promise, settled) { var child, callback, subscribers = promise._subscribers, detail = promise._detail; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; invokeCallback(settled, child, callback, detail); } promise._subscribers = null; } Promise.prototype = { constructor: Promise, _state: undefined, _detail: undefined, _subscribers: undefined, then: function(onFulfillment, onRejection) { var promise = this; var thenPromise = new this.constructor(function() {}); if (this._state) { var callbacks = arguments; config.async(function invokePromiseCallback() { invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail); }); } else { subscribe(this, thenPromise, onFulfillment, onRejection); } return thenPromise; }, 'catch': function(onRejection) { return this.then(null, onRejection); } }; Promise.all = all; Promise.race = race; Promise.resolve = staticResolve; Promise.reject = staticReject; function handleThenable(promise, value) { var then = null, resolved; try { if (promise === value) { throw new TypeError("A promises callback cannot return that same promise."); } if (objectOrFunction(value)) { then = value.then; if (isFunction(then)) { then.call(value, function(val) { if (resolved) { return true; } resolved = true; if (value !== val) { resolve(promise, val); } else { fulfill(promise, val); } }, function(val) { if (resolved) { return true; } resolved = true; reject(promise, val); }); return true; } } } catch (error) { if (resolved) { return true; } reject(promise, error); return true; } return false; } function resolve(promise, value) { if (promise === value) { fulfill(promise, value); } else if (!handleThenable(promise, value)) { fulfill(promise, value); } } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = value; config.async(publishFulfillment, promise); } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = reason; config.async(publishRejection, promise); } function publishFulfillment(promise) { publish(promise, promise._state = FULFILLED); } function publishRejection(promise) { publish(promise, promise._state = REJECTED); } __exports__.Promise = Promise; }); define("promise/race", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; /** `RSVP.race` allows you to watch a series of promises and act as soon as the first promise given to the `promises` argument fulfills or rejects. Example: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 2"); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // result === "promise 2" because it was resolved before promise1 // was resolved. }); ``` `RSVP.race` is deterministic in that only the state of the first completed promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first completed promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error("promise 2")); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // Code here never runs because there are rejected promises! }, function(reason){ // reason.message === "promise2" because promise 2 became rejected before // promise 1 became fulfilled }); ``` @method race @for RSVP @param {Array} promises array of promises to observe @param {String} label optional string for describing the promise returned. Useful for tooling. @return {Promise} a promise that becomes fulfilled with the value the first completed promises is resolved with if the first completed promise was fulfilled, or rejected with the reason that the first completed promise was rejected with. */ function race(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to race.'); } return new Promise(function(resolve, reject) { var results = [], promise; for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolve, reject); } else { resolve(promise); } } }); } __exports__.race = race; }); define("promise/reject", ["exports"], function(__exports__) { "use strict"; /** `RSVP.reject` returns a promise that will become rejected with the passed `reason`. `RSVP.reject` is essentially shorthand for the following: ```javascript var promise = new RSVP.Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript var promise = RSVP.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @for RSVP @param {Any} reason value that the returned promise will be rejected with. @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise that will become rejected with the given `reason`. */ function reject(reason) { /*jshint validthis:true */ var Promise = this; return new Promise(function (resolve, reject) { reject(reason); }); } __exports__.reject = reject; }); define("promise/resolve", ["exports"], function(__exports__) { "use strict"; function resolve(value) { /*jshint validthis:true */ if (value && typeof value === 'object' && value.constructor === this) { return value; } var Promise = this; return new Promise(function(resolve) { resolve(value); }); } __exports__.resolve = resolve; }); define("promise/utils", ["exports"], function(__exports__) { "use strict"; function objectOrFunction(x) { return isFunction(x) || (typeof x === "object" && x !== null); } function isFunction(x) { return typeof x === "function"; } function isArray(x) { return Object.prototype.toString.call(x) === "[object Array]"; } // Date.now is not available in browsers < IE9 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility var now = Date.now || function() { return new Date().getTime(); }; __exports__.objectOrFunction = objectOrFunction; __exports__.isFunction = isFunction; __exports__.isArray = isArray; __exports__.now = now; }); requireModule('promise/polyfill').polyfill(); }());(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["localforage"] = factory(); else root["localforage"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var localForage = (function (globalObject) { 'use strict'; // Custom drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var CustomDrivers = {}; var DriverType = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage' }; var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE]; var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem']; var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; var driverSupport = (function (self) { var result = {}; // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 result[DriverType.INDEXEDDB] = !!(function () { try { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { return false; } return indexedDB && typeof indexedDB.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof self.IDBKeyRange !== 'undefined'; } catch (e) { return false; } })(); result[DriverType.WEBSQL] = !!(function () { try { return self.openDatabase; } catch (e) { return false; } })(); result[DriverType.LOCALSTORAGE] = !!(function () { try { return self.localStorage && 'setItem' in self.localStorage && self.localStorage.setItem; } catch (e) { return false; } })(); return result; })(globalObject); var isArray = Array.isArray || function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function () { var _args = arguments; return localForageInstance.ready().then(function () { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var LocalForage = (function () { function LocalForage(options) { _classCallCheck(this, LocalForage); this.INDEXEDDB = DriverType.INDEXEDDB; this.LOCALSTORAGE = DriverType.LOCALSTORAGE; this.WEBSQL = DriverType.WEBSQL; this._defaultConfig = extend({}, DefaultConfig); this._config = extend({}, this._defaultConfig, options); this._driverSet = null; this._initDriver = null; this._ready = false; this._dbInfo = null; this._wrapLibraryMethodsWithReady(); this.setDriver(this._config.driver); } // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function config(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if (typeof options === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { this.setDriver(this._config.driver); } return true; } else if (typeof options === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { var promise = new Promise(function (resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); var namingError = new Error('Custom driver name already in use: ' + driverObject._driver); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } if (isLibraryDriver(driverObject._driver)) { reject(namingError); return; } var customDriverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0; i < customDriverMethods.length; i++) { var customDriverMethod = customDriverMethods[i]; if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { reject(complianceError); return; } } var supportPromise = Promise.resolve(true); if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { supportPromise = driverObject._support(); } else { supportPromise = Promise.resolve(!!driverObject._support); } } supportPromise.then(function (supportResult) { driverSupport[driverName] = supportResult; CustomDrivers[driverName] = driverObject; resolve(); }, reject); } catch (e) { reject(e); } }); promise.then(callback, errorCallback); return promise; }; LocalForage.prototype.driver = function driver() { return this._driver || null; }; LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { var self = this; var getDriverPromise = (function () { if (isLibraryDriver(driverName)) { switch (driverName) { case self.INDEXEDDB: return new Promise(function (resolve, reject) { resolve(__webpack_require__(1)); }); case self.LOCALSTORAGE: return new Promise(function (resolve, reject) { resolve(__webpack_require__(2)); }); case self.WEBSQL: return new Promise(function (resolve, reject) { resolve(__webpack_require__(4)); }); } } else if (CustomDrivers[driverName]) { return Promise.resolve(CustomDrivers[driverName]); } return Promise.reject(new Error('Driver not found.')); })(); getDriverPromise.then(callback, errorCallback); return getDriverPromise; }; LocalForage.prototype.getSerializer = function getSerializer(callback) { var serializerPromise = new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }); if (callback && typeof callback === 'function') { serializerPromise.then(function (result) { callback(result); }); } return serializerPromise; }; LocalForage.prototype.ready = function ready(callback) { var self = this; var promise = self._driverSet.then(function () { if (self._ready === null) { self._ready = self._initDriver(); } return self._ready; }); promise.then(callback, callback); return promise; }; LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { var self = this; if (!isArray(drivers)) { drivers = [drivers]; } var supportedDrivers = this._getSupportedDrivers(drivers); function setDriverToConfig() { self._config.driver = self.driver(); } function initDriver(supportedDrivers) { return function () { var currentDriverIndex = 0; function driverPromiseLoop() { while (currentDriverIndex < supportedDrivers.length) { var driverName = supportedDrivers[currentDriverIndex]; currentDriverIndex++; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._extend(driver); setDriverToConfig(); self._ready = self._initStorage(self._config); return self._ready; })['catch'](driverPromiseLoop); } setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise.reject(error); return self._driverSet; } return driverPromiseLoop(); }; } // There might be a driver initialization in progress // so wait for it to finish in order to avoid a possible // race condition to set _dbInfo var oldDriverSetDone = this._driverSet !== null ? this._driverSet['catch'](function () { return Promise.resolve(); }) : Promise.resolve(); this._driverSet = oldDriverSetDone.then(function () { var driverName = supportedDrivers[0]; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._driver = driver._driver; setDriverToConfig(); self._wrapLibraryMethodsWithReady(); self._initDriver = initDriver(supportedDrivers); }); })['catch'](function () { setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise.reject(error); return self._driverSet; }); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function supports(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { var supportedDrivers = []; for (var i = 0, len = drivers.length; i < len; i++) { var driverName = drivers[i]; if (this.supports(driverName)) { supportedDrivers.push(driverName); } } return supportedDrivers; }; LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0; i < LibraryMethods.length; i++) { callWhenReady(this, LibraryMethods[i]); } }; LocalForage.prototype.createInstance = function createInstance(options) { return new LocalForage(options); }; return LocalForage; })(); return new LocalForage(); })(typeof window !== 'undefined' ? window : self); exports['default'] = localForage; module.exports = exports['default']; /***/ }, /* 1 */ /***/ function(module, exports) { // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). 'use strict'; exports.__esModule = true; var asyncStorage = (function (globalObject) { 'use strict'; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || globalObject.indexedDB || globalObject.webkitIndexedDB || globalObject.mozIndexedDB || globalObject.OIndexedDB || globalObject.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; var supportsBlobs; var dbContexts; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (e) { if (e.name !== 'TypeError') { throw e; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Transform a binary string to an array buffer, because otherwise // weird stuff happens when you try to work with the binary string directly. // It is known. // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) function _binStringToArrayBuffer(bin) { var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; } // Fetch a blob using ajax. This reveals bugs in Chrome < 43. // For details on all this junk: // https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme function _blobAjax(url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.withCredentials = true; xhr.responseType = 'arraybuffer'; xhr.onreadystatechange = function () { if (xhr.readyState !== 4) { return; } if (xhr.status === 200) { return resolve({ response: xhr.response, type: xhr.getResponseHeader('Content-Type') }); } reject({ status: xhr.status, response: xhr.response }); }; xhr.send(); }); } // // Detect blob support. Chrome didn't support it until version 38. // In version 37 they had a broken version where PNGs (and possibly // other binary types) aren't stored correctly, because when you fetch // them, the content type is always null. // // Furthermore, they have some outstanding bugs where blobs occasionally // are read by FileReader as null, or by ajax as 404s. // // Sadly we use the 404 bug to detect the FileReader bug, so if they // get fixed independently and released in different versions of Chrome, // then the bug could come back. So it's worthwhile to watch these issues: // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 // function _checkBlobSupportWithoutCaching(idb) { return new Promise(function (resolve, reject) { var blob = _createBlob([''], { type: 'image/png' }); var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); txn.oncomplete = function () { // have to do it in a separate transaction, else the correct // content type is always returned var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); var getBlobReq = blobTxn.objectStore(DETECT_BLOB_SUPPORT_STORE).get('key'); getBlobReq.onerror = reject; getBlobReq.onsuccess = function (e) { var storedBlob = e.target.result; var url = URL.createObjectURL(storedBlob); _blobAjax(url).then(function (res) { resolve(!!(res && res.type === 'image/png')); }, function () { resolve(false); }).then(function () { URL.revokeObjectURL(url); }); }; }; txn.onerror = txn.onabort = reject; })['catch'](function () { return false; // error, so assume unsupported }); } function _checkBlobSupport(idb) { if (typeof supportsBlobs === 'boolean') { return Promise.resolve(supportsBlobs); } return _checkBlobSupportWithoutCaching(idb).then(function (value) { supportsBlobs = value; return supportsBlobs; }); } // encode a blob for indexeddb engines that don't support blobs function _encodeBlob(blob) { return new Promise(function (resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function (e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); } // decode an encoded blob function _decodeBlob(encodedBlob) { var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); return _createBlob([arrayBuff], { type: encodedBlob.type }); } // is this one of our fancy encoded blobs? function _isEncodedBlob(value) { return value && value.__local_forage_encoded_blob; } // Specialize the default `ready()` function by making it dependent // on the current database operations. Thus, the driver will be actually // ready when it's been initialized (default) *and* there are no pending // operations on the database (initiated by some other instances). function _fullyReady(callback) { var self = this; var promise = self._initReady().then(function () { var dbContext = dbContexts[self._dbInfo.name]; if (dbContext && dbContext.dbReady) { return dbContext.dbReady; } }); promise.then(callback, callback); return promise; } function _deferReadiness(dbInfo) { var dbContext = dbContexts[dbInfo.name]; // Create a deferred object representing the current database operation. var deferredOperation = {}; deferredOperation.promise = new Promise(function (resolve) { deferredOperation.resolve = resolve; }); // Enqueue the deferred operation. dbContext.deferredOperations.push(deferredOperation); // Chain its promise to the database readiness. if (!dbContext.dbReady) { dbContext.dbReady = deferredOperation.promise; } else { dbContext.dbReady = dbContext.dbReady.then(function () { return deferredOperation.promise; }); } } function _advanceReadiness(dbInfo) { var dbContext = dbContexts[dbInfo.name]; // Dequeue a deferred operation. var deferredOperation = dbContext.deferredOperations.pop(); // Resolve its promise (which is part of the database readiness // chain of promises). if (deferredOperation) { deferredOperation.resolve(); } } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } // Initialize a singleton container for all running localForages. if (!dbContexts) { dbContexts = {}; } // Get the current context of the database; var dbContext = dbContexts[dbInfo.name]; // ...or create a new context. if (!dbContext) { dbContext = { // Running localForages sharing a database. forages: [], // Shared database. db: null, // Database readiness (promise). dbReady: null, // Deferred operations on the database. deferredOperations: [] }; // Register the new context in the global container. dbContexts[dbInfo.name] = dbContext; } // Register itself as a running localForage in the current context. dbContext.forages.push(self); // Replace the default `ready()` function with the specialized one. if (!self._initReady) { self._initReady = self.ready; self.ready = _fullyReady; } // Create an array of initialization states of the related localForages. var initPromises = []; function ignoreErrors() { // Don't handle errors here, // just makes sure related localForages aren't pending. return Promise.resolve(); } for (var j = 0; j < dbContext.forages.length; j++) { var forage = dbContext.forages[j]; if (forage !== self) { // Don't wait for itself... initPromises.push(forage._initReady()['catch'](ignoreErrors)); } } // Take a snapshot of the related localForages. var forages = dbContext.forages.slice(0); // Initialize the connection process only when // all the related localForages aren't pending. return Promise.all(initPromises).then(function () { dbInfo.db = dbContext.db; // Get the connection or open a new one without upgrade. return _getOriginalConnection(dbInfo); }).then(function (db) { dbInfo.db = db; if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { // Reopen the database for upgrading. return _getUpgradedConnection(dbInfo); } return db; }).then(function (db) { dbInfo.db = dbContext.db = db; self._dbInfo = dbInfo; // Share the final connection amongst related localForages. for (var k = 0; k < forages.length; k++) { var forage = forages[k]; if (forage !== self) { // Self is already up-to-date. forage._dbInfo.db = dbInfo.db; forage._dbInfo.version = dbInfo.version; } } }); } function _getOriginalConnection(dbInfo) { return _getConnection(dbInfo, false); } function _getUpgradedConnection(dbInfo) { return _getConnection(dbInfo, true); } function _getConnection(dbInfo, upgradeNeeded) { return new Promise(function (resolve, reject) { if (dbInfo.db) { if (upgradeNeeded) { _deferReadiness(dbInfo); dbInfo.db.close(); } else { return resolve(dbInfo.db); } } var dbArgs = [dbInfo.name]; if (upgradeNeeded) { dbArgs.push(dbInfo.version); } var openreq = indexedDB.open.apply(indexedDB, dbArgs); if (upgradeNeeded) { openreq.onupgradeneeded = function (e) { var db = openreq.result; try { db.createObjectStore(dbInfo.storeName); if (e.oldVersion <= 1) { // Added when support for blob shims was added db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); } } catch (ex) { if (ex.name === 'ConstraintError') { globalObject.console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); } else { throw ex; } } }; } openreq.onerror = function () { reject(openreq.error); }; openreq.onsuccess = function () { resolve(openreq.result); _advanceReadiness(dbInfo); }; }); } function _isUpgradeNeeded(dbInfo, defaultVersion) { if (!dbInfo.db) { return true; } var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); var isDowngrade = dbInfo.version < dbInfo.db.version; var isUpgrade = dbInfo.version > dbInfo.db.version; if (isDowngrade) { // If the version is not the default one // then warn for impossible downgrade. if (dbInfo.version !== defaultVersion) { globalObject.console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.'); } // Align the versions to prevent errors. dbInfo.version = dbInfo.db.version; } if (isUpgrade || isNewStore) { // If the store is new then increment the version (if needed). // This will trigger an "upgradeneeded" event which is required // for creating a store. if (isNewStore) { var incVersion = dbInfo.db.version + 1; if (incVersion > dbInfo.version) { dbInfo.version = incVersion; } } return true; } return false; } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function () { var value = req.result; if (value === undefined) { value = null; } if (_isEncodedBlob(value)) { value = _decodeBlob(value); } resolve(value); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Iterate over all items stored in database. function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function () { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); if (result !== void 0) { resolve(result); } else { cursor['continue'](); } } else { resolve(); } }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { var dbInfo; self.ready().then(function () { dbInfo = self._dbInfo; if (value instanceof Blob) { return _checkBlobSupport(dbInfo.db).then(function (blobSupport) { if (blobSupport) { return value; } return _encodeBlob(value); }); } return value; }).then(function (value) { var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } transaction.oncomplete = function () { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; var req = store.put(value, key); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `['delete']()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store['delete'](key); transaction.oncomplete = function () { resolve(); }; transaction.onerror = function () { reject(req.error); }; // The request will be also be aborted if we've exceeded our storage // space. transaction.onabort = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); var req = store.clear(); transaction.oncomplete = function () { resolve(); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.count(); req.onsuccess = function () { resolve(req.result); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { if (n < 0) { resolve(null); return; } self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var advanced = false; var req = store.openCursor(); req.onsuccess = function () { var cursor = req.result; if (!cursor) { // this means there weren't enough keys resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. resolve(cursor.key); } } }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var keys = []; req.onsuccess = function () { var cursor = req.result; if (!cursor) { resolve(keys); return; } keys.push(cursor.key); cursor['continue'](); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; return asyncStorage; })(typeof window !== 'undefined' ? window : self); exports['default'] = asyncStorage; module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { // If IndexedDB isn't available, we'll fall back to localStorage. // Note that this will have considerable performance and storage // side-effects (all data will be serialized on save and only data that // can be converted to a string via `JSON.stringify()` will be saved). 'use strict'; exports.__esModule = true; var localStorageWrapper = (function (globalObject) { 'use strict'; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // If localStorage isn't available, we get outta here! // This should be inside a try catch if (!globalObject.localStorage || !('setItem' in globalObject.localStorage)) { return; } // Initialize localStorage and create a variable to use throughout // the code. localStorage = globalObject.localStorage; } catch (e) { return; } // Config the localStorage backend, using options set in the config. function _initStorage(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = dbInfo.name + '/'; if (dbInfo.storeName !== self._defaultConfig.storeName) { dbInfo.keyPrefix += dbInfo.storeName + '/'; } self._dbInfo = dbInfo; return new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }).then(function (lib) { dbInfo.serializer = lib; return Promise.resolve(); }); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear(callback) { var self = this; var promise = self.ready().then(function () { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = dbInfo.serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate(iterator, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var keyPrefix = dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; // We use a dedicated iterator instead of the `i` variable below // so other keys we fetch in localStorage aren't counted in // the `iterationNumber` argument passed to the `iterate()` // callback. // // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 var iterationNumber = 1; for (var i = 0; i < length; i++) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) !== 0) { continue; } var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = dbInfo.serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); if (value !== void 0) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key(n, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length(callback) { var self = this; var promise = self.keys().then(function (keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise(function (resolve, reject) { var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { try { localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage, // Default API, from Gaia/localStorage. iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; return localStorageWrapper; })(typeof window !== 'undefined' ? window : self); exports['default'] = localStorageWrapper; module.exports = exports['default']; /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; var localforageSerializer = (function (globalObject) { 'use strict'; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var BLOB_TYPE_PREFIX = '~~local_forage_type~'; var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (err) { if (err.name !== 'TypeError') { throw err; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueString === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function () { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return _createBlob([buffer], { type: blobType }); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i += 4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); /*jslint bitwise: true */ bytes[p++] = encoded1 << 2 | encoded2 >> 4; bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if (bytes.length % 3 === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; return localforageSerializer; })(typeof window !== 'undefined' ? window : self); exports['default'] = localforageSerializer; module.exports = exports['default']; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ 'use strict'; exports.__esModule = true; var webSQLStorage = (function (globalObject) { 'use strict'; var openDatabase = globalObject.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; } } var dbInfoPromise = new Promise(function (resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return reject(e); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function (t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () { self._dbInfo = dbInfo; resolve(); }, function (t, error) { reject(error); }); }); }); return new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }).then(function (lib) { dbInfo.serializer = lib; return dbInfoPromise; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = dbInfo.serializer.deserialize(result); } resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = dbInfo.serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void 0) { resolve(result); return; } } resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { dbInfo.db.transaction(function (t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () { resolve(originalValue); }, function (t, error) { reject(error); }); }, function (sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. reject(sqlError); } }); } }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () { resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { var result = results.rows.item(0).c; resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; return webSQLStorage; })(typeof window !== 'undefined' ? window : self); exports['default'] = webSQLStorage; module.exports = exports['default']; /***/ } /******/ ]) }); ; }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":93}],77:[function(_dereq_,module,exports){ // Top level file is just a mixin of submodules & constants 'use strict'; var assign = _dereq_('./lib/utils/common').assign; var deflate = _dereq_('./lib/deflate'); var inflate = _dereq_('./lib/inflate'); var constants = _dereq_('./lib/zlib/constants'); var pako = {}; assign(pako, deflate, inflate, constants); module.exports = pako; },{"./lib/deflate":78,"./lib/inflate":79,"./lib/utils/common":80,"./lib/zlib/constants":83}],78:[function(_dereq_,module,exports){ 'use strict'; var zlib_deflate = _dereq_('./zlib/deflate'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var msg = _dereq_('./zlib/messages'); var ZStream = _dereq_('./zlib/zstream'); var toString = Object.prototype.toString; /* Public constants ==========================================================*/ /* ===========================================================================*/ var Z_NO_FLUSH = 0; var Z_FINISH = 4; var Z_OK = 0; var Z_STREAM_END = 1; var Z_SYNC_FLUSH = 2; var Z_DEFAULT_COMPRESSION = -1; var Z_DEFAULT_STRATEGY = 0; var Z_DEFLATED = 8; /* ===========================================================================*/ /** * class Deflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[deflate]], * [[deflateRaw]] and [[gzip]]. **/ /* internal * Deflate.chunks -> Array * * Chunks of output data, if [[Deflate#onData]] not overriden. **/ /** * Deflate.result -> Uint8Array|Array * * Compressed result, generated by default [[Deflate#onData]] * and [[Deflate#onEnd]] handlers. Filled after you push last chunk * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Deflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Deflate.err -> Number * * Error code after deflate finished. 0 (Z_OK) on success. * You will not need it in real life, because deflate errors * are possible only on wrong options or bad `onData` / `onEnd` * custom handlers. **/ /** * Deflate.msg -> String * * Error message, if [[Deflate.err]] != 0 **/ /** * new Deflate(options) * - options (Object): zlib deflate options. * * Creates new deflator instance with specified params. Throws exception * on bad params. Supported options: * * - `level` * - `windowBits` * - `memLevel` * - `strategy` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw deflate * - `gzip` (Boolean) - create gzip wrapper * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * - `header` (Object) - custom header for gzip * - `text` (Boolean) - true if compressed data believed to be text * - `time` (Number) - modification time, unix timestamp * - `os` (Number) - operation system code * - `extra` (Array) - array of bytes with extra data (max 65536) * - `name` (String) - file name (binary string) * - `comment` (String) - comment (binary string) * - `hcrc` (Boolean) - true if header crc should be added * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var deflate = new pako.Deflate({ level: 3}); * * deflate.push(chunk1, false); * deflate.push(chunk2, true); // true -> last chunk * * if (deflate.err) { throw new Error(deflate.err); } * * console.log(deflate.result); * ``` **/ function Deflate(options) { if (!(this instanceof Deflate)) return new Deflate(options); this.options = utils.assign({ level: Z_DEFAULT_COMPRESSION, method: Z_DEFLATED, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: Z_DEFAULT_STRATEGY, to: '' }, options || {}); var opt = this.options; if (opt.raw && (opt.windowBits > 0)) { opt.windowBits = -opt.windowBits; } else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { opt.windowBits += 16; } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new ZStream(); this.strm.avail_out = 0; var status = zlib_deflate.deflateInit2( this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy ); if (status !== Z_OK) { throw new Error(msg[status]); } if (opt.header) { zlib_deflate.deflateSetHeader(this.strm, opt.header); } } /** * Deflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be * converted to utf8 byte sequence. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with * new compressed chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the compression context. * * On fail call [[Deflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * array format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Deflate.prototype.push = function (data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // If we need to compress text, change encoding to utf8. strm.input = strings.string2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ if (status !== Z_STREAM_END && status !== Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { if (this.options.to === 'string') { this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); // Finalize on the last chunk. if (_mode === Z_FINISH) { status = zlib_deflate.deflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === Z_SYNC_FLUSH) { this.onEnd(Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Deflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Deflate.prototype.onData = function (chunk) { this.chunks.push(chunk); }; /** * Deflate#onEnd(status) -> Void * - status (Number): deflate status. 0 (Z_OK) on success, * other if not. * * Called once after you tell deflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Deflate.prototype.onEnd = function (status) { // On success - join if (status === Z_OK) { if (this.options.to === 'string') { this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * deflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * Compress `data` with deflate algorithm and `options`. * * Supported options are: * * - level * - windowBits * - memLevel * - strategy * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * * ##### Example: * * ```javascript * var pako = require('pako') * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); * * console.log(pako.deflate(data)); * ``` **/ function deflate(input, options) { var deflator = new Deflate(options); deflator.push(input, true); // That will never happens, if you don't cheat with options :) if (deflator.err) { throw deflator.msg; } return deflator.result; } /** * deflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function deflateRaw(input, options) { options = options || {}; options.raw = true; return deflate(input, options); } /** * gzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but create gzip wrapper instead of * deflate one. **/ function gzip(input, options) { options = options || {}; options.gzip = true; return deflate(input, options); } exports.Deflate = Deflate; exports.deflate = deflate; exports.deflateRaw = deflateRaw; exports.gzip = gzip; },{"./utils/common":80,"./utils/strings":81,"./zlib/deflate":85,"./zlib/messages":90,"./zlib/zstream":92}],79:[function(_dereq_,module,exports){ 'use strict'; var zlib_inflate = _dereq_('./zlib/inflate'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var c = _dereq_('./zlib/constants'); var msg = _dereq_('./zlib/messages'); var ZStream = _dereq_('./zlib/zstream'); var GZheader = _dereq_('./zlib/gzheader'); var toString = Object.prototype.toString; /** * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[inflate]] * and [[inflateRaw]]. **/ /* internal * inflate.chunks -> Array * * Chunks of output data, if [[Inflate#onData]] not overriden. **/ /** * Inflate.result -> Uint8Array|Array|String * * Uncompressed result, generated by default [[Inflate#onData]] * and [[Inflate#onEnd]] handlers. Filled after you push last chunk * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Inflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Inflate.err -> Number * * Error code after inflate finished. 0 (Z_OK) on success. * Should be checked if broken data possible. **/ /** * Inflate.msg -> String * * Error message, if [[Inflate.err]] != 0 **/ /** * new Inflate(options) * - options (Object): zlib inflate options. * * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * * - `windowBits` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw inflate * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * By default, when no options set, autodetect deflate/gzip data format via * wrapper header. * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var inflate = new pako.Inflate({ level: 3}); * * inflate.push(chunk1, false); * inflate.push(chunk2, true); // true -> last chunk * * if (inflate.err) { throw new Error(inflate.err); } * * console.log(inflate.result); * ``` **/ function Inflate(options) { if (!(this instanceof Inflate)) return new Inflate(options); this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if ((opt.windowBits >= 0) && (opt.windowBits < 16) && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if ((opt.windowBits > 15) && (opt.windowBits < 48)) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new ZStream(); this.strm.avail_out = 0; var status = zlib_inflate.inflateInit2( this.strm, opt.windowBits ); if (status !== c.Z_OK) { throw new Error(msg[status]); } this.header = new GZheader(); zlib_inflate.inflateGetHeader(this.strm, this.header); } /** * Inflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with * new output chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the decompression context. * * On fail call [[Inflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Inflate.prototype.push = function (data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; var next_out_utf8, tail, utf8str; // Flag to properly process Z_BUF_ERROR on testing inflate call // when we check that all output data was flushed. var allowBufError = false; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // Only binary strings can be decompressed on practice strm.input = strings.binstring2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ if (status === c.Z_BUF_ERROR && allowBufError === true) { status = c.Z_OK; allowBufError = false; } if (status !== c.Z_STREAM_END && status !== c.Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.next_out) { if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { if (this.options.to === 'string') { next_out_utf8 = strings.utf8border(strm.output, strm.next_out); tail = strm.next_out - next_out_utf8; utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail strm.next_out = tail; strm.avail_out = chunkSize - tail; if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } this.onData(utf8str); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } // When no more input data, we should check that internal inflate buffers // are flushed. The only way to do it when avail_out = 0 - run one more // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. // Here we set flag to process this error properly. // // NOTE. Deflate does not return error in this case and does not needs such // logic. if (strm.avail_in === 0 && strm.avail_out === 0) { allowBufError = true; } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); if (status === c.Z_STREAM_END) { _mode = c.Z_FINISH; } // Finalize on the last chunk. if (_mode === c.Z_FINISH) { status = zlib_inflate.inflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === c.Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === c.Z_SYNC_FLUSH) { this.onEnd(c.Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Inflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Inflate.prototype.onData = function (chunk) { this.chunks.push(chunk); }; /** * Inflate#onEnd(status) -> Void * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * * Called either after you tell inflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Inflate.prototype.onEnd = function (status) { // On success - join if (status === c.Z_OK) { if (this.options.to === 'string') { // Glue & convert here, until we teach pako to send // utf8 alligned strings to onData this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * inflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Decompress `data` with inflate/ungzip and `options`. Autodetect * format via wrapper header by default. That's why we don't provide * separate `ungzip` method. * * Supported options are: * * - windowBits * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * * ##### Example: * * ```javascript * var pako = require('pako') * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) * , output; * * try { * output = pako.inflate(input); * } catch (err) * console.log(err); * } * ``` **/ function inflate(input, options) { var inflator = new Inflate(options); inflator.push(input, true); // That will never happens, if you don't cheat with options :) if (inflator.err) { throw inflator.msg; } return inflator.result; } /** * inflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function inflateRaw(input, options) { options = options || {}; options.raw = true; return inflate(input, options); } /** * ungzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Just shortcut to [[inflate]], because it autodetects format * by header.content. Done for convenience. **/ exports.Inflate = Inflate; exports.inflate = inflate; exports.inflateRaw = inflateRaw; exports.ungzip = inflate; },{"./utils/common":80,"./utils/strings":81,"./zlib/constants":83,"./zlib/gzheader":86,"./zlib/inflate":88,"./zlib/messages":90,"./zlib/zstream":92}],80:[function(_dereq_,module,exports){ 'use strict'; var TYPED_OK = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Int32Array !== 'undefined'); exports.assign = function (obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1); while (sources.length) { var source = sources.shift(); if (!source) { continue; } if (typeof source !== 'object') { throw new TypeError(source + 'must be non-object'); } for (var p in source) { if (source.hasOwnProperty(p)) { obj[p] = source[p]; } } } return obj; }; // reduce buffer size, avoiding mem copy exports.shrinkBuf = function (buf, size) { if (buf.length === size) { return buf; } if (buf.subarray) { return buf.subarray(0, size); } buf.length = size; return buf; }; var fnTyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { if (src.subarray && dest.subarray) { dest.set(src.subarray(src_offs, src_offs + len), dest_offs); return; } // Fallback to ordinary array for (var i = 0; i < len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function (chunks) { var i, l, len, pos, chunk, result; // calculate data length len = 0; for (i = 0, l = chunks.length; i < l; i++) { len += chunks[i].length; } // join chunks result = new Uint8Array(len); pos = 0; for (i = 0, l = chunks.length; i < l; i++) { chunk = chunks[i]; result.set(chunk, pos); pos += chunk.length; } return result; } }; var fnUntyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { for (var i = 0; i < len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function (chunks) { return [].concat.apply([], chunks); } }; // Enable/Disable typed arrays use, for testing // exports.setTyped = function (on) { if (on) { exports.Buf8 = Uint8Array; exports.Buf16 = Uint16Array; exports.Buf32 = Int32Array; exports.assign(exports, fnTyped); } else { exports.Buf8 = Array; exports.Buf16 = Array; exports.Buf32 = Array; exports.assign(exports, fnUntyped); } }; exports.setTyped(TYPED_OK); },{}],81:[function(_dereq_,module,exports){ // String encode/decode helpers 'use strict'; var utils = _dereq_('./common'); // Quick check if we can use fast array to bin string conversion // // - apply(Array) can fail on Android 2.2 // - apply(Uint8Array) can fail on iOS 5.1 Safary // var STR_APPLY_OK = true; var STR_APPLY_UIA_OK = true; try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; } try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } // Table with utf8 lengths (calculated by first byte of sequence) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff var _utf8len = new utils.Buf8(256); for (var q = 0; q < 256; q++) { _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); } _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start // convert string to array (typed, when possible) exports.string2buf = function (str) { var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { c2 = str.charCodeAt(m_pos + 1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } // allocate buffer buf = new utils.Buf8(buf_len); // convert for (i = 0, m_pos = 0; i < buf_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { c2 = str.charCodeAt(m_pos + 1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } if (c < 0x80) { /* one byte */ buf[i++] = c; } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | (c >>> 6); buf[i++] = 0x80 | (c & 0x3f); } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | (c >>> 12); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } else { /* four bytes */ buf[i++] = 0xf0 | (c >>> 18); buf[i++] = 0x80 | (c >>> 12 & 0x3f); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } } return buf; }; // Helper (used in 2 places) function buf2binstring(buf, len) { // use fallback for big arrays to avoid stack overflow if (len < 65537) { if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); } } var result = ''; for (var i = 0; i < len; i++) { result += String.fromCharCode(buf[i]); } return result; } // Convert byte array to binary string exports.buf2binstring = function (buf) { return buf2binstring(buf, buf.length); }; // Convert binary string (typed, when possible) exports.binstring2buf = function (str) { var buf = new utils.Buf8(str.length); for (var i = 0, len = buf.length; i < len; i++) { buf[i] = str.charCodeAt(i); } return buf; }; // convert array to string exports.buf2string = function (buf, max) { var i, out, c, c_len; var len = max || buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. var utf16buf = new Array(len * 2); for (out = 0, i = 0; i < len;) { c = buf[i++]; // quick process ascii if (c < 0x80) { utf16buf[out++] = c; continue; } c_len = _utf8len[c]; // skip 5 & 6 byte codes if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } // apply mask on first byte c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest while (c_len > 1 && i < len) { c = (c << 6) | (buf[i++] & 0x3f); c_len--; } // terminated by end of string? if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } if (c < 0x10000) { utf16buf[out++] = c; } else { c -= 0x10000; utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); utf16buf[out++] = 0xdc00 | (c & 0x3ff); } } return buf2binstring(utf16buf, out); }; // Calculate max possible position in utf8 buffer, // that will not break sequence. If that's not possible // - (very small limits) return max size as is. // // buf[] - utf8 bytes array // max - length limit (mandatory); exports.utf8border = function (buf, max) { var pos; max = max || buf.length; if (max > buf.length) { max = buf.length; } // go back from last position, until start of sequence found pos = max - 1; while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } // Fuckup - very small and broken sequence, // return max, because we should return something anyway. if (pos < 0) { return max; } // If we came to start of buffer - that means vuffer is too small, // return max too. if (pos === 0) { return max; } return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; },{"./common":80}],82:[function(_dereq_,module,exports){ 'use strict'; // Note: adler32 takes 12% for level 0 and 2% for level 6. // It doesn't worth to make additional optimizationa as in original. // Small size is preferable. function adler32(adler, buf, len, pos) { var s1 = (adler & 0xffff) |0, s2 = ((adler >>> 16) & 0xffff) |0, n = 0; while (len !== 0) { // Set limit ~ twice less than 5552, to keep // s2 in 31-bits, because we force signed ints. // in other case %= will fail. n = len > 2000 ? 2000 : len; len -= n; do { s1 = (s1 + buf[pos++]) |0; s2 = (s2 + s1) |0; } while (--n); s1 %= 65521; s2 %= 65521; } return (s1 | (s2 << 16)) |0; } module.exports = adler32; },{}],83:[function(_dereq_,module,exports){ 'use strict'; module.exports = { /* Allowed flush values; see deflate() and inflate() below for details */ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, //Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, //Z_VERSION_ERROR: -6, /* compression levels */ Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, /* Possible values of the data_type field (though see inflate()) */ Z_BINARY: 0, Z_TEXT: 1, //Z_ASCII: 1, // = Z_TEXT (deprecated) Z_UNKNOWN: 2, /* The deflate compression method */ Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type }; },{}],84:[function(_dereq_,module,exports){ 'use strict'; // Note: we can't get significant speed boost here. // So write code to minimize size - no pregenerated tables // and array tools dependencies. // Use ordinary array, since untyped makes no boost here function makeTable() { var c, table = []; for (var n = 0; n < 256; n++) { c = n; for (var k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } table[n] = c; } return table; } // Create table on load. Just 255 signed longs. Not a problem. var crcTable = makeTable(); function crc32(crc, buf, len, pos) { var t = crcTable, end = pos + len; crc ^= -1; for (var i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; },{}],85:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var trees = _dereq_('./trees'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var msg = _dereq_('./messages'); /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ var Z_NO_FLUSH = 0; var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; //var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; //var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; //var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* compression levels */ //var Z_NO_COMPRESSION = 0; //var Z_BEST_SPEED = 1; //var Z_BEST_COMPRESSION = 9; var Z_DEFAULT_COMPRESSION = -1; var Z_FILTERED = 1; var Z_HUFFMAN_ONLY = 2; var Z_RLE = 3; var Z_FIXED = 4; var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ //var Z_BINARY = 0; //var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /* The deflate compression method */ var Z_DEFLATED = 8; /*============================================================================*/ var MAX_MEM_LEVEL = 9; /* Maximum value for memLevel in deflateInit2 */ var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_MEM_LEVEL = 8; var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2 * L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var MIN_MATCH = 3; var MAX_MATCH = 258; var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); var PRESET_DICT = 0x20; var INIT_STATE = 42; var EXTRA_STATE = 69; var NAME_STATE = 73; var COMMENT_STATE = 91; var HCRC_STATE = 103; var BUSY_STATE = 113; var FINISH_STATE = 666; var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ var BS_BLOCK_DONE = 2; /* block flush performed */ var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. function err(strm, errorCode) { strm.msg = msg[errorCode]; return errorCode; } function rank(f) { return ((f) << 1) - ((f) > 4 ? 9 : 0); } function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->output buffer and copying into it. * (See also read_buf()). */ function flush_pending(strm) { var s = strm.state; //_tr_flush_bits(s); var len = s.pending; if (len > strm.avail_out) { len = strm.avail_out; } if (len === 0) { return; } utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); strm.next_out += len; s.pending_out += len; strm.total_out += len; strm.avail_out -= len; s.pending -= len; if (s.pending === 0) { s.pending_out = 0; } } function flush_block_only(s, last) { trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); s.block_start = s.strstart; flush_pending(s.strm); } function put_byte(s, b) { s.pending_buf[s.pending++] = b; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ function putShortMSB(s, b) { // put_byte(s, (Byte)(b >> 8)); // put_byte(s, (Byte)(b & 0xff)); s.pending_buf[s.pending++] = (b >>> 8) & 0xff; s.pending_buf[s.pending++] = b & 0xff; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->input buffer and copying from it. * (See also flush_pending()). */ function read_buf(strm, buf, start, size) { var len = strm.avail_in; if (len > size) { len = size; } if (len === 0) { return 0; } strm.avail_in -= len; utils.arraySet(buf, strm.input, strm.next_in, len, start); if (strm.state.wrap === 1) { strm.adler = adler32(strm.adler, buf, len, start); } else if (strm.state.wrap === 2) { strm.adler = crc32(strm.adler, buf, len, start); } strm.next_in += len; strm.total_in += len; return len; } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ function longest_match(s, cur_match) { var chain_length = s.max_chain_length; /* max hash chain length */ var scan = s.strstart; /* current string */ var match; /* matched string */ var len; /* length of current match */ var best_len = s.prev_length; /* best match length so far */ var nice_match = s.nice_match; /* stop if match long enough */ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; var _win = s.window; // shortcut var wmask = s.w_mask; var prev = s.prev; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ var strend = s.strstart + MAX_MATCH; var scan_end1 = _win[scan + best_len - 1]; var scan_end = _win[scan + best_len]; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s.prev_length >= s.good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (nice_match > s.lookahead) { nice_match = s.lookahead; } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { // Assert(cur_match < s->strstart, "no future"); match = cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { continue; } /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2; match++; // Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { /*jshint noempty:false*/ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { s.match_start = cur_match; best_len = len; if (len >= nice_match) { break; } scan_end1 = _win[scan + best_len - 1]; scan_end = _win[scan + best_len]; } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); if (best_len <= s.lookahead) { return best_len; } return s.lookahead; } /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ function fill_window(s) { var _w_size = s.w_size; var p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = s.window_size - s.lookahead - s.strstart; // JS ints have 32 bit, block below not needed /* Deal with !@#$% 64K limit: */ //if (sizeof(int) <= 2) { // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { // more = wsize; // // } else if (more == (unsigned)(-1)) { // /* Very unlikely, but possible on 16 bit machine if // * strstart == 0 && lookahead == 1 (input done a byte at time) // */ // more--; // } //} /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { utils.arraySet(s.window, s.window, _w_size, _w_size, 0); s.match_start -= _w_size; s.strstart -= _w_size; /* we now have strstart >= MAX_DIST */ s.block_start -= _w_size; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s.hash_size; p = n; do { m = s.head[--p]; s.head[p] = (m >= _w_size ? m - _w_size : 0); } while (--n); n = _w_size; p = n; do { m = s.prev[--p]; s.prev[p] = (m >= _w_size ? m - _w_size : 0); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += _w_size; } if (s.strm.avail_in === 0) { break; } /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ //Assert(more >= 2, "more < 2"); n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); s.lookahead += n; /* Initialize the hash value now that we have some input: */ if (s.lookahead + s.insert >= MIN_MATCH) { str = s.strstart - s.insert; s.ins_h = s.window[str]; /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call update_hash() MIN_MATCH-3 more times //#endif while (s.insert) { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; s.insert--; if (s.lookahead + s.insert < MIN_MATCH) { break; } } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ // if (s.high_water < s.window_size) { // var curr = s.strstart + s.lookahead; // var init = 0; // // if (s.high_water < curr) { // /* Previous high water mark below current data -- zero WIN_INIT // * bytes or up to end of window, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->window + curr, (unsigned)init); // s->high_water = curr + init; // } // else if (s->high_water < (ulg)curr + WIN_INIT) { // /* High water mark at or above current data, but below current data // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up // * to end of window, whichever is less. // */ // init = (ulg)curr + WIN_INIT - s->high_water; // if (init > s->window_size - s->high_water) // init = s->window_size - s->high_water; // zmemzero(s->window + s->high_water, (unsigned)init); // s->high_water += init; // } // } // // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, // "not enough room for search"); } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ function deflate_stored(s, flush) { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ var max_block_size = 0xffff; if (max_block_size > s.pending_buf_size - 5) { max_block_size = s.pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s.lookahead <= 1) { //Assert(s->strstart < s->w_size+MAX_DIST(s) || // s->block_start >= (long)s->w_size, "slide too late"); // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || // s.block_start >= s.w_size)) { // throw new Error("slide too late"); // } fill_window(s); if (s.lookahead === 0 && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } //Assert(s->block_start >= 0L, "block gone"); // if (s.block_start < 0) throw new Error("block gone"); s.strstart += s.lookahead; s.lookahead = 0; /* Emit a stored block if pending_buf will be full: */ var max_start = s.block_start + max_block_size; if (s.strstart === 0 || s.strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s.lookahead = s.strstart - max_start; s.strstart = max_start; /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.strstart > s.block_start) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_NEED_MORE; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ function deflate_fast(s, flush) { var hash_head; /* head of the hash chain */ var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; /* flush the current block */ } } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ } if (s.match_length >= MIN_MATCH) { // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only /*** _tr_tally_dist(s, s.strstart - s.match_start, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { s.match_length--; /* string at strstart already in table */ do { s.strstart++; /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s.match_length !== 0); s.strstart++; } else { s.strstart += s.match_length; s.match_length = 0; s.ins_h = s.window[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call UPDATE_HASH() MIN_MATCH-3 more times //#endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s.window[s.strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ function deflate_slow(s, flush) { var hash_head; /* head of hash chain */ var bflush; /* set if current block must be flushed */ var max_insert; /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. */ s.prev_length = s.match_length; s.prev_match = s.match_start; s.match_length = MIN_MATCH - 1; if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ if (s.match_length <= 5 && (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s.match_length = MIN_MATCH - 1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { max_insert = s.strstart + s.lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ //check_match(s, s.strstart-1, s.prev_match, s.prev_length); /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH, bflush);***/ bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s.lookahead -= s.prev_length - 1; s.prev_length -= 2; do { if (++s.strstart <= max_insert) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } } while (--s.prev_length !== 0); s.match_available = 0; s.match_length = MIN_MATCH - 1; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } else if (s.match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); if (bflush) { /*** FLUSH_BLOCK_ONLY(s, 0) ***/ flush_block_only(s, false); /***/ } s.strstart++; s.lookahead--; if (s.strm.avail_out === 0) { return BS_NEED_MORE; } } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s.match_available = 1; s.strstart++; s.lookahead--; } } //Assert (flush != Z_NO_FLUSH, "no flush?"); if (s.match_available) { //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); s.match_available = 0; } s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ function deflate_rle(s, flush) { var bflush; /* set if current block must be flushed */ var prev; /* byte at distance one to match */ var scan, strend; /* scan goes up to strend for length of run */ var _win = s.window; for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s.lookahead <= MAX_MATCH) { fill_window(s); if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* See how many times the previous byte repeats */ s.match_length = 0; if (s.lookahead >= MIN_MATCH && s.strstart > 0) { scan = s.strstart - 1; prev = _win[scan]; if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { strend = s.strstart + MAX_MATCH; do { /*jshint noempty:false*/ } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); s.match_length = MAX_MATCH - (strend - scan); if (s.match_length > s.lookahead) { s.match_length = s.lookahead; } } //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s.match_length >= MIN_MATCH) { //check_match(s, s.strstart, s.strstart - 1, s.match_length); /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; s.strstart += s.match_length; s.match_length = 0; } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ function deflate_huff(s, flush) { var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s.lookahead === 0) { fill_window(s); if (s.lookahead === 0) { if (flush === Z_NO_FLUSH) { return BS_NEED_MORE; } break; /* flush the current block */ } } /* Output a literal byte */ s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ function Config(good_length, max_lazy, nice_length, max_chain, func) { this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; this.max_chain = max_chain; this.func = func; } var configuration_table; configuration_table = [ /* good lazy nice chain */ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ new Config(4, 5, 16, 8, deflate_fast), /* 2 */ new Config(4, 6, 32, 32, deflate_fast), /* 3 */ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ new Config(8, 16, 32, 32, deflate_slow), /* 5 */ new Config(8, 16, 128, 128, deflate_slow), /* 6 */ new Config(8, 32, 128, 256, deflate_slow), /* 7 */ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ ]; /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ function lm_init(s) { s.window_size = 2 * s.w_size; /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); /* Set the default configuration parameters: */ s.max_lazy_match = configuration_table[s.level].max_lazy; s.good_match = configuration_table[s.level].good_length; s.nice_match = configuration_table[s.level].nice_length; s.max_chain_length = configuration_table[s.level].max_chain; s.strstart = 0; s.block_start = 0; s.lookahead = 0; s.insert = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; s.ins_h = 0; } function DeflateState() { this.strm = null; /* pointer back to this zlib stream */ this.status = 0; /* as the name implies */ this.pending_buf = null; /* output still pending */ this.pending_buf_size = 0; /* size of pending_buf */ this.pending_out = 0; /* next pending byte to output to the stream */ this.pending = 0; /* nb of bytes in the pending buffer */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.gzhead = null; /* gzip header information to write */ this.gzindex = 0; /* where in extra, name, or comment */ this.method = Z_DEFLATED; /* can only be DEFLATED */ this.last_flush = -1; /* value of flush param for previous deflate call */ this.w_size = 0; /* LZ77 window size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.window = null; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. */ this.window_size = 0; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ this.prev = null; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ this.head = null; /* Heads of the hash chains or NIL. */ this.ins_h = 0; /* hash index of string to be inserted */ this.hash_size = 0; /* number of elements in hash table */ this.hash_bits = 0; /* log2(hash_size) */ this.hash_mask = 0; /* hash_size-1 */ this.hash_shift = 0; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ this.block_start = 0; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ this.match_length = 0; /* length of best match */ this.prev_match = 0; /* previous match */ this.match_available = 0; /* set if previous match exists */ this.strstart = 0; /* start of string to insert */ this.match_start = 0; /* start of matching string */ this.lookahead = 0; /* number of valid bytes ahead in window */ this.prev_length = 0; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ this.max_chain_length = 0; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ this.max_lazy_match = 0; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ // That's alias to max_lazy_match, don't use directly //this.max_insert_length = 0; /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ this.level = 0; /* compression level (1..9) */ this.strategy = 0; /* favor or force Huffman coding*/ this.good_match = 0; /* Use a faster search when the previous match is longer than this */ this.nice_match = 0; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to suppress compiler warning */ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ // Use flat array of DOUBLE size, with interleaved fata, // because JS does not support effective this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); zero(this.dyn_ltree); zero(this.dyn_dtree); zero(this.bl_tree); this.l_desc = null; /* desc. for literal tree */ this.d_desc = null; /* desc. for distance tree */ this.bl_desc = null; /* desc. for bit length tree */ //ush bl_count[MAX_BITS+1]; this.bl_count = new utils.Buf16(MAX_BITS + 1); /* number of codes at each bit length for an optimal tree */ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ zero(this.heap); this.heap_len = 0; /* number of elements in the heap */ this.heap_max = 0; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; zero(this.depth); /* Depth of each subtree used as tie breaker for trees of equal frequency */ this.l_buf = 0; /* buffer index for literals or lengths */ this.lit_bufsize = 0; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ this.last_lit = 0; /* running index in l_buf */ this.d_buf = 0; /* Buffer index for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ this.opt_len = 0; /* bit length of current block with optimal trees */ this.static_len = 0; /* bit length of current block with static trees */ this.matches = 0; /* number of string matches in current block */ this.insert = 0; /* bytes at end of window left to insert */ this.bi_buf = 0; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ this.bi_valid = 0; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ // Used for window memory init. We safely ignore it for JS. That makes // sense only for pointers and memory check tools. //this.high_water = 0; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } function deflateResetKeep(strm) { var s; if (!strm || !strm.state) { return err(strm, Z_STREAM_ERROR); } strm.total_in = strm.total_out = 0; strm.data_type = Z_UNKNOWN; s = strm.state; s.pending = 0; s.pending_out = 0; if (s.wrap < 0) { s.wrap = -s.wrap; /* was made negative by deflate(..., Z_FINISH); */ } s.status = (s.wrap ? INIT_STATE : BUSY_STATE); strm.adler = (s.wrap === 2) ? 0 // crc32(0, Z_NULL, 0) : 1; // adler32(0, Z_NULL, 0) s.last_flush = Z_NO_FLUSH; trees._tr_init(s); return Z_OK; } function deflateReset(strm) { var ret = deflateResetKeep(strm); if (ret === Z_OK) { lm_init(strm.state); } return ret; } function deflateSetHeader(strm, head) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } strm.state.gzhead = head; return Z_OK; } function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { if (!strm) { // === Z_NULL return Z_STREAM_ERROR; } var wrap = 1; if (level === Z_DEFAULT_COMPRESSION) { level = 6; } if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return err(strm, Z_STREAM_ERROR); } if (windowBits === 8) { windowBits = 9; } /* until 256-byte window bug fixed */ var s = new DeflateState(); strm.state = s; s.strm = strm; s.wrap = wrap; s.gzhead = null; s.w_bits = windowBits; s.w_size = 1 << s.w_bits; s.w_mask = s.w_size - 1; s.hash_bits = memLevel + 7; s.hash_size = 1 << s.hash_bits; s.hash_mask = s.hash_size - 1; s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); s.window = new utils.Buf8(s.w_size * 2); s.head = new utils.Buf16(s.hash_size); s.prev = new utils.Buf16(s.w_size); // Don't need mem init magic for JS. //s.high_water = 0; /* nothing written to s->window yet */ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ s.pending_buf_size = s.lit_bufsize * 4; s.pending_buf = new utils.Buf8(s.pending_buf_size); s.d_buf = s.lit_bufsize >> 1; s.l_buf = (1 + 2) * s.lit_bufsize; s.level = level; s.strategy = strategy; s.method = method; return deflateReset(strm); } function deflateInit(strm, level) { return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } function deflate(strm, flush) { var old_flush, s; var beg, val; // for gzip header write only if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; } s = strm.state; if (!strm.output || (!strm.input && strm.avail_in !== 0) || (s.status === FINISH_STATE && flush !== Z_FINISH)) { return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); } s.strm = strm; /* just in case */ old_flush = s.last_flush; s.last_flush = flush; /* Write the header */ if (s.status === INIT_STATE) { if (s.wrap === 2) { // GZIP header strm.adler = 0; //crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (!s.gzhead) { // s->gzhead == Z_NULL put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s.status = BUSY_STATE; } else { put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) ); put_byte(s, s.gzhead.time & 0xff); put_byte(s, (s.gzhead.time >> 8) & 0xff); put_byte(s, (s.gzhead.time >> 16) & 0xff); put_byte(s, (s.gzhead.time >> 24) & 0xff); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, s.gzhead.os & 0xff); if (s.gzhead.extra && s.gzhead.extra.length) { put_byte(s, s.gzhead.extra.length & 0xff); put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); } if (s.gzhead.hcrc) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); } s.gzindex = 0; s.status = EXTRA_STATE; } } else // DEFLATE header { var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; var level_flags = -1; if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { level_flags = 0; } else if (s.level < 6) { level_flags = 1; } else if (s.level === 6) { level_flags = 2; } else { level_flags = 3; } header |= (level_flags << 6); if (s.strstart !== 0) { header |= PRESET_DICT; } header += 31 - (header % 31); s.status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s.strstart !== 0) { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } strm.adler = 1; // adler32(0L, Z_NULL, 0); } } //#ifdef GZIP if (s.status === EXTRA_STATE) { if (s.gzhead.extra/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { break; } } put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); s.gzindex++; } if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (s.gzindex === s.gzhead.extra.length) { s.gzindex = 0; s.status = NAME_STATE; } } else { s.status = NAME_STATE; } } if (s.status === NAME_STATE) { if (s.gzhead.name/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.name.length) { val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.gzindex = 0; s.status = COMMENT_STATE; } } else { s.status = COMMENT_STATE; } } if (s.status === COMMENT_STATE) { if (s.gzhead.comment/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.comment.length) { val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.status = HCRC_STATE; } } else { s.status = HCRC_STATE; } } if (s.status === HCRC_STATE) { if (s.gzhead.hcrc) { if (s.pending + 2 > s.pending_buf_size) { flush_pending(strm); } if (s.pending + 2 <= s.pending_buf_size) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); strm.adler = 0; //crc32(0L, Z_NULL, 0); s.status = BUSY_STATE; } } else { s.status = BUSY_STATE; } } //#endif /* Flush as much pending output as possible */ if (s.pending !== 0) { flush_pending(strm); if (strm.avail_out === 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s.last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { return err(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s.status === FINISH_STATE && strm.avail_in !== 0) { return err(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm.avail_in !== 0 || s.lookahead !== 0 || (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : (s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush)); if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { s.status = FINISH_STATE; } if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate === BS_BLOCK_DONE) { if (flush === Z_PARTIAL_FLUSH) { trees._tr_align(s); } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ trees._tr_stored_block(s, 0, 0, false); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush === Z_FULL_FLUSH) { /*** CLEAR_HASH(s); ***/ /* forget history */ zero(s.head); // Fill with NIL (= 0); if (s.lookahead === 0) { s.strstart = 0; s.block_start = 0; s.insert = 0; } } } flush_pending(strm); if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } //Assert(strm->avail_out > 0, "bug2"); //if (strm.avail_out <= 0) { throw new Error("bug2");} if (flush !== Z_FINISH) { return Z_OK; } if (s.wrap <= 0) { return Z_STREAM_END; } /* Write the trailer */ if (s.wrap === 2) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); put_byte(s, (strm.adler >> 16) & 0xff); put_byte(s, (strm.adler >> 24) & 0xff); put_byte(s, strm.total_in & 0xff); put_byte(s, (strm.total_in >> 8) & 0xff); put_byte(s, (strm.total_in >> 16) & 0xff); put_byte(s, (strm.total_in >> 24) & 0xff); } else { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s.wrap > 0) { s.wrap = -s.wrap; } /* write the trailer only once! */ return s.pending !== 0 ? Z_OK : Z_STREAM_END; } function deflateEnd(strm) { var status; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } status = strm.state.status; if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE ) { return err(strm, Z_STREAM_ERROR); } strm.state = null; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; } /* ========================================================================= * Copy the source state to the destination state */ //function deflateCopy(dest, source) { // //} exports.deflateInit = deflateInit; exports.deflateInit2 = deflateInit2; exports.deflateReset = deflateReset; exports.deflateResetKeep = deflateResetKeep; exports.deflateSetHeader = deflateSetHeader; exports.deflate = deflate; exports.deflateEnd = deflateEnd; exports.deflateInfo = 'pako deflate (from Nodeca project)'; /* Not implemented exports.deflateBound = deflateBound; exports.deflateCopy = deflateCopy; exports.deflateSetDictionary = deflateSetDictionary; exports.deflateParams = deflateParams; exports.deflatePending = deflatePending; exports.deflatePrime = deflatePrime; exports.deflateTune = deflateTune; */ },{"../utils/common":80,"./adler32":82,"./crc32":84,"./messages":90,"./trees":91}],86:[function(_dereq_,module,exports){ 'use strict'; function GZheader() { /* true if compressed data believed to be text */ this.text = 0; /* modification time */ this.time = 0; /* extra flags (not used when writing a gzip file) */ this.xflags = 0; /* operating system */ this.os = 0; /* pointer to extra field or Z_NULL if none */ this.extra = null; /* extra field length (valid if extra != Z_NULL) */ this.extra_len = 0; // Actually, we don't need it in JS, // but leave for few code modifications // // Setup limits is not necessary because in js we should not preallocate memory // for inflate use constant limit in 65536 bytes // /* space at extra (only when reading header) */ // this.extra_max = 0; /* pointer to zero-terminated file name or Z_NULL */ this.name = ''; /* space at name (only when reading header) */ // this.name_max = 0; /* pointer to zero-terminated comment or Z_NULL */ this.comment = ''; /* space at comment (only when reading header) */ // this.comm_max = 0; /* true if there was or will be a header crc */ this.hcrc = 0; /* true when done reading gzip header (not used when writing a gzip file) */ this.done = false; } module.exports = GZheader; },{}],87:[function(_dereq_,module,exports){ 'use strict'; // See state defs from inflate.js var BAD = 30; /* got a data error -- remain here until reset */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state.mode === LEN strm.avail_in >= 6 strm.avail_out >= 258 start >= strm.avail_out state.bits < 8 On return, state.mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm.avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm.avail_out >= 258 for each loop to avoid checking for output space. */ module.exports = function inflate_fast(strm, start) { var state; var _in; /* local strm.input */ var last; /* have enough input while in < last */ var _out; /* local strm.output */ var beg; /* inflate()'s initial strm.output */ var end; /* while out < end, enough space available */ //#ifdef INFLATE_STRICT var dmax; /* maximum distance from zlib header */ //#endif var wsize; /* window size or zero if not using window */ var whave; /* valid bytes in the window */ var wnext; /* window write index */ // Use `s_window` instead `window`, avoid conflict with instrumentation tools var s_window; /* allocated sliding window, if wsize != 0 */ var hold; /* local strm.hold */ var bits; /* local strm.bits */ var lcode; /* local strm.lencode */ var dcode; /* local strm.distcode */ var lmask; /* mask for first level of length codes */ var dmask; /* mask for first level of distance codes */ var here; /* retrieved table entry */ var op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ var len; /* match length, unused bytes */ var dist; /* match distance */ var from; /* where to copy match from */ var from_source; var input, output; // JS specific, because we have no pointers /* copy state to local variables */ state = strm.state; //here = state.here; _in = strm.next_in; input = strm.input; last = _in + (strm.avail_in - 5); _out = strm.next_out; output = strm.output; beg = _out - (start - strm.avail_out); end = _out + (strm.avail_out - 257); //#ifdef INFLATE_STRICT dmax = state.dmax; //#endif wsize = state.wsize; whave = state.whave; wnext = state.wnext; s_window = state.window; hold = state.hold; bits = state.bits; lcode = state.lencode; dcode = state.distcode; lmask = (1 << state.lenbits) - 1; dmask = (1 << state.distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ top: do { if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = lcode[hold & lmask]; dolen: for (;;) { // Goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op === 0) { /* literal */ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); output[_out++] = here & 0xffff/*here.val*/; } else if (op & 16) { /* length base */ len = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += input[_in++] << bits; bits += 8; } len += hold & ((1 << op) - 1); hold >>>= op; bits -= op; } //Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = dcode[hold & dmask]; dodist: for (;;) { // goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op & 16) { /* distance base */ dist = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (bits < op) { hold += input[_in++] << bits; bits += 8; if (bits < op) { hold += input[_in++] << bits; bits += 8; } } dist += hold & ((1 << op) - 1); //#ifdef INFLATE_STRICT if (dist > dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } //#endif hold >>>= op; bits -= op; //Tracevv((stderr, "inflate: distance %u\n", dist)); op = _out - beg; /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // if (len <= op - whave) { // do { // output[_out++] = 0; // } while (--len); // continue top; // } // len -= op - whave; // do { // output[_out++] = 0; // } while (--op > whave); // if (op === 0) { // from = _out - dist; // do { // output[_out++] = output[from++]; // } while (--len); // continue top; // } //#endif } from = 0; // window index from_source = s_window; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } while (len > 2) { output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; len -= 3; } if (len) { output[_out++] = from_source[from++]; if (len > 1) { output[_out++] = from_source[from++]; } } } else { from = _out - dist; /* copy direct from output */ do { /* minimum length is three */ output[_out++] = output[from++]; output[_out++] = output[from++]; output[_out++] = output[from++]; len -= 3; } while (len > 2); if (len) { output[_out++] = output[from++]; if (len > 1) { output[_out++] = output[from++]; } } } } else if ((op & 64) === 0) { /* 2nd level distance code */ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dodist; } else { strm.msg = 'invalid distance code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } else if ((op & 64) === 0) { /* 2nd level length code */ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dolen; } else if (op & 32) { /* end-of-block */ //Tracevv((stderr, "inflate: end of block\n")); state.mode = TYPE; break top; } else { strm.msg = 'invalid literal/length code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } while (_in < last && _out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; _in -= len; bits -= len << 3; hold &= (1 << bits) - 1; /* update state and return */ strm.next_in = _in; strm.next_out = _out; strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); state.hold = hold; state.bits = bits; return; }; },{}],88:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var inflate_fast = _dereq_('./inffast'); var inflate_table = _dereq_('./inftrees'); var CODES = 0; var LENS = 1; var DISTS = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ //var Z_NO_FLUSH = 0; //var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; //var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* The deflate compression method */ var Z_DEFLATED = 8; /* STATES ====================================================================*/ /* ===========================================================================*/ var HEAD = 1; /* i: waiting for magic header */ var FLAGS = 2; /* i: waiting for method and flags (gzip) */ var TIME = 3; /* i: waiting for modification time (gzip) */ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ var EXLEN = 5; /* i: waiting for extra length (gzip) */ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ var NAME = 7; /* i: waiting for end of file name (gzip) */ var COMMENT = 8; /* i: waiting for end of comment (gzip) */ var HCRC = 9; /* i: waiting for header crc (gzip) */ var DICTID = 10; /* i: waiting for dictionary check value */ var DICT = 11; /* waiting for inflateSetDictionary() call */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ var STORED = 14; /* i: waiting for stored size (length and complement) */ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ var COPY = 16; /* i/o: waiting for input or output to copy stored block */ var TABLE = 17; /* i: waiting for dynamic block table lengths */ var LENLENS = 18; /* i: waiting for code length code lengths */ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ var LEN_ = 20; /* i: same as LEN below, but only first time in */ var LEN = 21; /* i: waiting for length/lit/eob code */ var LENEXT = 22; /* i: waiting for length extra bits */ var DIST = 23; /* i: waiting for distance code */ var DISTEXT = 24; /* i: waiting for distance extra bits */ var MATCH = 25; /* o: waiting for output space to copy string */ var LIT = 26; /* o: waiting for output space to write literal */ var CHECK = 27; /* i: waiting for 32-bit check value */ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ var DONE = 29; /* finished check, done -- remain here until reset */ var BAD = 30; /* got a data error -- remain here until reset */ var MEM = 31; /* got an inflate() memory error -- remain here until reset */ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_WBITS = MAX_WBITS; function zswap32(q) { return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); } function InflateState() { this.mode = 0; /* current inflate mode */ this.last = false; /* true if processing last block */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.havedict = false; /* true if dictionary provided */ this.flags = 0; /* gzip header method and flags (0 if zlib) */ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ this.check = 0; /* protected copy of check value */ this.total = 0; /* protected copy of output count */ // TODO: may be {} this.head = null; /* where to save gzip header information */ /* sliding window */ this.wbits = 0; /* log base 2 of requested window size */ this.wsize = 0; /* window size or zero if not using window */ this.whave = 0; /* valid bytes in the window */ this.wnext = 0; /* window write index */ this.window = null; /* allocated sliding window, if needed */ /* bit accumulator */ this.hold = 0; /* input bit accumulator */ this.bits = 0; /* number of bits in "in" */ /* for string and stored block copying */ this.length = 0; /* literal or length of data to copy */ this.offset = 0; /* distance back to copy string from */ /* for table and code decoding */ this.extra = 0; /* extra bits needed */ /* fixed and dynamic code tables */ this.lencode = null; /* starting table for length/literal codes */ this.distcode = null; /* starting table for distance codes */ this.lenbits = 0; /* index bits for lencode */ this.distbits = 0; /* index bits for distcode */ /* dynamic table building */ this.ncode = 0; /* number of code length code lengths */ this.nlen = 0; /* number of length code lengths */ this.ndist = 0; /* number of distance code lengths */ this.have = 0; /* number of code lengths in lens[] */ this.next = null; /* next available space in codes[] */ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ this.work = new utils.Buf16(288); /* work area for code table building */ /* because we don't have pointers in js, we use lencode and distcode directly as buffers so we don't need codes */ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ this.distdyn = null; /* dynamic table for distance codes (JS specific) */ this.sane = 0; /* if false, allow invalid distance too far */ this.back = 0; /* bits back of last unprocessed length/lit */ this.was = 0; /* initial length of match */ } function inflateResetKeep(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; strm.total_in = strm.total_out = state.total = 0; strm.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ strm.adler = state.wrap & 1; } state.mode = HEAD; state.last = 0; state.havedict = 0; state.dmax = 32768; state.head = null/*Z_NULL*/; state.hold = 0; state.bits = 0; //state.lencode = state.distcode = state.next = state.codes; state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); state.sane = 1; state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; } function inflateReset(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); } function inflateReset2(strm, windowBits) { var wrap; var state; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; if (windowBits < 48) { windowBits &= 15; } } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.window !== null && state.wbits !== windowBits) { state.window = null; } /* update state and reset the rest of it */ state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); } function inflateInit2(strm, windowBits) { var ret; var state; if (!strm) { return Z_STREAM_ERROR; } //strm.msg = Z_NULL; /* in case we return an error */ state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null/*Z_NULL*/; ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null/*Z_NULL*/; } return ret; } function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ var virgin = true; var lenfix, distfix; // We have no pointers in JS, so keep tables separate function fixedtables(state) { /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { var sym; lenfix = new utils.Buf32(512); distfix = new utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); /* do this just once */ virgin = false; } state.lencode = lenfix; state.lenbits = 9; state.distcode = distfix; state.distbits = 5; } /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ function updatewindow(strm, src, end, copy) { var dist; var state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.window = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state.wsize) { utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); state.wnext = 0; state.whave = state.wsize; } else { dist = state.wsize - state.wnext; if (dist > copy) { dist = copy; } //zmemcpy(state->window + state->wnext, end - copy, dist); utils.arraySet(state.window, src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->window, end - copy, copy); utils.arraySet(state.window, src, end - copy, copy, 0); state.wnext = copy; state.whave = state.wsize; } else { state.wnext += dist; if (state.wnext === state.wsize) { state.wnext = 0; } if (state.whave < state.wsize) { state.whave += dist; } } } return 0; } function inflate(strm, flush) { var state; var input, output; // input/output buffers var next; /* next input INDEX */ var put; /* next output INDEX */ var have, left; /* available input and output */ var hold; /* bit buffer */ var bits; /* bits in bit buffer */ var _in, _out; /* save starting available input and output */ var copy; /* number of stored or match bytes to copy */ var from; /* where to copy match bytes from */ var from_source; var here = 0; /* current decoding table entry */ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) //var last; /* parent table entry */ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) var len; /* length to copy for repeats, bits to drop */ var ret; /* return code */ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ var opts; var n; // temporary var for NEED_BITS var order = /* permutation of code lengths */ [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; if (!strm || !strm.state || !strm.output || (!strm.input && strm.avail_in !== 0)) { return Z_STREAM_ERROR; } state = strm.state; if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- _in = have; _out = left; ret = Z_OK; inf_leave: // goto emulation for (;;) { switch (state.mode) { case HEAD: if (state.wrap === 0) { state.mode = TYPEDO; break; } //=== NEEDBITS(16); while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ state.check = 0/*crc32(0L, Z_NULL, 0)*/; //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = FLAGS; break; } state.flags = 0; /* expect zlib header */ if (state.head) { state.head.done = false; } if (!(state.wrap & 1) || /* check if zlib header allowed */ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { strm.msg = 'incorrect header check'; state.mode = BAD; break; } if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// len = (hold & 0x0f)/*BITS(4)*/ + 8; if (state.wbits === 0) { state.wbits = len; } else if (len > state.wbits) { strm.msg = 'invalid window size'; state.mode = BAD; break; } state.dmax = 1 << len; //Tracev((stderr, "inflate: zlib header ok\n")); strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = hold & 0x200 ? DICTID : TYPE; //=== INITBITS(); hold = 0; bits = 0; //===// break; case FLAGS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.flags = hold; if ((state.flags & 0xff) !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } if (state.flags & 0xe000) { strm.msg = 'unknown header flags set'; state.mode = BAD; break; } if (state.head) { state.head.text = ((hold >> 8) & 1); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = TIME; /* falls through */ case TIME: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.time = hold; } if (state.flags & 0x0200) { //=== CRC4(state.check, hold) hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; hbuf[2] = (hold >>> 16) & 0xff; hbuf[3] = (hold >>> 24) & 0xff; state.check = crc32(state.check, hbuf, 4, 0); //=== } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = OS; /* falls through */ case OS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.xflags = (hold & 0xff); state.head.os = (hold >> 8); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = EXLEN; /* falls through */ case EXLEN: if (state.flags & 0x0400) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length = hold; if (state.head) { state.head.extra_len = hold; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// } else if (state.head) { state.head.extra = null/*Z_NULL*/; } state.mode = EXTRA; /* falls through */ case EXTRA: if (state.flags & 0x0400) { copy = state.length; if (copy > have) { copy = have; } if (copy) { if (state.head) { len = state.head.extra_len - state.length; if (!state.head.extra) { // Use untyped array for more conveniend processing later state.head.extra = new Array(state.head.extra_len); } utils.arraySet( state.head.extra, input, next, // extra field is limited to 65536 bytes // - no need for additional size check copy, /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ len ); //zmemcpy(state.head.extra + len, next, // len + copy > state.head.extra_max ? // state.head.extra_max - len : copy); } if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; state.length -= copy; } if (state.length) { break inf_leave; } } state.length = 0; state.mode = NAME; /* falls through */ case NAME: if (state.flags & 0x0800) { if (have === 0) { break inf_leave; } copy = 0; do { // TODO: 2 or 1 bytes? len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.name_max*/)) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.name = null; } state.length = 0; state.mode = COMMENT; /* falls through */ case COMMENT: if (state.flags & 0x1000) { if (have === 0) { break inf_leave; } copy = 0; do { len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.comm_max*/)) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.comment = null; } state.mode = HCRC; /* falls through */ case HCRC: if (state.flags & 0x0200) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.check & 0xffff)) { strm.msg = 'header crc mismatch'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// } if (state.head) { state.head.hcrc = ((state.flags >> 9) & 1); state.head.done = true; } strm.adler = state.check = 0; state.mode = TYPE; break; case DICTID: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// strm.adler = state.check = zswap32(hold); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = DICT; /* falls through */ case DICT: if (state.havedict === 0) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- return Z_NEED_DICT; } strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = TYPE; /* falls through */ case TYPE: if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } /* falls through */ case TYPEDO: if (state.last) { //--- BYTEBITS() ---// hold >>>= bits & 7; bits -= bits & 7; //---// state.mode = CHECK; break; } //=== NEEDBITS(3); */ while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.last = (hold & 0x01)/*BITS(1)*/; //--- DROPBITS(1) ---// hold >>>= 1; bits -= 1; //---// switch ((hold & 0x03)/*BITS(2)*/) { case 0: /* stored block */ //Tracev((stderr, "inflate: stored block%s\n", // state.last ? " (last)" : "")); state.mode = STORED; break; case 1: /* fixed block */ fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n", // state.last ? " (last)" : "")); state.mode = LEN_; /* decode codes */ if (flush === Z_TREES) { //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break inf_leave; } break; case 2: /* dynamic block */ //Tracev((stderr, "inflate: dynamic codes block%s\n", // state.last ? " (last)" : "")); state.mode = TABLE; break; case 3: strm.msg = 'invalid block type'; state.mode = BAD; } //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break; case STORED: //--- BYTEBITS() ---// /* go to byte boundary */ hold >>>= bits & 7; bits -= bits & 7; //---// //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { strm.msg = 'invalid stored block lengths'; state.mode = BAD; break; } state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n", // state.length)); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = COPY_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case COPY_: state.mode = COPY; /* falls through */ case COPY: copy = state.length; if (copy) { if (copy > have) { copy = have; } if (copy > left) { copy = left; } if (copy === 0) { break inf_leave; } //--- zmemcpy(put, next, copy); --- utils.arraySet(output, input, next, copy, put); //---// have -= copy; next += copy; left -= copy; put += copy; state.length -= copy; break; } //Tracev((stderr, "inflate: stored end\n")); state.mode = TYPE; break; case TABLE: //=== NEEDBITS(14); */ while (bits < 14) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// //#ifndef PKZIP_BUG_WORKAROUND if (state.nlen > 286 || state.ndist > 30) { strm.msg = 'too many length or distance symbols'; state.mode = BAD; break; } //#endif //Tracev((stderr, "inflate: table sizes ok\n")); state.have = 0; state.mode = LENLENS; /* falls through */ case LENLENS: while (state.have < state.ncode) { //=== NEEDBITS(3); while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } while (state.have < 19) { state.lens[order[state.have++]] = 0; } // We have separate tables & no pointers. 2 commented lines below not needed. //state.next = state.codes; //state.lencode = state.next; // Switch to use dynamic table state.lencode = state.lendyn; state.lenbits = 7; opts = { bits: state.lenbits }; ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); state.lenbits = opts.bits; if (ret) { strm.msg = 'invalid code lengths set'; state.mode = BAD; break; } //Tracev((stderr, "inflate: code lengths ok\n")); state.have = 0; state.mode = CODELENS; /* falls through */ case CODELENS: while (state.have < state.nlen + state.ndist) { for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_val < 16) { //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.lens[state.have++] = here_val; } else { if (here_val === 16) { //=== NEEDBITS(here.bits + 2); n = here_bits + 2; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// if (state.have === 0) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } len = state.lens[state.have - 1]; copy = 3 + (hold & 0x03);//BITS(2); //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// } else if (here_val === 17) { //=== NEEDBITS(here.bits + 3); n = here_bits + 3; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 3 + (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } else { //=== NEEDBITS(here.bits + 7); n = here_bits + 7; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 11 + (hold & 0x7f);//BITS(7); //--- DROPBITS(7) ---// hold >>>= 7; bits -= 7; //---// } if (state.have + copy > state.nlen + state.ndist) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } while (copy--) { state.lens[state.have++] = len; } } } /* handle error breaks in while */ if (state.mode === BAD) { break; } /* check for end-of-block code (better have one) */ if (state.lens[256] === 0) { strm.msg = 'invalid code -- missing end-of-block'; state.mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state.lenbits = 9; opts = { bits: state.lenbits }; ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.lenbits = opts.bits; // state.lencode = state.next; if (ret) { strm.msg = 'invalid literal/lengths set'; state.mode = BAD; break; } state.distbits = 6; //state.distcode.copy(state.codes); // Switch to use dynamic table state.distcode = state.distdyn; opts = { bits: state.distbits }; ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.distbits = opts.bits; // state.distcode = state.next; if (ret) { strm.msg = 'invalid distances set'; state.mode = BAD; break; } //Tracev((stderr, 'inflate: codes ok\n')); state.mode = LEN_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case LEN_: state.mode = LEN; /* falls through */ case LEN: if (have >= 6 && left >= 258) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- inflate_fast(strm, _out); //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- if (state.mode === TYPE) { state.back = -1; } break; } state.back = 0; for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_op && (here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.lencode[last_val + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; state.length = here_val; if (here_op === 0) { //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); state.mode = LIT; break; } if (here_op & 32) { //Tracevv((stderr, "inflate: end of block\n")); state.back = -1; state.mode = TYPE; break; } if (here_op & 64) { strm.msg = 'invalid literal/length code'; state.mode = BAD; break; } state.extra = here_op & 15; state.mode = LENEXT; /* falls through */ case LENEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //Tracevv((stderr, "inflate: length %u\n", state.length)); state.was = state.length; state.mode = DIST; /* falls through */ case DIST: for (;;) { here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if ((here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.distcode[last_val + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; if (here_op & 64) { strm.msg = 'invalid distance code'; state.mode = BAD; break; } state.offset = here_val; state.extra = (here_op) & 15; state.mode = DISTEXT; /* falls through */ case DISTEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //#ifdef INFLATE_STRICT if (state.offset > state.dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } //#endif //Tracevv((stderr, "inflate: distance %u\n", state.offset)); state.mode = MATCH; /* falls through */ case MATCH: if (left === 0) { break inf_leave; } copy = _out - left; if (state.offset > copy) { /* copy from window */ copy = state.offset - copy; if (copy > state.whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // Trace((stderr, "inflate.c too far\n")); // copy -= state.whave; // if (copy > state.length) { copy = state.length; } // if (copy > left) { copy = left; } // left -= copy; // state.length -= copy; // do { // output[put++] = 0; // } while (--copy); // if (state.length === 0) { state.mode = LEN; } // break; //#endif } if (copy > state.wnext) { copy -= state.wnext; from = state.wsize - copy; } else { from = state.wnext - copy; } if (copy > state.length) { copy = state.length; } from_source = state.window; } else { /* copy from output */ from_source = output; from = put - state.offset; copy = state.length; } if (copy > left) { copy = left; } left -= copy; state.length -= copy; do { output[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; } break; case LIT: if (left === 0) { break inf_leave; } output[put++] = state.length; left--; state.mode = LEN; break; case CHECK: if (state.wrap) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; // Use '|' insdead of '+' to make sure that result is signed hold |= input[next++] << bits; bits += 8; } //===// _out -= left; strm.total_out += _out; state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); } _out = left; // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too if ((state.flags ? hold : zswap32(hold)) !== state.check) { strm.msg = 'incorrect data check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: check matches trailer\n")); } state.mode = LENGTH; /* falls through */ case LENGTH: if (state.wrap && state.flags) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.total & 0xffffffff)) { strm.msg = 'incorrect length check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: length matches trailer\n")); } state.mode = DONE; /* falls through */ case DONE: ret = Z_STREAM_END; break inf_leave; case BAD: ret = Z_DATA_ERROR; break inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* falls through */ default: return Z_STREAM_ERROR; } } // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH))) { if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { state.mode = MEM; return Z_MEM_ERROR; } } _in -= strm.avail_in; _out -= strm.avail_out; strm.total_in += _in; strm.total_out += _out; state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { ret = Z_BUF_ERROR; } return ret; } function inflateEnd(strm) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { return Z_STREAM_ERROR; } var state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; } function inflateGetHeader(strm, head) { var state; /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; } exports.inflateReset = inflateReset; exports.inflateReset2 = inflateReset2; exports.inflateResetKeep = inflateResetKeep; exports.inflateInit = inflateInit; exports.inflateInit2 = inflateInit2; exports.inflate = inflate; exports.inflateEnd = inflateEnd; exports.inflateGetHeader = inflateGetHeader; exports.inflateInfo = 'pako inflate (from Nodeca project)'; /* Not implemented exports.inflateCopy = inflateCopy; exports.inflateGetDictionary = inflateGetDictionary; exports.inflateMark = inflateMark; exports.inflatePrime = inflatePrime; exports.inflateSetDictionary = inflateSetDictionary; exports.inflateSync = inflateSync; exports.inflateSyncPoint = inflateSyncPoint; exports.inflateUndermine = inflateUndermine; */ },{"../utils/common":80,"./adler32":82,"./crc32":84,"./inffast":87,"./inftrees":89}],89:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var MAXBITS = 15; var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var CODES = 0; var LENS = 1; var DISTS = 2; var lbase = [ /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ]; var lext = [ /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 ]; var dbase = [ /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 ]; var dext = [ /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64 ]; module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { var bits = opts.bits; //here = opts.here; /* table entry for duplication */ var len = 0; /* a code's length in bits */ var sym = 0; /* index of code symbols */ var min = 0, max = 0; /* minimum and maximum code lengths */ var root = 0; /* number of index bits for root table */ var curr = 0; /* number of index bits for current table */ var drop = 0; /* code bits to drop for sub-table */ var left = 0; /* number of prefix codes available */ var used = 0; /* code entries in table used */ var huff = 0; /* Huffman code */ var incr; /* for incrementing code, index */ var fill; /* index for replicating entries */ var low; /* low bits for current root entry */ var mask; /* mask for low root bits */ var next; /* next available space in table */ var base = null; /* base value table to use */ var base_index = 0; // var shoextra; /* extra bits table to use */ var end; /* use base and extra for symbol > end */ var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ var extra = null; var extra_index = 0; var here_bits, here_op, here_val; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) { count[len] = 0; } for (sym = 0; sym < codes; sym++) { count[lens[lens_index + sym]]++; } /* bound code lengths, force root to be within code lengths */ root = bits; for (max = MAXBITS; max >= 1; max--) { if (count[max] !== 0) { break; } } if (root > max) { root = max; } if (max === 0) { /* no symbols to code at all */ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ //table.bits[opts.table_index] = 1; //here.bits = (var char)1; //table.val[opts.table_index++] = 0; //here.val = (var short)0; table[table_index++] = (1 << 24) | (64 << 16) | 0; //table.op[opts.table_index] = 64; //table.bits[opts.table_index] = 1; //table.val[opts.table_index++] = 0; table[table_index++] = (1 << 24) | (64 << 16) | 0; opts.bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) { if (count[min] !== 0) { break; } } if (root < min) { root = min; } /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) { return -1; } /* over-subscribed */ } if (left > 0 && (type === CODES || max !== 1)) { return -1; /* incomplete set */ } /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + count[len]; } /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) { if (lens[lens_index + sym] !== 0) { work[offs[lens[lens_index + sym]]++] = sym; } } /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ // poor man optimization - use if-else instead of switch, // to avoid deopts in old v8 if (type === CODES) { base = extra = work; /* dummy value--not used */ end = 19; } else if (type === LENS) { base = lbase; base_index -= 257; extra = lext; extra_index -= 257; end = 256; } else { /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize opts for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = table_index; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = -1; /* trigger new sub-table when len > root */ used = 1 << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } var i = 0; /* process all codes and make table entries */ for (;;) { i++; /* create table entry */ here_bits = len - drop; if (work[sym] < end) { here_op = 0; here_val = work[sym]; } else if (work[sym] > end) { here_op = extra[extra_index + work[sym]]; here_val = base[base_index + work[sym]]; } else { here_op = 32 + 64; /* end of block */ here_val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1 << (len - drop); fill = 1 << curr; min = fill; /* save offset to next table */ do { fill -= incr; table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; } while (fill !== 0); /* backwards increment the len-bit code huff */ incr = 1 << (len - 1); while (huff & incr) { incr >>= 1; } if (incr !== 0) { huff &= incr - 1; huff += incr; } else { huff = 0; } /* go to next symbol, update count, len */ sym++; if (--count[len] === 0) { if (len === max) { break; } len = lens[lens_index + work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) !== low) { /* if first time, transition to sub-tables */ if (drop === 0) { drop = root; } /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = 1 << curr; while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) { break; } curr++; left <<= 1; } /* check for enough space */ used += 1 << curr; if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* point entry in root table to sub-table */ low = huff & mask; /*table.op[low] = curr; table.bits[low] = root; table.val[low] = next - opts.table_index;*/ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff !== 0) { //table.op[next + huff] = 64; /* invalid code marker */ //table.bits[next + huff] = len - drop; //table.val[next + huff] = 0; table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; } /* set return parameters */ //opts.table_index += used; opts.bits = root; return 0; }; },{"../utils/common":80}],90:[function(_dereq_,module,exports){ 'use strict'; module.exports = { 2: 'need dictionary', /* Z_NEED_DICT 2 */ 1: 'stream end', /* Z_STREAM_END 1 */ 0: '', /* Z_OK 0 */ '-1': 'file error', /* Z_ERRNO (-1) */ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ '-3': 'data error', /* Z_DATA_ERROR (-3) */ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; },{}],91:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); /* Public constants ==========================================================*/ /* ===========================================================================*/ //var Z_FILTERED = 1; //var Z_HUFFMAN_ONLY = 2; //var Z_RLE = 3; var Z_FIXED = 4; //var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ var Z_BINARY = 0; var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /*============================================================================*/ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } // From zutil.h var STORED_BLOCK = 0; var STATIC_TREES = 1; var DYN_TREES = 2; /* The three kinds of block type */ var MIN_MATCH = 3; var MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h /* =========================================================================== * Internal compression state. */ var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2 * L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var Buf_size = 16; /* size of bit buffer in bi_buf */ /* =========================================================================== * Constants */ var MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ var END_BLOCK = 256; /* end of block literal code */ var REP_3_6 = 16; /* repeat previous bit length 3-6 times (2 bits of repeat count) */ var REPZ_3_10 = 17; /* repeat a zero length 3-10 times (3 bits of repeat count) */ var REPZ_11_138 = 18; /* repeat a zero length 11-138 times (7 bits of repeat count) */ /* eslint-disable comma-spacing,array-bracket-spacing */ var extra_lbits = /* extra bits for each length code */ [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; var extra_dbits = /* extra bits for each distance code */ [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; var extra_blbits = /* extra bits for each bit length code */ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; var bl_order = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; /* eslint-enable comma-spacing,array-bracket-spacing */ /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ // We pre-fill arrays with 0 to avoid uninitialized gaps var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 var static_ltree = new Array((L_CODES + 2) * 2); zero(static_ltree); /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ var static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ var _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); zero(_length_code); /* length code for each normalized match length (0 == MIN_MATCH) */ var base_length = new Array(LENGTH_CODES); zero(base_length); /* First normalized length for each code (0 = MIN_MATCH) */ var base_dist = new Array(D_CODES); zero(base_dist); /* First normalized distance for each code (0 = distance of 1) */ function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { this.static_tree = static_tree; /* static tree or NULL */ this.extra_bits = extra_bits; /* extra bits for each code or NULL */ this.extra_base = extra_base; /* base index for extra_bits */ this.elems = elems; /* max number of elements in the tree */ this.max_length = max_length; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects this.has_stree = static_tree && static_tree.length; } var static_l_desc; var static_d_desc; var static_bl_desc; function TreeDesc(dyn_tree, stat_desc) { this.dyn_tree = dyn_tree; /* the dynamic tree */ this.max_code = 0; /* largest code with non zero frequency */ this.stat_desc = stat_desc; /* the corresponding static tree */ } function d_code(dist) { return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; } /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ function put_short(s, w) { // put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += length; } } function send_code(s, c, tree) { send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ function bi_reverse(code, len) { var res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ function bi_flush(s) { if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; s.bi_valid = 0; } else if (s.bi_valid >= 8) { s.pending_buf[s.pending++] = s.bi_buf & 0xff; s.bi_buf >>= 8; s.bi_valid -= 8; } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ function gen_bitlen(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var max_code = desc.max_code; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var extra = desc.stat_desc.extra_bits; var base = desc.stat_desc.extra_base; var max_length = desc.stat_desc.max_length; var h; /* heap index */ var n, m; /* iterate over the tree elements */ var bits; /* bit length */ var xbits; /* extra bits */ var f; /* frequency */ var overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; } /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n * 2 + 1]/*.Len*/ = bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) { continue; } /* not a leaf node */ s.bl_count[bits]++; xbits = 0; if (n >= base) { xbits = extra[n - base]; } f = tree[n * 2]/*.Freq*/; s.opt_len += f * (bits + xbits); if (has_stree) { s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); } } if (overflow === 0) { return; } // Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length - 1; while (s.bl_count[bits] === 0) { bits--; } s.bl_count[bits]--; /* move one leaf down the tree */ s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ s.bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > max_code) { continue; } if (tree[m * 2 + 1]/*.Len*/ !== bits) { // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; tree[m * 2 + 1]/*.Len*/ = bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */ // int max_code; /* largest code with non zero frequency */ // ushf *bl_count; /* number of codes at each bit length */ { var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ var code = 0; /* running code value */ var bits; /* bit index */ var n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits - 1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { var len = tree[n * 2 + 1]/*.Len*/; if (len === 0) { continue; } /* Now reverse the bits */ tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len); //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Initialize the various 'constant' tables. */ function tr_static_init() { var n; /* iterates over tree elements */ var bits; /* bit counter */ var length; /* length value */ var code; /* code value */ var dist; /* distance index */ var bl_count = new Array(MAX_BITS + 1); /* number of codes at each bit length for an optimal tree */ // do check in _tr_init() //if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ /*#ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif*/ /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES - 1; code++) { base_length[code] = length; for (n = 0; n < (1 << extra_lbits[code]); n++) { _length_code[length++] = code; } } //Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length - 1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1 << extra_dbits[code]); n++) { _dist_code[dist++] = code; } } //Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for (; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { _dist_code[256 + dist++] = code; } } //Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } n = 0; while (n <= 143) { static_ltree[n * 2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } while (n <= 255) { static_ltree[n * 2 + 1]/*.Len*/ = 9; n++; bl_count[9]++; } while (n <= 279) { static_ltree[n * 2 + 1]/*.Len*/ = 7; n++; bl_count[7]++; } while (n <= 287) { static_ltree[n * 2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes(static_ltree, L_CODES + 1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n * 2 + 1]/*.Len*/ = 5; static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); } // Now data ready and we can init static trees static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); //static_init_done = true; } /* =========================================================================== * Initialize a new block. */ function init_block(s) { var n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; s.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ function bi_windup(s) { if (s.bi_valid > 8) { put_short(s, s.bi_buf); } else if (s.bi_valid > 0) { //put_byte(s, (Byte)s->bi_buf); s.pending_buf[s.pending++] = s.bi_buf; } s.bi_buf = 0; s.bi_valid = 0; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ function copy_block(s, buf, len, header) //DeflateState *s; //charf *buf; /* the input data */ //unsigned len; /* its length */ //int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ if (header) { put_short(s, len); put_short(s, ~len); } // while (len--) { // put_byte(s, *buf++); // } utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); s.pending += len; } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ function smaller(tree, n, m, depth) { var _n2 = n * 2; var _m2 = m * 2; return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); } /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ function pqdownheap(s, tree, k) // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { var v = s.heap[k]; var j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s.heap[j], s.depth)) { break; } /* Exchange v with the smallest son */ s.heap[k] = s.heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s.heap[k] = v; } // inlined manually // var SMALLEST = 1; /* =========================================================================== * Send the block data compressed using the given Huffman trees */ function compress_block(s, ltree, dtree) // deflate_state *s; // const ct_data *ltree; /* literal tree */ // const ct_data *dtree; /* distance tree */ { var dist; /* distance of matched string */ var lc; /* match length or unmatched char (if dist == 0) */ var lx = 0; /* running index in l_buf */ var code; /* the code to send */ var extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); lc = s.pending_buf[s.l_buf + lx]; lx++; if (dist === 0) { send_code(s, lc, ltree); /* send a literal byte */ //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code + LITERALS + 1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra !== 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); //Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra !== 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, // "pendingBuf overflow"); } while (lx < s.last_lit); } send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ function build_tree(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var elems = desc.stat_desc.elems; var n, m; /* iterate over heap elements */ var max_code = -1; /* largest code with non zero frequency */ var node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2]/*.Freq*/ !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n * 2 + 1]/*.Len*/ = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2]/*.Freq*/ = 1; s.depth[node] = 0; s.opt_len--; if (has_stree) { s.static_len -= stree[node * 2 + 1]/*.Len*/; } /* node is 0 or 1 so it does not have extra bits */ } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { //pqremove(s, tree, n); /* n = node of least frequency */ /*** pqremove ***/ n = s.heap[1/*SMALLEST*/]; s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; pqdownheap(s, tree, 1/*SMALLEST*/); /***/ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ s.heap[--s.heap_max] = m; /* Create a new node father of n and m */ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; /* and insert the new node in the heap */ s.heap[1/*SMALLEST*/] = node++; pqdownheap(s, tree, 1/*SMALLEST*/); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, desc); /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ function scan_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { s.bl_tree[curlen * 2]/*.Freq*/ += count; } else if (curlen !== 0) { if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } s.bl_tree[REP_3_6 * 2]/*.Freq*/++; } else if (count <= 10) { s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; } else { s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ function send_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen !== prevlen) { send_code(s, curlen, s.bl_tree); count--; } //Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s.bl_tree); send_bits(s, count - 3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s.bl_tree); send_bits(s, count - 3, 3); } else { send_code(s, REPZ_11_138, s.bl_tree); send_bits(s, count - 11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ function build_bl_tree(s) { var max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_dtree, s.d_desc.max_code); /* Build the bit length tree: */ build_tree(s, s.bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { break; } } /* Update opt_len to include the bit length tree and counts */ s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ function send_all_trees(s, lcodes, dcodes, blcodes) // deflate_state *s; // int lcodes, dcodes, blcodes; /* number of codes for each tree */ { var rank; /* index in bl_order */ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); //Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes - 1, 5); send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); } //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ function detect_data_type(s) { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ var black_mask = 0xf3ffc07f; var n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>>= 1) { if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { return Z_BINARY; } } /* Check for textual ("white-listed") bytes. */ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { return Z_TEXT; } for (n = 32; n < LITERALS; n++) { if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { return Z_TEXT; } } /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } var static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ function _tr_init(s) { if (!static_init_done) { tr_static_init(); static_init_done = true; } s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); s.bi_buf = 0; s.bi_valid = 0; /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Send a stored block */ function _tr_stored_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ copy_block(s, buf, stored_len, true); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ function _tr_align(s) { send_bits(s, STATIC_TREES << 1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ function _tr_flush_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block, or NULL if too old */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ var max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s.level > 0) { /* Check if the file is binary or text */ if (s.strm.data_type === Z_UNKNOWN) { s.strm.data_type = detect_data_type(s); } /* Construct the literal and distance trees */ build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s.opt_len + 3 + 7) >>> 3; static_lenb = (s.static_len + 3 + 7) >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, // s->last_lit)); if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } } else { // Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { /* 4: two words for the lengths */ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); compress_block(s, static_ltree, static_dtree); } else { send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); compress_block(s, s.dyn_ltree, s.dyn_dtree); } // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); } // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ function _tr_tally(s, dist, lc) // deflate_state *s; // unsigned dist; /* distance of matched string */ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { //var out_length, in_length, dcode; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; s.last_lit++; if (dist === 0) { /* lc is the unmatched char */ s.dyn_ltree[lc * 2]/*.Freq*/++; } else { s.matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ //Assert((ush)dist < (ush)MAX_DIST(s) && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef TRUNCATE_BLOCK // /* Try to guess if it is profitable to stop the current block here */ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { // /* Compute an upper bound for the compressed length */ // out_length = s.last_lit*8; // in_length = s.strstart - s.block_start; // // for (dcode = 0; dcode < D_CODES; dcode++) { // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); // } // out_length >>>= 3; // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", // // s->last_lit, in_length, out_length, // // 100L - out_length*100L/in_length)); // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { // return true; // } // } //#endif return (s.last_lit === s.lit_bufsize - 1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } exports._tr_init = _tr_init; exports._tr_stored_block = _tr_stored_block; exports._tr_flush_block = _tr_flush_block; exports._tr_tally = _tr_tally; exports._tr_align = _tr_align; },{"../utils/common":80}],92:[function(_dereq_,module,exports){ 'use strict'; function ZStream() { /* next input byte */ this.input = null; // JS specific, because we have no pointers this.next_in = 0; /* number of bytes available at input */ this.avail_in = 0; /* total number of input bytes read so far */ this.total_in = 0; /* next output byte should be put there */ this.output = null; // JS specific, because we have no pointers this.next_out = 0; /* remaining free space at output */ this.avail_out = 0; /* total number of bytes output so far */ this.total_out = 0; /* last error message, NULL if no error */ this.msg = ''/*Z_NULL*/; /* not visible by applications */ this.state = null; /* best guess about the data type: binary or text */ this.data_type = 2/*Z_UNKNOWN*/; /* adler32 value of the uncompressed data */ this.adler = 0; } module.exports = ZStream; },{}],93:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}]},{},[1]);
sreym/cdnjs
ajax/libs/forerunnerdb/1.3.755/fdb-legacy.js
JavaScript
mit
996,596
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var helpers = require('./helpers'); /** * Block's constructor */ var Block = function(block) { var name = block.data('b'); var params = block.data('p'); var decl = helpers.decls[name]; if (!decl) { throw new Error(name + ' block is not declared'); } var info = { name: name, params: params, $node: block, _id: helpers.guid() }; $.extend(this, info, decl.methods); this._addEvents(); this._setInited(); this.$node.trigger('b-inited'); }; /** * Adds handler for block's event * @param {string} name * @param {function} callback */ Block.prototype.on = function(name, callback) { this.$node.on(this._getEventName(name), callback); return this; }; /** * Removes handler for block's event * @param {string} name * @param {function} callback */ Block.prototype.off = function(name, callback) { var event = this._getEventName(name); if (!name) { this.$node.off(); } else if (!callback) { this.$node.off(event); } else { this.$node.off(event, callback); } return this; }; /** * Adds events to block's node according its decl */ Block.prototype._addEvents = function() { var decl = helpers.decls[this.name]; var events = decl.events; for (var e in events) { if (events.hasOwnProperty(e)) { var p = e.split(' ', 2); var handler = events[e]; if (typeof handler === 'string') { handler = decl.methods[handler]; } this.$node.on(p[0], p[1], handler.bind(this)); } } }; /** * Mark the block as inited */ Block.prototype._setInited = function() { this.$node.addClass('jb-inited'); }; /** * Triggers specified event * @param {string} name */ Block.prototype.emit = function(name) { this.$node.trigger(this._getEventName(name)); return this; }; /** * Removes block from cache and triggers b-destroy event */ Block.prototype.destroy = function() { helpers.cache[this._id] = null; this.$node.removeClass('jb-inited'); this.off(); this.$node.trigger('b-destroyed'); }; /** * Возвращает имя события с учетом пространства имен * @param {string} name * @return {string} */ Block.prototype._getEventName = function(name) { return this.id + ':' + name; }; module.exports = Block; },{"./helpers":3}],2:[function(require,module,exports){ var helpers = require('./helpers'); var Block = require('./Block'); var methods = { /** * Init all blocks inside */ 'init': function () { return this.find('[data-b]').jblocks('get'); }, /** * Destroy all blocks */ 'destroy': function () { this.find('[data-b]').jblocks('get').each(function () { this.destroy(); }); }, /** * Returns block from cache or create it if doesn't exist * @return {jQuery} */ 'get': function () { return this.map(function () { var $b = $(this); var bid = $b.data('_bid'); if (bid) { return helpers.cache[bid]; } var block = new Block($b); bid = block._id; $b.data('_bid', bid); helpers.cache[bid] = block; return block; }); }, /** * Returns blocks inside * @return {jQuery} */ 'find': function(filter) { var selector = '[data-b]'; if (filter) { selector = '[data-b="' + filter + '"]'; } return this.find(selector).map(function() { return $(this).jblocks('get')[0]; }); } }; $.fn.jblocks = function (method) { if (method in methods) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else { throw new Error('Can`t find method ' + method); } }; /** * Block's declaration * @param {Object} proto */ $.jblocks = function (proto) { if (!('name' in proto)) { throw new Error('Need to define block`s name'); } if (helpers.decls[proto.name]) { throw new Error('Can`t redefine ' + proto.name + ' block'); } helpers.decls[proto.name] = proto; }; // to get Block from global outspace $.Block = Block; },{"./Block":1,"./helpers":3}],3:[function(require,module,exports){ var id = 0; exports.cache = {}; exports.decls = {}; /** * Returns unique id */ exports.guid = function() { return 'b-' + id++; }; },{}]},{},[2])
BenjaminVanRyseghem/cdnjs
ajax/libs/jblocks/0.3.2/jblocks.js
JavaScript
mit
5,010
/** * @fileoverview Interface for database connector. */ goog.provide('ydn.db.con.IDatabase'); goog.require('goog.async.Deferred'); /** * @interface */ ydn.db.con.IDatabase = function() {}; /** * Close the connection. */ ydn.db.con.IDatabase.prototype.close = function() {}; /** * Return readable representation of storage mechanism. It should be all lower * case and use in type checking. * @return {string} connected database type. */ ydn.db.con.IDatabase.prototype.getType = function() {}; /** * @return {boolean} ready status. */ ydn.db.con.IDatabase.prototype.isReady = function() {}; /** * @param {string} name database name. * @param {!ydn.db.schema.Database} schema database schema. * @return {!goog.async.Deferred} promise on connected. */ ydn.db.con.IDatabase.prototype.connect = function(name, schema) {}; /** * @return {number|undefined} return current version; */ ydn.db.con.IDatabase.prototype.getVersion = goog.abstractMethod; /** * @return {*} underlying database. */ ydn.db.con.IDatabase.prototype.getDbInstance = function() {}; /** * Perform transaction immediately and invoke transaction_callback with * the transaction object. * Database adaptor must invoke completed_event_handler * when the data is transaction completed. * Caller must not invoke this method until transaction completed event is * fired. * @param {function(ydn.db.base.Transaction)} * transaction_callback callback function that invoke in the transaction with * transaction instance. * @param {Array.<string>} store_names list of store names involved in the * transaction. * @param {ydn.db.base.TransactionMode} mode mode, default to 'read_write'. * @param {function(ydn.db.base.TxEventTypes, *)} * completed_event_handler handler for on completed event. */ ydn.db.con.IDatabase.prototype.doTransaction = goog.abstractMethod; /** * * @param {function(ydn.db.schema.Database)} callback database schema obtained * by reflecting connected database. * @param {(SQLTransaction|IDBTransaction|Object)=} trans transaction to reuse. * @param {(IDBDatabase|Database)=} db database to reuse. */ ydn.db.con.IDatabase.prototype.getSchema = goog.abstractMethod; /** * On terminal failure. * @type {Function} */ ydn.db.con.IDatabase.prototype.onFail = goog.abstractMethod; /** * On terminal failure. * @type {Function} */ ydn.db.con.IDatabase.prototype.onError = goog.abstractMethod; /** * On terminal failure. * @type {Function} */ ydn.db.con.IDatabase.prototype.onVersionChange = goog.abstractMethod;
jayteemi/educatoursja
www2/lib/ydn.db/src/ydn/db/conn/i_database.js
JavaScript
apache-2.0
2,558
describe("Select Plugin", function () { beforeEach(function() { loadFixtures('select/selectFixture.html'); $('select').not('.disabled').material_select(); }); describe("Select", function () { var browserSelect, normalInput, normalDropdown; beforeEach(function() { browserSelect = $('select.normal'); }); it("should open dropdown and select option", function (done) { normalInput = browserSelect.parent().find('input.select-dropdown'); normalDropdown = browserSelect.parent().find('ul.select-dropdown'); expect(normalInput).toExist('Should dynamically generate select dropdown structure.'); expect(normalDropdown).toExist('Should dynamically generate select dropdown structure.'); expect(normalInput).toBeVisible('Should be hidden before dropdown is opened.'); expect(normalDropdown).toBeHidden('Should be hidden before dropdown is opened.'); normalInput.click(); setTimeout(function() { expect(normalDropdown).toBeVisible('Should be visible after opening.'); var firstOption = normalDropdown.find('li:not(.disabled)').first(); firstOption.click(); normalInput.blur(); setTimeout(function() { expect(normalDropdown).toBeHidden('Should be hidden after choosing item.'); expect(normalInput.val()).toEqual(firstOption[0].innerText, 'Value should equal chosen option.'); done(); }, 400); }, 400); }); it("should have pre-selected value", function () { normalInput = browserSelect.parent().find('input.select-dropdown'); normalDropdown = browserSelect.parent().find('ul.select-dropdown'); var firstOption = browserSelect.find('option[selected]'); expect(normalInput.val()).toEqual(firstOption.text(), 'Value should be equal to preselected option.'); }); }); describe("Multiple Select", function () { var browserSelect, multipleInput, multipleDropdown; beforeEach(function() { browserSelect = $('select.multiple'); }); it("should open dropdown and select multiple options", function(done) { multipleInput = browserSelect.parent().find('input.select-dropdown'); multipleDropdown = browserSelect.parent().find('ul.select-dropdown'); expect(multipleInput).toExist('Should dynamically generate select dropdown structure.'); expect(multipleDropdown).toExist('Should dynamically generate select dropdown structure.'); expect(multipleInput).toBeVisible('Should be hidden before dropdown is opened.'); expect(multipleDropdown).toBeHidden('Should be hidden before dropdown is opened.'); multipleInput.click(); setTimeout(function() { expect(multipleDropdown).toBeVisible('Should be visible after opening.'); var firstOption = multipleDropdown.find('li:not(.disabled)').first(); var secondOption = multipleDropdown.find('li:not(.disabled)').eq(1); var thirdOption = multipleDropdown.find('li:not(.disabled)').eq(2); firstOption.click(); $('body').click(); setTimeout(function() { expect(multipleDropdown).toBeHidden('Should be hidden after choosing item.'); expect(browserSelect.val()).toEqual(['1', '2', '3'], 'Actual select should have correct selected values.'); expect(multipleInput.val()).toEqual(secondOption[0].innerText + ', ' + thirdOption[0].innerText + ', ' + firstOption[0].innerText, 'Value should equal chosen multiple options.'); done(); }, 400); }, 400); }); it("should open dropdown and deselect multiple options", function(done) { multipleInput = browserSelect.parent().find('input.select-dropdown'); multipleDropdown = browserSelect.parent().find('ul.select-dropdown'); expect(multipleInput).toExist('Should dynamically generate select dropdown structure.'); expect(multipleDropdown).toExist('Should dynamically generate select dropdown structure.'); expect(multipleInput).toBeVisible('Should be hidden before dropdown is opened.'); expect(multipleDropdown).toBeHidden('Should be hidden before dropdown is opened.'); multipleInput.click(); setTimeout(function() { expect(multipleDropdown).toBeVisible('Should be visible after opening.'); var disabledOption = multipleDropdown.find('li.disabled'); var secondOption = multipleDropdown.find('li:not(.disabled)').eq(1); var thirdOption = multipleDropdown.find('li:not(.disabled)').eq(2); secondOption.click(); thirdOption.click(); $('body').click(); setTimeout(function() { expect(multipleDropdown).toBeHidden('Should be hidden after choosing item.'); expect(browserSelect.val()).toEqual(null, 'Actual select element should be empty because none chosen.'); expect(multipleInput.val()).toEqual(disabledOption[0].innerText, 'Value should equal default because none chosen.'); done(); }, 400); }, 400); }); it("should have multiple pre-selected values", function () { multipleInput = browserSelect.parent().find('input.select-dropdown'); multipleDropdown = browserSelect.parent().find('ul.select-dropdown'); var secondOption = browserSelect.find('option[selected]').eq(0); var thirdOption = browserSelect.find('option[selected]').eq(1); expect(multipleInput.val()).toEqual(secondOption.text() + ', ' + thirdOption.text(), 'Value should be equal to preselected option.'); }); }); describe("Optgroup Select", function () { var browserSelect, optInput, optDropdown; beforeEach(function() { browserSelect = $('select.optgroup'); }); it("should open dropdown and select options", function(done) { optInput = browserSelect.parent().find('input.select-dropdown'); optDropdown = browserSelect.parent().find('ul.select-dropdown'); var optgroups = optDropdown.find('li.optgroup'); browserSelect.find('optgroup').each(function(i) { expect($(this).attr('label')).toEqual(optgroups.eq(i)[0].innerText, 'should generate optgroup structure.'); }); expect(optInput).toExist('Should dynamically generate select dropdown structure.'); expect(optDropdown).toExist('Should dynamically generate select dropdown structure.'); expect(optInput).toBeVisible('Should be hidden before dropdown is opened.'); expect(optDropdown).toBeHidden('Should be hidden before dropdown is opened.'); optInput.click(); setTimeout(function() { expect(optDropdown).toBeVisible('Should be visible after opening.'); var secondOption = optDropdown.find('li:not(.disabled):not(.optgroup)').eq(1); secondOption.click(); optInput.blur(); setTimeout(function() { expect(optDropdown).toBeHidden('Should be hidden after choosing item.'); expect(optInput.val()).toEqual(secondOption[0].innerText, 'Value should be equal to selected option.'); done(); }, 400); }, 400); }); it("should not do anything when optgroup li clicked", function(done) { optInput = browserSelect.parent().find('input.select-dropdown'); optDropdown = browserSelect.parent().find('ul.select-dropdown'); var originalVal = optInput.val(); var optgroups = optDropdown.find('li.optgroup'); browserSelect.find('optgroup').each(function(i) { expect($(this).attr('label')).toEqual(optgroups.eq(i)[0].innerText, 'should generate optgroup structure.'); }); expect(optInput).toExist('Should dynamically generate select dropdown structure.'); expect(optDropdown).toExist('Should dynamically generate select dropdown structure.'); expect(optInput).toBeVisible('Should be hidden before dropdown is opened.'); expect(optDropdown).toBeHidden('Should be hidden before dropdown is opened.'); optInput.click(); setTimeout(function() { expect(optDropdown).toBeVisible('Should be visible after opening.'); var optgroup = optDropdown.find('li.optgroup').first(); optgroup.click(); optInput.blur(); setTimeout(function() { expect(optDropdown).toBeHidden('Should be hidden after choosing invalid item.'); expect(optInput.val()).toEqual(originalVal, 'Value should be equal to original option.'); done(); }, 400); }, 400); }); }); });
Taraszion/AngularSymfonyGl
web/bower_components/Materialize/tests/spec/select/selectSpec.js
JavaScript
mit
8,477
/** * @file * A simple jQuery ThumbnailHover Div Slideshow Rotator. */ (function ($) { /** * This will set our initial behavior, by starting up each individual slideshow. */ Drupal.behaviors.viewsSlideshowThumbnailHover = function (context) { $('.views_slideshow_thumbnailhover_main:not(.viewsSlideshowThumbnailHover-processed)', context).addClass('viewsSlideshowThumbnailHover-processed').each(function() { var fullId = '#' + $(this).attr('id'); if (!Drupal.settings.viewsSlideshowThumbnailHover || !Drupal.settings.viewsSlideshowThumbnailHover[fullId]) { return; } var settings = Drupal.settings.viewsSlideshowThumbnailHover[fullId]; settings.targetId = '#' + $(fullId + " :first").attr('id'); settings.paused = false; settings.opts = { speed:settings.speed, timeout:parseInt(settings.timeout), delay:parseInt(settings.delay), sync:settings.sync==1, random:settings.random==1, pause:false, allowPagerClickBubble:(settings.pager_event=='click')? false : true, pager:(settings.pager_event == 'hoverIntent') ? null : '#views_slideshow_breakout_teasers_' + settings.vss_id, nowrap:parseInt(settings.nowrap), pagerAnchorBuilder:(settings.pager_event == 'hoverIntent') ? null : function(idx, slide) { return '#views_slideshow_thumbnailhover_div_breakout_teaser_' + settings.vss_id + '_' + idx; }, after:function(curr, next, opts) { // Used for Image Counter. if (settings.image_count) { $('#views_slideshow_thumbnailhover_image_count_' + settings.vss_id + ' span.num').html(opts.currSlide + 1); $('#views_slideshow_thumbnailhover_image_count_' + settings.vss_id + ' span.total').html(opts.slideCount); } }, before:function(current, next, opts) { // Remember last slide. if (settings.remember_slide) { createCookie(settings.view_id, opts.currSlide + 1, settings.remember_slide_days); } // Make variable height. if (settings.fixed_height == 0) { //get the height of the current slide var $ht = $(this).height(); //set the container's height to that of the current slide $(this).parent().animate({height: $ht}); } var currId = (currId=$(current).attr('id')).substring(currId.lastIndexOf('_')+1) var nextId = (nextId=$(next).attr('id')).substring(nextId.lastIndexOf('_')+1) $('#views_slideshow_thumbnailhover_div_breakout_teaser_' + settings.vss_id + '_' + currId).removeClass('activeSlide'); $('#views_slideshow_thumbnailhover_div_breakout_teaser_' + settings.vss_id + '_' + nextId).addClass('activeSlide'); }, pagerEvent: (settings.pager_event == 'hoverIntent') ? null : settings.pager_event, prev:(settings.controls > 0)?'#views_slideshow_thumbnailhover_prev_' + settings.vss_id:null, next:(settings.controls > 0)?'#views_slideshow_thumbnailhover_next_' + settings.vss_id:null, cleartype:(settings.ie.cleartype == 'true')? true : false, cleartypeNoBg:(settings.ie.cleartypenobg == 'true')? true : false }; // Set the starting slide if we are supposed to remember the slide if (settings.remember_slide) { var startSlide = readCookie(settings.view_id); if (startSlide == null) { startSlide = 0; } settings.opts.startingSlide = startSlide; } if (settings.effect == 'none') { settings.opts.speed = 1; } else { settings.opts.fx = settings.effect; } // Pause on hover. if (settings.pause == 1) { $('#views_slideshow_thumbnailhover_teaser_section_' + settings.vss_id).hover(function() { $(settings.targetId).cycle('pause'); }, function() { if (settings.paused == false) { $(settings.targetId).cycle('resume'); } }); } // Pause on clicking of the slide. if (settings.pause_on_click == 1) { $('#views_slideshow_thumbnailhover_teaser_section_' + settings.vss_id).click(function() { viewsSlideshowThumbnailHoverPause(settings); }); } // Add additional settings. if (settings.advanced && settings.advanced != "\n") { settings.advanced = settings.advanced.toString(); var advanced = settings.advanced.split("\n"); for (i=0; i<advanced.length; i++) { var prop = ''; var value = ''; var property = advanced[i].split(":"); for (j=0; j<property.length; j++) { if (j == 0) { prop = property[j]; } else if (j == 1) { value = property[j]; } else { value += ":" + property[j]; } } // Need to evaluate so true, false and numerics aren't a string. if (value == 'true' || value == 'false' || IsNumeric(value)) { value = eval(value); } else { // Parse strings into functions. var func = value.match(/function\s*\((.*?)\)\s*\{(.*)\}/i); if (func) { value = new Function(func[1].match(/(\w+)/g), func[2]); } } // Call both functions if prop was set previously. if (typeof(value) == "function" && prop in settings.opts) { var callboth = function(before_func, new_func) { return function() { before_func.apply(null, arguments); new_func.apply(null, arguments); }; }; settings.opts[prop] = callboth(settings.opts[prop], value); } else { settings.opts[prop] = value; } } } $(settings.targetId).cycle(settings.opts); // Start Paused if (settings.start_paused) { viewsSlideshowThumbnailHoverPause(settings); } // Pause if hidden. if (settings.pause_when_hidden) { var checkPause = function(settings) { // If the slideshow is visible and it is paused then resume. // otherwise if the slideshow is not visible and it is not paused then // pause it. var visible = viewsSlideshowThumbnailHoverIsVisible(settings.targetId, settings.pause_when_hidden_type, settings.amount_allowed_visible); if (visible && settings.paused) { viewsSlideshowThumbnailHoverResume(settings); } else if (!visible && !settings.paused) { viewsSlideshowThumbnailHoverPause(settings); } } // Check when scrolled. $(window).scroll(function() { checkPause(settings); }); // Check when window is resized. $(window).resize(function() { checkPause(settings); }); } // Show image count for people who have js enabled. $('#views_slideshow_thumbnailhover_image_count_' + settings.vss_id).show(); if (settings.pager_event == 'hoverIntent') { $('#views_slideshow_thumbnailhover_breakout_teasers_' + settings.vss_id + ' .views_slideshow_thumbnailhover_div_breakout_teaser').each(function(i,obj) { $(obj).hoverIntent( function() { $('.views_slideshow_thumbnailhover_div_breakout_teaser').removeClass('activeSlide'); var id = $(this).attr('id'); id = parseInt(id.substring(id.lastIndexOf('_')+1)); $(settings.targetId).cycle(id); $('#views_slideshow_thumbnailhover_div_breakout_teaser_' + settings.vss_id + '_' + id).addClass('activeSlide'); $(settings.targetId).cycle('stop'); }, function() { var id = $(this).attr('id'); settings.opts.startingSlide = parseInt(id.substring(id.lastIndexOf('_')+1)); $(settings.targetId).cycle(settings.opts); } ); }); } if (settings.controls > 0) { // Show controls for people who have js enabled browsers. $('#views_slideshow_thumbnailhover_controls_' + settings.vss_id).show(); $('#views_slideshow_thumbnailhover_playpause_' + settings.vss_id).click(function(e) { if (settings.paused) { viewsSlideshowThumbnailHoverResume(settings); } else { viewsSlideshowThumbnailHoverPause(settings); } e.preventDefault(); }); } }); } // Pause the slideshow viewsSlideshowThumbnailHoverPause = function (settings) { //make Resume translatable var resume = Drupal.t('Resume'); $(settings.targetId).cycle('pause'); if (settings.controls > 0) { $('#views_slideshow_thumbnailhover_playpause_' + settings.vss_id) .addClass('views_slideshow_thumbnailhover_play') .addClass('views_slideshow_play') .removeClass('views_slideshow_thumbnailhover_pause') .removeClass('views_slideshow_pause') .text(resume); } settings.paused = true; } // Resume the slideshow viewsSlideshowThumbnailHoverResume = function (settings) { // Make Pause translatable var pause = Drupal.t('Pause'); $(settings.targetId).cycle('resume'); if (settings.controls > 0) { $('#views_slideshow_thumbnailhover_playpause_' + settings.vss_id) .addClass('views_slideshow_thumbnailhover_pause') .addClass('views_slideshow_pause') .removeClass('views_slideshow_thumbnailhover_play') .removeClass('views_slideshow_play') .text(pause); } settings.paused = false; } // Verify that the value is a number. function IsNumeric(sText) { var ValidChars = "0123456789"; var IsNumber=true; var Char; for (var i=0; i < sText.length && IsNumber == true; i++) { Char = sText.charAt(i); if (ValidChars.indexOf(Char) == -1) { IsNumber = false; } } return IsNumber; } /** * Cookie Handling Functions */ function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else { var expires = ""; } document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length,c.length); } } return null; } function eraseCookie(name) { createCookie(name,"",-1); } /** * Checks to see if the slide is visible enough. * elem = element to check. * amountVisible = amount that should be visible. Either in percent or px. If * it's not defined then all of the slide must be visible. * * Returns true or false */ function viewsSlideshowThumbnailHoverIsVisible(elem, type, amountVisible) { // Get the top and bottom of the window; var docViewTop = $(window).scrollTop(); var docViewBottom = docViewTop + $(window).height(); var docViewLeft = $(window).scrollLeft(); var docViewRight = docViewLeft + $(window).width(); // Get the top, bottom, and height of the slide; var elemTop = $(elem).offset().top; var elemHeight = $(elem).height(); var elemBottom = elemTop + elemHeight; var elemLeft = $(elem).offset().left; var elemWidth = $(elem).width(); var elemRight = elemLeft + elemWidth; var elemArea = elemHeight * elemWidth; // Calculate what's hiding in the slide. var missingLeft = 0; var missingRight = 0; var missingTop = 0; var missingBottom = 0; // Find out how much of the slide is missing from the left. if (elemLeft < docViewLeft) { missingLeft = docViewLeft - elemLeft; } // Find out how much of the slide is missing from the right. if (elemRight > docViewRight) { missingRight = elemRight - docViewRight; } // Find out how much of the slide is missing from the top. if (elemTop < docViewTop) { missingTop = docViewTop - elemTop; } // Find out how much of the slide is missing from the bottom. if (elemBottom > docViewBottom) { missingBottom = elemBottom - docViewBottom; } // If there is no amountVisible defined then check to see if the whole slide // is visible. if (type == 'full') { return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom) && (elemBottom <= docViewBottom) && (elemTop >= docViewTop) && (elemLeft >= docViewLeft) && (elemRight <= docViewRight) && (elemLeft <= docViewRight) && (elemRight >= docViewLeft)); } else if(type == 'vertical') { var verticalShowing = elemHeight - missingTop - missingBottom; // If user specified a percentage then find out if the current shown percent // is larger than the allowed percent. // Otherwise check to see if the amount of px shown is larger than the // allotted amount. if (amountVisible.indexOf('%')) { return (((verticalShowing/elemHeight)*100) >= parseInt(amountVisible)); } else { return (verticalShowing >= parseInt(amountVisible)); } } else if(type == 'horizontal') { var horizontalShowing = elemWidth - missingLeft - missingRight; // If user specified a percentage then find out if the current shown percent // is larger than the allowed percent. // Otherwise check to see if the amount of px shown is larger than the // allotted amount. if (amountVisible.indexOf('%')) { return (((horizontalShowing/elemWidth)*100) >= parseInt(amountVisible)); } else { return (horizontalShowing >= parseInt(amountVisible)); } } else if(type == 'area') { var areaShowing = (elemWidth - missingLeft - missingRight) * (elemHeight - missingTop - missingBottom); // If user specified a percentage then find out if the current shown percent // is larger than the allowed percent. // Otherwise check to see if the amount of px shown is larger than the // allotted amount. if (amountVisible.indexOf('%')) { return (((areaShowing/elemArea)*100) >= parseInt(amountVisible)); } else { return (areaShowing >= parseInt(amountVisible)); } } } })(jQuery);
Wylbur/kula
sites/kulacenter.com/modules/views_slideshow/contrib/views_slideshow_thumbnailhover/views_slideshow.js
JavaScript
gpl-2.0
14,726
'use strict'; var got = require('got'); var objectAssign = require('object-assign'); var Promise = require('pinkie-promise'); function ghGot(path, opts) { if (typeof path !== 'string') { return Promise.reject(new TypeError('Path should be a string')); } opts = objectAssign({json: true, endpoint: 'https://api.github.com/'}, opts); opts.headers = objectAssign({ 'accept': 'application/vnd.github.v3+json', 'user-agent': 'https://github.com/sindresorhus/gh-got' }, opts.headers); var env = process.env; var token = env.GITHUB_TOKEN || opts.token; if (token) { opts.headers.authorization = 'token ' + token; } // https://developer.github.com/v3/#http-verbs if (opts.method && opts.method.toLowerCase() === 'put' && !opts.body) { opts.headers['content-length'] = 0; } var endpoint = env.GITHUB_ENDPOINT ? env.GITHUB_ENDPOINT.replace(/[^/]$/, '$&/') : opts.endpoint; var url = /https?/.test(path) ? path : endpoint + path; if (opts.stream) { return got.stream(url, opts); } return got(url, opts); } var helpers = [ 'get', 'post', 'put', 'patch', 'head', 'delete' ]; helpers.forEach(function (el) { ghGot[el] = function (url, opts) { return ghGot(url, objectAssign({}, opts, {method: el.toUpperCase()})); }; }); ghGot.stream = function (url, opts) { return ghGot(url, objectAssign({}, opts, {json: false, stream: true})); }; helpers.forEach(function (el) { ghGot.stream[el] = function (url, opts) { return ghGot.stream(url, objectAssign({}, opts, {method: el.toUpperCase()})); }; }); module.exports = ghGot;
tsiry95/openshift-strongloop-cartridge
strongloop/node_modules/gh-got/index.js
JavaScript
mit
1,561
/*! HTML - v0.12.1 - 2014-10-22 * http://nbubna.github.io/HTML/ * Copyright (c) 2014 ESHA Research; Licensed MIT, GPL */ (function(window, document, HTML) { "use strict"; var fn = HTML._.fn.stringify = function(markup, indent) { var s = ''; this.each(function(el) { s += _.print(el, markup||false, indent||''); }); return s; }, _ = fn._ = { map: Array.prototype.map, specialPrefix: '_', markup: { '\n': '<br>', '<': '<span class="markup">&lt;</span>', '>': '<span class="markup">&gt;</span>', '</': '<span class="markup">&lt;/</span>', '\t': '&nbsp;&nbsp;&nbsp;&nbsp;' }, plain: { '\n': '\n', '<': '<', '>': '>', '</': '</', '/>': '/>', '\t': ' ' }, type: { attr: 'attr', string: 'string', tag: 'tag', }, print: function(el, markup, indent) { var tag = el.tagName.toLowerCase(), code = markup ? _.markup : _.plain, line = _.isInline(el) ? '' : code['\n'], content = _.content(el, markup, indent+code['\t'], line), attrs = _.attrs(el, markup), special = markup ? _.special(el) : []; if (markup) { tag = _.mark(tag, _.type.tag); } var open = _.mark(code['<'] + tag + (attrs ? ' '+attrs : '') + code['>'], special), close = _.mark(code['</'] + tag + code['>'], special); if (content && line) { content = line + content + line + indent; } return indent + open + content + close; }, isInline: function(el) { return (el.currentStyle || window.getComputedStyle(el,'')).display === 'inline' || el.tagName.match(/^(H\d|LI)$/i); }, content: function(el, markup, indent, line) { var s = []; for (var i=0, m= el.childNodes.length; i<m; i++) { var node = el.childNodes[i]; if (node.tagName) { s.push(_.print(node, markup, line ? indent : '')); } else if (node.nodeType === 3) { var text = node.textContent.replace(/^\s+|\s+$/g, ' '); if (text.match(/[^\s]/)) { s.push(text); } } } return s.join(line); }, attrs: function(el, markup) { return _.map.call(el.attributes, function(attr) { var name = attr.nodeName, value = attr.nodeValue; if (!markup || name.indexOf(_.specialPrefix) !== 0) { return markup ? _.mark(name+'=', _.type.attr) + _.mark('"'+value+'"', _.type.string) : name+'="'+value+'"'; } }).filter(_.notEmpty).join(' '); }, special: function(el) { return _.map.call(el.attributes, function(attr) { var name = attr.nodeName; if (name.indexOf(_.specialPrefix) === 0) { return name.substr(1)+'="'+attr.nodeValue+'"'; } }).filter(_.notEmpty); }, mark: function(value, attrs) { if (attrs.length) { if (typeof attrs === "string"){ attrs = ['class="'+attrs+'"']; } return '<span '+attrs.join(' ')+'>'+value+'</span>'; } return value; }, notEmpty: function(s) { return s !== undefined && s !== null && s !== ''; } }; })(window, document, document.documentElement);
nbubna/HTML
dist/HTML.stringify.js
JavaScript
mit
3,843
onerror = function(message, url, lineno) { if (url != location.href) postMessage("FAIL: Bad location. Actual: " + url + " Expected: " + location.href); splitUrl = url.split('/'); postMessage("PASS: onerror in worker context invoked for a script that has script error '" + message + "' at line " + lineno + " in " + splitUrl[splitUrl.length - 1]); return false; } foo.bar = 0;
scheib/chromium
third_party/blink/web_tests/fast/workers/resources/worker-script-error-bubbled.js
JavaScript
bsd-3-clause
401
/* jshint expr:true */ import {expect} from 'chai'; import { describeComponent, it } from 'ember-mocha'; describeComponent( 'gh-user-active', 'Unit: Component: gh-user-active', { unit: true // specify the other units that are required for this test // needs: ['component:foo', 'helper:bar'] }, function () { it('renders', function () { // creates the component instance let component = this.subject(); expect(component._state).to.equal('preRender'); // renders the component on the page this.render(); expect(component._state).to.equal('inDOM'); }); } );
airycanon/Ghost-Admin
tests/unit/components/gh-user-active-test.js
JavaScript
mit
702
// This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * JS module for the data requests filter. * * @module tool_dataprivacy/request_filter * @package tool_dataprivacy * @copyright 2018 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define(['jquery', 'core/form-autocomplete', 'core/str', 'core/notification'], function($, Autocomplete, Str, Notification) { /** * Selectors. * * @access private * @type {{REQUEST_FILTERS: string}} */ var SELECTORS = { REQUEST_FILTERS: '#request-filters' }; /** * Init function. * * @method init * @private */ var init = function() { var stringkeys = [ { key: 'filter', component: 'moodle' }, { key: 'nofiltersapplied', component: 'moodle' } ]; Str.get_strings(stringkeys).then(function(langstrings) { var placeholder = langstrings[0]; var noSelectionString = langstrings[1]; return Autocomplete.enhance(SELECTORS.REQUEST_FILTERS, false, '', placeholder, false, true, noSelectionString, true); }).fail(Notification.exception); var last = $(SELECTORS.REQUEST_FILTERS).val(); $(SELECTORS.REQUEST_FILTERS).on('change', function() { var current = $(this).val(); // Prevent form from submitting unnecessarily, eg. on blur when no filter is selected. if (last.join(',') !== current.join(',')) { // If we're submitting without filters, set the hidden input 'filters-cleared' to 1. if (current.length === 0) { $('#filters-cleared').val(1); } $(this.form).submit(); } }); }; return /** @alias module:core/form-autocomplete */ { /** * Initialise the unified user filter. * * @method init */ init: function() { init(); } }; });
merrill-oakland/moodle
admin/tool/dataprivacy/amd/src/request_filter.js
JavaScript
gpl-3.0
2,742
'use strict'; exports.__esModule = true; var _postcssValueParser = require('postcss-value-parser'); var _postcssValueParser2 = _interopRequireDefault(_postcssValueParser); var _postcss = require('postcss'); var _postcss2 = _interopRequireDefault(_postcss); var _encode = require('./lib/encode'); var _encode2 = _interopRequireDefault(_encode); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function isNum(node) { return (0, _postcssValueParser.unit)(node.value); } function transformAtRule(_ref) { var cache = _ref.cache; var ruleCache = _ref.ruleCache; var declCache = _ref.declCache; // Iterate each property and change their names declCache.forEach(function (decl) { decl.value = (0, _postcssValueParser2.default)(decl.value).walk(function (node) { if (node.type === 'word' && node.value in cache) { cache[node.value].count++; node.value = cache[node.value].ident; } else if (node.type === 'space') { node.value = ' '; } else if (node.type === 'div') { node.before = node.after = ''; } }).toString(); }); // Ensure that at rules with no references to them are left unchanged ruleCache.forEach(function (rule) { Object.keys(cache).forEach(function (key) { var cached = cache[key]; if (cached.ident === rule.params && !cached.count) { rule.params = key; } }); }); } function transformDecl(_ref2) { var cache = _ref2.cache; var declOneCache = _ref2.declOneCache; var declTwoCache = _ref2.declTwoCache; declTwoCache.forEach(function (decl) { decl.value = (0, _postcssValueParser2.default)(decl.value).walk(function (node) { var type = node.type; var value = node.value; if (type === 'function' && (value === 'counter' || value === 'counters')) { (0, _postcssValueParser.walk)(node.nodes, function (child) { if (child.type === 'word' && child.value in cache) { cache[child.value].count++; child.value = cache[child.value].ident; } else if (child.type === 'div') { child.before = child.after = ''; } }); } if (type === 'space') { node.value = ' '; } return false; }).toString(); }); declOneCache.forEach(function (decl) { decl.value = decl.value.walk(function (node) { if (node.type === 'word' && !isNum(node)) { Object.keys(cache).forEach(function (key) { var cached = cache[key]; if (cached.ident === node.value && !cached.count) { node.value = key; } }); } }).toString(); }); } function addToCache(value, encoder, cache) { if (cache[value]) { return; } cache[value] = { ident: encoder(value, Object.keys(cache).length), count: 0 }; } function cacheAtRule(node, encoder, _ref3) { var cache = _ref3.cache; var ruleCache = _ref3.ruleCache; var params = node.params; addToCache(params, encoder, cache); node.params = cache[params].ident; ruleCache.push(node); } exports.default = _postcss2.default.plugin('postcss-reduce-idents', function () { var _ref4 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var _ref4$counter = _ref4.counter; var counter = _ref4$counter === undefined ? true : _ref4$counter; var _ref4$counterStyle = _ref4.counterStyle; var counterStyle = _ref4$counterStyle === undefined ? true : _ref4$counterStyle; var _ref4$encoder = _ref4.encoder; var encoder = _ref4$encoder === undefined ? _encode2.default : _ref4$encoder; var _ref4$keyframes = _ref4.keyframes; var keyframes = _ref4$keyframes === undefined ? true : _ref4$keyframes; return function (css) { // Encode at rule names and cache the result var counterCache = { cache: {}, declOneCache: [], declTwoCache: [] }; var counterStyleCache = { cache: {}, ruleCache: [], declCache: [] }; var keyframesCache = { cache: {}, ruleCache: [], declCache: [] }; css.walk(function (node) { var name = node.name; var prop = node.prop; var type = node.type; if (type === 'atrule') { if (counterStyle && /counter-style/.test(name)) { cacheAtRule(node, encoder, counterStyleCache); } if (keyframes && /keyframes/.test(name)) { cacheAtRule(node, encoder, keyframesCache); } } if (type === 'decl') { if (counter) { if (/counter-(reset|increment)/.test(prop)) { node.value = (0, _postcssValueParser2.default)(node.value).walk(function (child) { if (child.type === 'word' && !isNum(child)) { addToCache(child.value, encoder, counterCache.cache); child.value = counterCache.cache[child.value].ident; } else if (child.type === 'space') { child.value = ' '; } }); counterCache.declOneCache.push(node); } else if (/content/.test(prop)) { counterCache.declTwoCache.push(node); } } if (counterStyle && /(list-style|system)/.test(prop)) { counterStyleCache.declCache.push(node); } if (keyframes && /animation/.test(prop)) { keyframesCache.declCache.push(node); } } }); counter && transformDecl(counterCache); counterStyle && transformAtRule(counterStyleCache); keyframes && transformAtRule(keyframesCache); }; }); module.exports = exports['default'];
hfutlyz/react-exp-demos
webpack/node_modules/postcss-reduce-idents/dist/index.js
JavaScript
mit
6,466
/*! * dependencyLib.min.js * http://github.com/RobinHerbots/jquery.inputmask * Copyright (c) 2010 - 2015 Robin Herbots * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) * Version: 3.2.0 */ !function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a(require("jquery")):a(jQuery)}(function(a){var b=a;return window.dependencyLib=b,b});
hackultura/meta-id-client
src/public/vendors/jquery.inputmask/dist/min/inputmask/dependencyLib.min.js
JavaScript
gpl-2.0
423
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang("a11yhelp","th",{title:"Accessibility Instructions",contents:"Help Contents. To close this dialog press ESC.",legend:[{name:"ทั่วไป",items:[{name:"แถบเครื่องมือสำหรับเครื่องมือช่วยพิมพ์",legend:"Press ${toolbarFocus} to navigate to the toolbar. Move to the next and previous toolbar group with TAB and SHIFT+TAB. Move to the next and previous toolbar button with RIGHT ARROW or LEFT ARROW. Press SPACE or ENTER to activate the toolbar button."},{name:"Editor Dialog",legend:"Inside a dialog, press TAB to navigate to the next dialog element, press SHIFT+TAB to move to the previous dialog element, press ENTER to submit the dialog, press ESC to cancel the dialog. When a dialog has multiple tabs, the tab list can be reached either with ALT+F10 or with TAB as part of the dialog tabbing order. With tab list focused, move to the next and previous tab with RIGHT and LEFT ARROW, respectively."}, {name:"Editor Context Menu",legend:"Press ${contextMenu} or APPLICATION KEY to open context-menu. Then move to next menu option with TAB or DOWN ARROW. Move to previous option with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the menu option. Open sub-menu of current option with SPACE or ENTER or RIGHT ARROW. Go back to parent menu item with ESC or LEFT ARROW. Close context menu with ESC."},{name:"Editor List Box",legend:"Inside a list-box, move to next list item with TAB OR DOWN ARROW. Move to previous list item with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the list option. Press ESC to close the list-box."}, {name:"Editor Element Path Bar",legend:"Press ${elementsPathFocus} to navigate to the elements path bar. Move to next element button with TAB or RIGHT ARROW. Move to previous button with SHIFT+TAB or LEFT ARROW. Press SPACE or ENTER to select the element in editor."}]},{name:"คำสั่ง",items:[{name:"เลิกทำคำสั่ง",legend:"วาง ${undo}"},{name:"คำสั่งสำหรับทำซ้ำ",legend:"วาง ${redo}"},{name:"คำสั่งสำหรับตัวหนา",legend:"วาง ${bold}"},{name:"คำสั่งสำหรับตัวเอียง",legend:"วาง ${italic}"},{name:"คำสั่งสำหรับขีดเส้นใต้", legend:"วาง ${underline}"},{name:"คำสั่งสำหรับลิงก์",legend:"วาง ${link}"},{name:" Toolbar Collapse command",legend:"Press ${toolbarCollapse}"},{name:" Access previous focus space command",legend:"Press ${accessPreviousSpace} to access the closest unreachable focus space before the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."},{name:" Access next focus space command",legend:"Press ${accessNextSpace} to access the closest unreachable focus space after the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."}, {name:" Accessibility Help",legend:"Press ${a11yHelp}"},{name:" Paste as plain text",legend:"Press ${pastetext}",legendEdge:"Press ${pastetext}, followed by ${paste}"}]}],tab:"Tab",pause:"Pause",capslock:"Caps Lock",escape:"Escape",pageUp:"Page Up",pageDown:"Page Down",leftArrow:"Left Arrow",upArrow:"Up Arrow",rightArrow:"Right Arrow",downArrow:"Down Arrow",insert:"Insert",leftWindowKey:"Left Windows key",rightWindowKey:"Right Windows key",selectKey:"Select key",numpad0:"Numpad 0",numpad1:"Numpad 1", numpad2:"Numpad 2",numpad3:"Numpad 3",numpad4:"Numpad 4",numpad5:"Numpad 5",numpad6:"Numpad 6",numpad7:"Numpad 7",numpad8:"Numpad 8",numpad9:"Numpad 9",multiply:"Multiply",add:"Add",subtract:"Subtract",decimalPoint:"Decimal Point",divide:"Divide",f1:"F1",f2:"F2",f3:"F3",f4:"F4",f5:"F5",f6:"F6",f7:"F7",f8:"F8",f9:"F9",f10:"F10",f11:"F11",f12:"F12",numLock:"Num Lock",scrollLock:"Scroll Lock",semiColon:"Semicolon",equalSign:"Equal Sign",comma:"Comma",dash:"Dash",period:"Period",forwardSlash:"Forward Slash", graveAccent:"Grave Accent",openBracket:"Open Bracket",backSlash:"Backslash",closeBracket:"Close Bracket",singleQuote:"Single Quote"});
OpenLGK/ProcessWire
wire/modules/Inputfield/InputfieldCKEditor/ckeditor-4.8.0/plugins/a11yhelp/dialogs/lang/th.js
JavaScript
mpl-2.0
4,369
// Karma configuration // Generated on Thu Dec 10 2015 03:01:27 GMT+0100 (CET) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha'], // list of files / patterns to load in the browser files: [ 'dist/*.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS', 'Firefox'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false, // Concurrency level // how many browser should be started simultanous concurrency: Infinity }) }
MacroLin/practice
webpack+react(练习)/node_modules/.1.1.7@object-hash/karma.conf.js
JavaScript
mit
1,683
!function(root, factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else { factory(root.jQuery); } }(this, function($) { /*! @package noty - jQuery Notification Plugin @version version: 2.3.3 @contributors https://github.com/needim/noty/graphs/contributors @documentation Examples and Documentation - http://needim.github.com/noty/ @license Licensed under the MIT licenses: http://www.opensource.org/licenses/mit-license.php */ if(typeof Object.create !== 'function') { Object.create = function(o) { function F() { } F.prototype = o; return new F(); }; } var NotyObject = { init: function(options) { // Mix in the passed in options with the default options this.options = $.extend({}, $.noty.defaults, options); this.options.layout = (this.options.custom) ? $.noty.layouts['inline'] : $.noty.layouts[this.options.layout]; if($.noty.themes[this.options.theme]) this.options.theme = $.noty.themes[this.options.theme]; else options.themeClassName = this.options.theme; delete options.layout; delete options.theme; this.options = $.extend({}, this.options, this.options.layout.options); this.options.id = 'noty_' + (new Date().getTime() * Math.floor(Math.random() * 1000000)); this.options = $.extend({}, this.options, options); // Build the noty dom initial structure this._build(); // return this so we can chain/use the bridge with less code. return this; }, // end init _build: function() { // Generating noty bar var $bar = $('<div class="noty_bar noty_type_' + this.options.type + '"></div>').attr('id', this.options.id); $bar.append(this.options.template).find('.noty_text').html(this.options.text); this.$bar = (this.options.layout.parent.object !== null) ? $(this.options.layout.parent.object).css(this.options.layout.parent.css).append($bar) : $bar; if(this.options.themeClassName) this.$bar.addClass(this.options.themeClassName).addClass('noty_container_type_' + this.options.type); // Set buttons if available if(this.options.buttons) { // If we have button disable closeWith & timeout options this.options.closeWith = []; this.options.timeout = false; var $buttons = $('<div/>').addClass('noty_buttons'); (this.options.layout.parent.object !== null) ? this.$bar.find('.noty_bar').append($buttons) : this.$bar.append($buttons); var self = this; $.each(this.options.buttons, function(i, button) { var $button = $('<button/>').addClass((button.addClass) ? button.addClass : 'gray').html(button.text).attr('id', button.id ? button.id : 'button-' + i) .appendTo(self.$bar.find('.noty_buttons')) .on('click', function() { if($.isFunction(button.onClick)) { button.onClick.call($button, self); } }); }); } // For easy access this.$message = this.$bar.find('.noty_message'); this.$closeButton = this.$bar.find('.noty_close'); this.$buttons = this.$bar.find('.noty_buttons'); $.noty.store[this.options.id] = this; // store noty for api }, // end _build show: function() { var self = this; (self.options.custom) ? self.options.custom.find(self.options.layout.container.selector).append(self.$bar) : $(self.options.layout.container.selector).append(self.$bar); if(self.options.theme && self.options.theme.style) self.options.theme.style.apply(self); ($.type(self.options.layout.css) === 'function') ? this.options.layout.css.apply(self.$bar) : self.$bar.css(this.options.layout.css || {}); self.$bar.addClass(self.options.layout.addClass); self.options.layout.container.style.apply($(self.options.layout.container.selector)); self.showing = true; if(self.options.theme && self.options.theme.style) self.options.theme.callback.onShow.apply(this); if($.inArray('click', self.options.closeWith) > -1) self.$bar.css('cursor', 'pointer').one('click', function(evt) { self.stopPropagation(evt); if(self.options.callback.onCloseClick) { self.options.callback.onCloseClick.apply(self); } self.close(); }); if($.inArray('hover', self.options.closeWith) > -1) self.$bar.one('mouseenter', function() { self.close(); }); if($.inArray('button', self.options.closeWith) > -1) self.$closeButton.one('click', function(evt) { self.stopPropagation(evt); self.close(); }); if($.inArray('button', self.options.closeWith) == -1) self.$closeButton.remove(); if(self.options.callback.onShow) self.options.callback.onShow.apply(self); if (typeof self.options.animation.open == 'string') { self.$bar.css('height', self.$bar.innerHeight()); self.$bar.show().addClass(self.options.animation.open).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() { if(self.options.callback.afterShow) self.options.callback.afterShow.apply(self); self.showing = false; self.shown = true; }); } else { self.$bar.animate( self.options.animation.open, self.options.animation.speed, self.options.animation.easing, function() { if(self.options.callback.afterShow) self.options.callback.afterShow.apply(self); self.showing = false; self.shown = true; }); } // If noty is have a timeout option if(self.options.timeout) self.$bar.delay(self.options.timeout).promise().done(function() { self.close(); }); return this; }, // end show close: function() { if(this.closed) return; if(this.$bar && this.$bar.hasClass('i-am-closing-now')) return; var self = this; if(this.showing) { self.$bar.queue( function() { self.close.apply(self); } ); return; } //this.$bar.dequeue(); if(!this.shown && !this.showing) { // If we are still waiting in the queue just delete from queue var queue = []; $.each($.noty.queue, function(i, n) { if(n.options.id != self.options.id) { queue.push(n); } }); $.noty.queue = queue; return; } self.$bar.addClass('i-am-closing-now'); if(self.options.callback.onClose) { self.options.callback.onClose.apply(self); } if (typeof self.options.animation.close == 'string') { self.$bar.addClass(self.options.animation.close).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() { if(self.options.callback.afterClose) self.options.callback.afterClose.apply(self); self.closeCleanUp(); }); } else { self.$bar.clearQueue().stop().animate( self.options.animation.close, self.options.animation.speed, self.options.animation.easing, function() { if(self.options.callback.afterClose) self.options.callback.afterClose.apply(self); }) .promise().done(function() { self.closeCleanUp(); }); } }, // end close closeCleanUp: function() { var self = this; // Modal Cleaning if(self.options.modal) { $.notyRenderer.setModalCount(-1); if($.notyRenderer.getModalCount() == 0) $('.noty_modal').fadeOut('fast', function() { $(this).remove(); }); } // Layout Cleaning $.notyRenderer.setLayoutCountFor(self, -1); if($.notyRenderer.getLayoutCountFor(self) == 0) $(self.options.layout.container.selector).remove(); // Make sure self.$bar has not been removed before attempting to remove it if(typeof self.$bar !== 'undefined' && self.$bar !== null) { if (typeof self.options.animation.close == 'string') { self.$bar.css('transition', 'all 100ms ease').css('border', 0).css('margin', 0).height(0); self.$bar.one('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function() { self.$bar.remove(); self.$bar = null; self.closed = true; if(self.options.theme.callback && self.options.theme.callback.onClose) { self.options.theme.callback.onClose.apply(self); } }); } else { self.$bar.remove(); self.$bar = null; self.closed = true; } } delete $.noty.store[self.options.id]; // deleting noty from store if(self.options.theme.callback && self.options.theme.callback.onClose) { self.options.theme.callback.onClose.apply(self); } if(!self.options.dismissQueue) { // Queue render $.noty.ontap = true; $.notyRenderer.render(); } if(self.options.maxVisible > 0 && self.options.dismissQueue) { $.notyRenderer.render(); } }, // end close clean up setText: function(text) { if(!this.closed) { this.options.text = text; this.$bar.find('.noty_text').html(text); } return this; }, setType: function(type) { if(!this.closed) { this.options.type = type; this.options.theme.style.apply(this); this.options.theme.callback.onShow.apply(this); } return this; }, setTimeout: function(time) { if(!this.closed) { var self = this; this.options.timeout = time; self.$bar.delay(self.options.timeout).promise().done(function() { self.close(); }); } return this; }, stopPropagation: function(evt) { evt = evt || window.event; if(typeof evt.stopPropagation !== "undefined") { evt.stopPropagation(); } else { evt.cancelBubble = true; } }, closed : false, showing: false, shown : false }; // end NotyObject $.notyRenderer = {}; $.notyRenderer.init = function(options) { // Renderer creates a new noty var notification = Object.create(NotyObject).init(options); if(notification.options.killer) $.noty.closeAll(); (notification.options.force) ? $.noty.queue.unshift(notification) : $.noty.queue.push(notification); $.notyRenderer.render(); return ($.noty.returns == 'object') ? notification : notification.options.id; }; $.notyRenderer.render = function() { var instance = $.noty.queue[0]; if($.type(instance) === 'object') { if(instance.options.dismissQueue) { if(instance.options.maxVisible > 0) { if($(instance.options.layout.container.selector + ' li').length < instance.options.maxVisible) { $.notyRenderer.show($.noty.queue.shift()); } else { } } else { $.notyRenderer.show($.noty.queue.shift()); } } else { if($.noty.ontap) { $.notyRenderer.show($.noty.queue.shift()); $.noty.ontap = false; } } } else { $.noty.ontap = true; // Queue is over } }; $.notyRenderer.show = function(notification) { if(notification.options.modal) { $.notyRenderer.createModalFor(notification); $.notyRenderer.setModalCount(+1); } // Where is the container? if(notification.options.custom) { if(notification.options.custom.find(notification.options.layout.container.selector).length == 0) { notification.options.custom.append($(notification.options.layout.container.object).addClass('i-am-new')); } else { notification.options.custom.find(notification.options.layout.container.selector).removeClass('i-am-new'); } } else { if($(notification.options.layout.container.selector).length == 0) { $('body').append($(notification.options.layout.container.object).addClass('i-am-new')); } else { $(notification.options.layout.container.selector).removeClass('i-am-new'); } } $.notyRenderer.setLayoutCountFor(notification, +1); notification.show(); }; $.notyRenderer.createModalFor = function(notification) { if($('.noty_modal').length == 0) { var modal = $('<div/>').addClass('noty_modal').addClass(notification.options.theme).data('noty_modal_count', 0); if(notification.options.theme.modal && notification.options.theme.modal.css) modal.css(notification.options.theme.modal.css); modal.prependTo($('body')).fadeIn('fast'); if($.inArray('backdrop', notification.options.closeWith) > -1) modal.on('click', function(e) { $.noty.closeAll(); }); } }; $.notyRenderer.getLayoutCountFor = function(notification) { return $(notification.options.layout.container.selector).data('noty_layout_count') || 0; }; $.notyRenderer.setLayoutCountFor = function(notification, arg) { return $(notification.options.layout.container.selector).data('noty_layout_count', $.notyRenderer.getLayoutCountFor(notification) + arg); }; $.notyRenderer.getModalCount = function() { return $('.noty_modal').data('noty_modal_count') || 0; }; $.notyRenderer.setModalCount = function(arg) { return $('.noty_modal').data('noty_modal_count', $.notyRenderer.getModalCount() + arg); }; // This is for custom container $.fn.noty = function(options) { options.custom = $(this); return $.notyRenderer.init(options); }; $.noty = {}; $.noty.queue = []; $.noty.ontap = true; $.noty.layouts = {}; $.noty.themes = {}; $.noty.returns = 'object'; $.noty.store = {}; $.noty.get = function(id) { return $.noty.store.hasOwnProperty(id) ? $.noty.store[id] : false; }; $.noty.close = function(id) { return $.noty.get(id) ? $.noty.get(id).close() : false; }; $.noty.setText = function(id, text) { return $.noty.get(id) ? $.noty.get(id).setText(text) : false; }; $.noty.setType = function(id, type) { return $.noty.get(id) ? $.noty.get(id).setType(type) : false; }; $.noty.clearQueue = function() { $.noty.queue = []; }; $.noty.closeAll = function() { $.noty.clearQueue(); $.each($.noty.store, function(id, noty) { noty.close(); }); }; var windowAlert = window.alert; $.noty.consumeAlert = function(options) { window.alert = function(text) { if(options) options.text = text; else options = {text: text}; $.notyRenderer.init(options); }; }; $.noty.stopConsumeAlert = function() { window.alert = windowAlert; }; $.noty.defaults = { layout : 'top', theme : 'defaultTheme', type : 'alert', text : '', dismissQueue: true, template : '<div class="noty_message"><span class="noty_text"></span><div class="noty_close"></div></div>', animation : { open : {height: 'toggle'}, close : {height: 'toggle'}, easing: 'swing', speed : 500 }, timeout : false, force : false, modal : false, maxVisible : 5, killer : false, closeWith : ['click'], callback : { onShow : function() { }, afterShow : function() { }, onClose : function() { }, afterClose : function() { }, onCloseClick: function() { } }, buttons : false }; $(window).on('resize', function() { $.each($.noty.layouts, function(index, layout) { layout.container.style.apply($(layout.container.selector)); }); }); // Helpers window.noty = function noty(options) { return jQuery.notyRenderer.init(options); }; $.noty.layouts.bottom = { name : 'bottom', options : {}, container: { object : '<ul id="noty_bottom_layout_container" />', selector: 'ul#noty_bottom_layout_container', style : function() { $(this).css({ bottom : 0, left : '5%', position : 'fixed', width : '90%', height : 'auto', margin : 0, padding : 0, listStyleType: 'none', zIndex : 9999999 }); } }, parent : { object : '<li />', selector: 'li', css : {} }, css : { display: 'none' }, addClass : '' }; $.noty.layouts.bottomCenter = { name : 'bottomCenter', options : { // overrides options }, container: { object : '<ul id="noty_bottomCenter_layout_container" />', selector: 'ul#noty_bottomCenter_layout_container', style : function() { $(this).css({ bottom : 20, left : 0, position : 'fixed', width : '310px', height : 'auto', margin : 0, padding : 0, listStyleType: 'none', zIndex : 10000000 }); $(this).css({ left: ($(window).width() - $(this).outerWidth(false)) / 2 + 'px' }); } }, parent : { object : '<li />', selector: 'li', css : {} }, css : { display: 'none', width : '310px' }, addClass : '' }; $.noty.layouts.bottomLeft = { name : 'bottomLeft', options : { // overrides options }, container: { object : '<ul id="noty_bottomLeft_layout_container" />', selector: 'ul#noty_bottomLeft_layout_container', style : function() { $(this).css({ bottom : 20, left : 20, position : 'fixed', width : '310px', height : 'auto', margin : 0, padding : 0, listStyleType: 'none', zIndex : 10000000 }); if(window.innerWidth < 600) { $(this).css({ left: 5 }); } } }, parent : { object : '<li />', selector: 'li', css : {} }, css : { display: 'none', width : '310px' }, addClass : '' }; $.noty.layouts.bottomRight = { name : 'bottomRight', options : { // overrides options }, container: { object : '<ul id="noty_bottomRight_layout_container" />', selector: 'ul#noty_bottomRight_layout_container', style : function() { $(this).css({ bottom : 20, right : 20, position : 'fixed', width : '310px', height : 'auto', margin : 0, padding : 0, listStyleType: 'none', zIndex : 10000000 }); if(window.innerWidth < 600) { $(this).css({ right: 5 }); } } }, parent : { object : '<li />', selector: 'li', css : {} }, css : { display: 'none', width : '310px' }, addClass : '' }; $.noty.layouts.center = { name : 'center', options : { // overrides options }, container: { object : '<ul id="noty_center_layout_container" />', selector: 'ul#noty_center_layout_container', style : function() { $(this).css({ position : 'fixed', width : '310px', height : 'auto', margin : 0, padding : 0, listStyleType: 'none', zIndex : 10000000 }); // getting hidden height var dupe = $(this).clone().css({visibility: "hidden", display: "block", position: "absolute", top: 0, left: 0}).attr('id', 'dupe'); $("body").append(dupe); dupe.find('.i-am-closing-now').remove(); dupe.find('li').css('display', 'block'); var actual_height = dupe.height(); dupe.remove(); if($(this).hasClass('i-am-new')) { $(this).css({ left: ($(window).width() - $(this).outerWidth(false)) / 2 + 'px', top : ($(window).height() - actual_height) / 2 + 'px' }); } else { $(this).animate({ left: ($(window).width() - $(this).outerWidth(false)) / 2 + 'px', top : ($(window).height() - actual_height) / 2 + 'px' }, 500); } } }, parent : { object : '<li />', selector: 'li', css : {} }, css : { display: 'none', width : '310px' }, addClass : '' }; $.noty.layouts.centerLeft = { name : 'centerLeft', options : { // overrides options }, container: { object : '<ul id="noty_centerLeft_layout_container" />', selector: 'ul#noty_centerLeft_layout_container', style : function() { $(this).css({ left : 20, position : 'fixed', width : '310px', height : 'auto', margin : 0, padding : 0, listStyleType: 'none', zIndex : 10000000 }); // getting hidden height var dupe = $(this).clone().css({visibility: "hidden", display: "block", position: "absolute", top: 0, left: 0}).attr('id', 'dupe'); $("body").append(dupe); dupe.find('.i-am-closing-now').remove(); dupe.find('li').css('display', 'block'); var actual_height = dupe.height(); dupe.remove(); if($(this).hasClass('i-am-new')) { $(this).css({ top: ($(window).height() - actual_height) / 2 + 'px' }); } else { $(this).animate({ top: ($(window).height() - actual_height) / 2 + 'px' }, 500); } if(window.innerWidth < 600) { $(this).css({ left: 5 }); } } }, parent : { object : '<li />', selector: 'li', css : {} }, css : { display: 'none', width : '310px' }, addClass : '' }; $.noty.layouts.centerRight = { name : 'centerRight', options : { // overrides options }, container: { object : '<ul id="noty_centerRight_layout_container" />', selector: 'ul#noty_centerRight_layout_container', style : function() { $(this).css({ right : 20, position : 'fixed', width : '310px', height : 'auto', margin : 0, padding : 0, listStyleType: 'none', zIndex : 10000000 }); // getting hidden height var dupe = $(this).clone().css({visibility: "hidden", display: "block", position: "absolute", top: 0, left: 0}).attr('id', 'dupe'); $("body").append(dupe); dupe.find('.i-am-closing-now').remove(); dupe.find('li').css('display', 'block'); var actual_height = dupe.height(); dupe.remove(); if($(this).hasClass('i-am-new')) { $(this).css({ top: ($(window).height() - actual_height) / 2 + 'px' }); } else { $(this).animate({ top: ($(window).height() - actual_height) / 2 + 'px' }, 500); } if(window.innerWidth < 600) { $(this).css({ right: 5 }); } } }, parent : { object : '<li />', selector: 'li', css : {} }, css : { display: 'none', width : '310px' }, addClass : '' }; $.noty.layouts.inline = { name : 'inline', options : {}, container: { object : '<ul class="noty_inline_layout_container" />', selector: 'ul.noty_inline_layout_container', style : function() { $(this).css({ width : '100%', height : 'auto', margin : 0, padding : 0, listStyleType: 'none', zIndex : 9999999 }); } }, parent : { object : '<li />', selector: 'li', css : {} }, css : { display: 'none' }, addClass : '' }; $.noty.layouts.top = { name : 'top', options : {}, container: { object : '<ul id="noty_top_layout_container" />', selector: 'ul#noty_top_layout_container', style : function() { $(this).css({ top : 0, left : '5%', position : 'fixed', width : '90%', height : 'auto', margin : 0, padding : 0, listStyleType: 'none', zIndex : 9999999 }); } }, parent : { object : '<li />', selector: 'li', css : {} }, css : { display: 'none' }, addClass : '' }; $.noty.layouts.topCenter = { name : 'topCenter', options : { // overrides options }, container: { object : '<ul id="noty_topCenter_layout_container" />', selector: 'ul#noty_topCenter_layout_container', style : function() { $(this).css({ top : 20, left : 0, position : 'fixed', width : '310px', height : 'auto', margin : 0, padding : 0, listStyleType: 'none', zIndex : 10000000 }); $(this).css({ left: ($(window).width() - $(this).outerWidth(false)) / 2 + 'px' }); } }, parent : { object : '<li />', selector: 'li', css : {} }, css : { display: 'none', width : '310px' }, addClass : '' }; $.noty.layouts.topLeft = { name : 'topLeft', options : { // overrides options }, container: { object : '<ul id="noty_topLeft_layout_container" />', selector: 'ul#noty_topLeft_layout_container', style : function() { $(this).css({ top : 20, left : 20, position : 'fixed', width : '310px', height : 'auto', margin : 0, padding : 0, listStyleType: 'none', zIndex : 10000000 }); if(window.innerWidth < 600) { $(this).css({ left: 5 }); } } }, parent : { object : '<li />', selector: 'li', css : {} }, css : { display: 'none', width : '310px' }, addClass : '' }; $.noty.layouts.topRight = { name : 'topRight', options : { // overrides options }, container: { object : '<ul id="noty_topRight_layout_container" />', selector: 'ul#noty_topRight_layout_container', style : function() { $(this).css({ top : 20, right : 20, position : 'fixed', width : '310px', height : 'auto', margin : 0, padding : 0, listStyleType: 'none', zIndex : 10000000 }); if(window.innerWidth < 600) { $(this).css({ right: 5 }); } } }, parent : { object : '<li />', selector: 'li', css : {} }, css : { display: 'none', width : '310px' }, addClass : '' }; $.noty.themes.bootstrapTheme = { name: 'bootstrapTheme', modal: { css: { position: 'fixed', width: '100%', height: '100%', backgroundColor: '#000', zIndex: 10000, opacity: 0.6, display: 'none', left: 0, top: 0 } }, style: function() { var containerSelector = this.options.layout.container.selector; $(containerSelector).addClass('list-group'); this.$closeButton.append('<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>'); this.$closeButton.addClass('close'); this.$bar.addClass( "list-group-item" ).css('padding', '0px'); switch (this.options.type) { case 'alert': case 'notification': this.$bar.addClass( "list-group-item-info" ); break; case 'warning': this.$bar.addClass( "list-group-item-warning" ); break; case 'error': this.$bar.addClass( "list-group-item-danger" ); break; case 'information': this.$bar.addClass("list-group-item-info"); break; case 'success': this.$bar.addClass( "list-group-item-success" ); break; } this.$message.css({ fontSize: '13px', lineHeight: '16px', textAlign: 'center', padding: '8px 10px 9px', width: 'auto', position: 'relative' }); }, callback: { onShow: function() { }, onClose: function() { } } }; $.noty.themes.defaultTheme = { name : 'defaultTheme', helpers : { borderFix: function() { if(this.options.dismissQueue) { var selector = this.options.layout.container.selector + ' ' + this.options.layout.parent.selector; switch(this.options.layout.name) { case 'top': $(selector).css({borderRadius: '0px 0px 0px 0px'}); $(selector).last().css({borderRadius: '0px 0px 5px 5px'}); break; case 'topCenter': case 'topLeft': case 'topRight': case 'bottomCenter': case 'bottomLeft': case 'bottomRight': case 'center': case 'centerLeft': case 'centerRight': case 'inline': $(selector).css({borderRadius: '0px 0px 0px 0px'}); $(selector).first().css({'border-top-left-radius': '5px', 'border-top-right-radius': '5px'}); $(selector).last().css({'border-bottom-left-radius': '5px', 'border-bottom-right-radius': '5px'}); break; case 'bottom': $(selector).css({borderRadius: '0px 0px 0px 0px'}); $(selector).first().css({borderRadius: '5px 5px 0px 0px'}); break; default: break; } } } }, modal : { css: { position : 'fixed', width : '100%', height : '100%', backgroundColor: '#000', zIndex : 10000, opacity : 0.6, display : 'none', left : 0, top : 0 } }, style : function() { this.$bar.css({ overflow : 'hidden', background: "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABsAAAAoCAQAAAClM0ndAAAAhklEQVR4AdXO0QrCMBBE0bttkk38/w8WRERpdyjzVOc+HxhIHqJGMQcFFkpYRQotLLSw0IJ5aBdovruMYDA/kT8plF9ZKLFQcgF18hDj1SbQOMlCA4kao0iiXmah7qBWPdxpohsgVZyj7e5I9KcID+EhiDI5gxBYKLBQYKHAQoGFAoEks/YEGHYKB7hFxf0AAAAASUVORK5CYII=') repeat-x scroll left top #fff" }); this.$message.css({ fontSize : '13px', lineHeight: '16px', textAlign : 'center', padding : '8px 10px 9px', width : 'auto', position : 'relative' }); this.$closeButton.css({ position : 'absolute', top : 4, right: 4, width : 10, height: 10, background: "url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAQAAAAnOwc2AAAAxUlEQVR4AR3MPUoDURSA0e++uSkkOxC3IAOWNtaCIDaChfgXBMEZbQRByxCwk+BasgQRZLSYoLgDQbARxry8nyumPcVRKDfd0Aa8AsgDv1zp6pYd5jWOwhvebRTbzNNEw5BSsIpsj/kurQBnmk7sIFcCF5yyZPDRG6trQhujXYosaFoc+2f1MJ89uc76IND6F9BvlXUdpb6xwD2+4q3me3bysiHvtLYrUJto7PD/ve7LNHxSg/woN2kSz4txasBdhyiz3ugPGetTjm3XRokAAAAASUVORK5CYII=)", display : 'none', cursor : 'pointer' }); this.$buttons.css({ padding : 5, textAlign : 'right', borderTop : '1px solid #ccc', backgroundColor: '#fff' }); this.$buttons.find('button').css({ marginLeft: 5 }); this.$buttons.find('button:first').css({ marginLeft: 0 }); this.$bar.on({ mouseenter: function() { $(this).find('.noty_close').stop().fadeTo('normal', 1); }, mouseleave: function() { $(this).find('.noty_close').stop().fadeTo('normal', 0); } }); switch(this.options.layout.name) { case 'top': this.$bar.css({ borderRadius: '0px 0px 5px 5px', borderBottom: '2px solid #eee', borderLeft : '2px solid #eee', borderRight : '2px solid #eee', boxShadow : "0 2px 4px rgba(0, 0, 0, 0.1)" }); break; case 'topCenter': case 'center': case 'bottomCenter': case 'inline': this.$bar.css({ borderRadius: '5px', border : '1px solid #eee', boxShadow : "0 2px 4px rgba(0, 0, 0, 0.1)" }); this.$message.css({fontSize: '13px', textAlign: 'center'}); break; case 'topLeft': case 'topRight': case 'bottomLeft': case 'bottomRight': case 'centerLeft': case 'centerRight': this.$bar.css({ borderRadius: '5px', border : '1px solid #eee', boxShadow : "0 2px 4px rgba(0, 0, 0, 0.1)" }); this.$message.css({fontSize: '13px', textAlign: 'left'}); break; case 'bottom': this.$bar.css({ borderRadius: '5px 5px 0px 0px', borderTop : '2px solid #eee', borderLeft : '2px solid #eee', borderRight : '2px solid #eee', boxShadow : "0 -2px 4px rgba(0, 0, 0, 0.1)" }); break; default: this.$bar.css({ border : '2px solid #eee', boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)" }); break; } switch(this.options.type) { case 'alert': case 'notification': this.$bar.css({backgroundColor: '#FFF', borderColor: '#CCC', color: '#444'}); break; case 'warning': this.$bar.css({backgroundColor: '#FFEAA8', borderColor: '#FFC237', color: '#826200'}); this.$buttons.css({borderTop: '1px solid #FFC237'}); break; case 'error': this.$bar.css({backgroundColor: 'red', borderColor: 'darkred', color: '#FFF'}); this.$message.css({fontWeight: 'bold'}); this.$buttons.css({borderTop: '1px solid darkred'}); break; case 'information': this.$bar.css({backgroundColor: '#57B7E2', borderColor: '#0B90C4', color: '#FFF'}); this.$buttons.css({borderTop: '1px solid #0B90C4'}); break; case 'success': this.$bar.css({backgroundColor: 'lightgreen', borderColor: '#50C24E', color: 'darkgreen'}); this.$buttons.css({borderTop: '1px solid #50C24E'}); break; default: this.$bar.css({backgroundColor: '#FFF', borderColor: '#CCC', color: '#444'}); break; } }, callback: { onShow : function() { $.noty.themes.defaultTheme.helpers.borderFix.apply(this); }, onClose: function() { $.noty.themes.defaultTheme.helpers.borderFix.apply(this); } } }; $.noty.themes.relax = { name : 'relax', helpers : {}, modal : { css: { position : 'fixed', width : '100%', height : '100%', backgroundColor: '#000', zIndex : 10000, opacity : 0.6, display : 'none', left : 0, top : 0 } }, style : function() { this.$bar.css({ overflow : 'hidden', margin : '4px 0', borderRadius: '2px' }); this.$message.css({ fontSize : '14px', lineHeight: '16px', textAlign : 'center', padding : '10px', width : 'auto', position : 'relative' }); this.$closeButton.css({ position : 'absolute', top : 4, right: 4, width : 10, height: 10, background: "url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAQAAAAnOwc2AAAAxUlEQVR4AR3MPUoDURSA0e++uSkkOxC3IAOWNtaCIDaChfgXBMEZbQRByxCwk+BasgQRZLSYoLgDQbARxry8nyumPcVRKDfd0Aa8AsgDv1zp6pYd5jWOwhvebRTbzNNEw5BSsIpsj/kurQBnmk7sIFcCF5yyZPDRG6trQhujXYosaFoc+2f1MJ89uc76IND6F9BvlXUdpb6xwD2+4q3me3bysiHvtLYrUJto7PD/ve7LNHxSg/woN2kSz4txasBdhyiz3ugPGetTjm3XRokAAAAASUVORK5CYII=)", display : 'none', cursor : 'pointer' }); this.$buttons.css({ padding : 5, textAlign : 'right', borderTop : '1px solid #ccc', backgroundColor: '#fff' }); this.$buttons.find('button').css({ marginLeft: 5 }); this.$buttons.find('button:first').css({ marginLeft: 0 }); this.$bar.on({ mouseenter: function() { $(this).find('.noty_close').stop().fadeTo('normal', 1); }, mouseleave: function() { $(this).find('.noty_close').stop().fadeTo('normal', 0); } }); switch(this.options.layout.name) { case 'top': this.$bar.css({ borderBottom: '2px solid #eee', borderLeft : '2px solid #eee', borderRight : '2px solid #eee', borderTop : '2px solid #eee', boxShadow : "0 2px 4px rgba(0, 0, 0, 0.1)" }); break; case 'topCenter': case 'center': case 'bottomCenter': case 'inline': this.$bar.css({ border : '1px solid #eee', boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)" }); this.$message.css({fontSize: '13px', textAlign: 'center'}); break; case 'topLeft': case 'topRight': case 'bottomLeft': case 'bottomRight': case 'centerLeft': case 'centerRight': this.$bar.css({ border : '1px solid #eee', boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)" }); this.$message.css({fontSize: '13px', textAlign: 'left'}); break; case 'bottom': this.$bar.css({ borderTop : '2px solid #eee', borderLeft : '2px solid #eee', borderRight : '2px solid #eee', borderBottom: '2px solid #eee', boxShadow : "0 -2px 4px rgba(0, 0, 0, 0.1)" }); break; default: this.$bar.css({ border : '2px solid #eee', boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)" }); break; } switch(this.options.type) { case 'alert': case 'notification': this.$bar.css({backgroundColor: '#FFF', borderColor: '#dedede', color: '#444'}); break; case 'warning': this.$bar.css({backgroundColor: '#FFEAA8', borderColor: '#FFC237', color: '#826200'}); this.$buttons.css({borderTop: '1px solid #FFC237'}); break; case 'error': this.$bar.css({backgroundColor: '#FF8181', borderColor: '#e25353', color: '#FFF'}); this.$message.css({fontWeight: 'bold'}); this.$buttons.css({borderTop: '1px solid darkred'}); break; case 'information': this.$bar.css({backgroundColor: '#78C5E7', borderColor: '#3badd6', color: '#FFF'}); this.$buttons.css({borderTop: '1px solid #0B90C4'}); break; case 'success': this.$bar.css({backgroundColor: '#BCF5BC', borderColor: '#7cdd77', color: 'darkgreen'}); this.$buttons.css({borderTop: '1px solid #50C24E'}); break; default: this.$bar.css({backgroundColor: '#FFF', borderColor: '#CCC', color: '#444'}); break; } }, callback: { onShow : function() { }, onClose: function() { } } }; });
dibstigz/myrecipechannel
wp-content/plugins/slider-by-supsystic/src/SupsysticSlider/Slider/assets/js/noty/js/noty/packaged/jquery.noty.packaged.js
JavaScript
gpl-2.0
46,485
// ** I18N // Calendar RU language // Translation: Sly Golovanov, http://golovanov.net, <sly@golovanov.net> // Encoding: any // Distributed under the same terms as the calendar itself. // For translators: please use UTF-8 if possible. We strongly believe that // Unicode is the answer to a real internationalized world. Also please // include your contact information in the header, as can be seen above. // full day names Calendar._DN = new Array ("воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота", "воскресенье"); // Please note that the following array of short day names (and the same goes // for short month names, _SMN) isn't absolutely necessary. We give it here // for exemplification on how one can customize the short day names, but if // they are simply the first N letters of the full name you can simply say: // // Calendar._SDN_len = N; // short day name length // Calendar._SMN_len = N; // short month name length // // If N = 3 then this is not needed either since we assume a value of 3 if not // present, to be compatible with translation files that were written before // this feature. // short day names Calendar._SDN = new Array ("вск", "пон", "втр", "срд", "чет", "пят", "суб", "вск"); // full month names Calendar._MN = new Array ("январь", "февраль", "март", "апрель", "май", "июнь", "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь"); // short month names Calendar._SMN = new Array ("янв", "фев", "мар", "апр", "май", "июн", "июл", "авг", "сен", "окт", "ноя", "дек"); // tooltips Calendar._TT = {}; Calendar._TT["INFO"] = "О календаре..."; Calendar._TT["ABOUT"] = "DHTML Date/Time Selector\n" + "(c) dynarch.com 2002-2003\n" + // don't translate this this ;-) "For latest version visit: http://dynarch.com/mishoo/calendar.epl\n" + "Distributed under GNU LGPL. See http://gnu.org/licenses/lgpl.html for details." + "\n\n" + "Как выбрать дату:\n" + "- При помощи кнопок \xab, \xbb можно выбрать год\n" + "- При помощи кнопок " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " можно выбрать месяц\n" + "- Подержите эти кнопки нажатыми, чтобы появилось меню быстрого выбора."; Calendar._TT["ABOUT_TIME"] = "\n\n" + "Как выбрать время:\n" + "- При клике на часах или минутах они увеличиваются\n" + "- при клике с нажатой клавишей Shift они уменьшаются\n" + "- если нажать и двигать мышкой влево/вправо, они будут меняться быстрее."; Calendar._TT["PREV_YEAR"] = "На год назад (удерживать для меню)"; Calendar._TT["PREV_MONTH"] = "На месяц назад (удерживать для меню)"; Calendar._TT["GO_TODAY"] = "Сегодня"; Calendar._TT["NEXT_MONTH"] = "На месяц вперед (удерживать для меню)"; Calendar._TT["NEXT_YEAR"] = "На год вперед (удерживать для меню)"; Calendar._TT["SEL_DATE"] = "Выберите дату"; Calendar._TT["DRAG_TO_MOVE"] = "Перетаскивайте мышкой"; Calendar._TT["PART_TODAY"] = " (сегодня)"; // the following is to inform that "%s" is to be the first day of week // %s will be replaced with the day name. Calendar._TT["DAY_FIRST"] = "Первый день недели будет %s"; // This may be locale-dependent. It specifies the week-end days, as an array // of comma-separated numbers. The numbers are from 0 to 6: 0 means Sunday, 1 // means Monday, etc. Calendar._TT["WEEKEND"] = "0,6"; Calendar._TT["CLOSE"] = "Закрыть"; Calendar._TT["TODAY"] = "Сегодня"; Calendar._TT["TIME_PART"] = "(Shift-)клик или нажать и двигать"; // date formats Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d"; Calendar._TT["TT_DATE_FORMAT"] = "%e %b, %a"; Calendar._TT["WK"] = "нед"; Calendar._TT["TIME"] = "Время:";
conder/sakai
reference/library/src/webapp/jscalendar/lang/calendar-ru.js
JavaScript
apache-2.0
4,332
const environment = require('./environment') module.exports = environment.toWebpackConfig()
sic2/isamuni
webapp/config/webpack/test.js
JavaScript
mit
93
var camelCase = require("lodash.camelcase"); function dashesCamelCase(str) { return str.replace(/-(\w)/g, function(match, firstLetter) { return firstLetter.toUpperCase(); }); } module.exports = function compileExports(result, importItemMatcher, camelCaseKeys) { if (!Object.keys(result.exports).length) { return ""; } var exportJs = Object.keys(result.exports).reduce(function(res, key) { var valueAsString = JSON.stringify(result.exports[key]); valueAsString = valueAsString.replace(result.importItemRegExpG, importItemMatcher); function addEntry(k) { res.push("\t" + JSON.stringify(k) + ": " + valueAsString); } var targetKey; switch(camelCaseKeys) { case true: addEntry(key); targetKey = camelCase(key); if (targetKey !== key) { addEntry(targetKey); } break; case 'dashes': addEntry(key); targetKey = dashesCamelCase(key); if (targetKey !== key) { addEntry(targetKey); } break; case 'only': addEntry(camelCase(key)); break; case 'dashesOnly': addEntry(dashesCamelCase(key)); break; default: addEntry(key); break; } return res; }, []).join(",\n"); return "{\n" + exportJs + "\n}"; };
puyanLiu/LPYFramework
前端练习/autoFramework/webpack-demo3/node_modules/css-loader/lib/compile-exports.js
JavaScript
apache-2.0
1,329
/* * flickrBomb v1 * www.ZURB.com/playground * Copyright 2011, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ // @param [key] Optionally pass a Flickr API key on instantiation, or just hardcode it below. var flickrBomb = function flickrBomb(key) { if (!(this instanceof flickrBomb)) return new flickrBomb(arguments[0]); var flickrbombAPIkey = key || '66b5c17019403c96779e8fe88d5b576d', // replace with your Flickr API key (fallback) /* flickrbombLicenseTypes values (comma delimited) empty means all license types 0: All Rights Reserved 4: Attribution License http://creativecommons.org/licenses/by/2.0/ 6: Attribution-NoDerivs License http://creativecommons.org/licenses/by-nd/2.0/ 3: Attribution-NonCommercial-NoDerivs License http://creativecommons.org/licenses/by-nc-nd/2.0/ 2: Attribution-NonCommercial License http://creativecommons.org/licenses/by-nc/2.0/ 1: Attribution-NonCommercial-ShareAlike License http://creativecommons.org/licenses/by-nc-sa/2.0/ 5: Attribution-ShareAlike License http://creativecommons.org/licenses/by-sa/2.0/ 7: No known copyright restrictions http://www.flickr.com/commons/usage/ 8: United States Government Work http://www.usa.gov/copyright.shtml ex. flickrbombLicenseTypes = '5,7,8'; */ flickrbombLicenseTypes = '', localStorage, localSync; if (!flickrbombAPIkey) return new Error('flickr API key required'); function supports_local_storage() { try { return 'localStorage' in window && window.localStorage !== null; } catch(e){ return false; } } if (supports_local_storage()) { // A simple module to replace `Backbone.sync` with *localStorage*-based // persistence. Models are given GUIDS, and saved into a JSON object. Simple // as that. // Generate four random hex digits. var S4 = function() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; // Generate a pseudo-GUID by concatenating random hexadecimal. var guid = function() { return (S4()+S4()+'-'+S4()+'-'+S4()+'-'+S4()+'-'+S4()+S4()+S4()); }; // Our Store is represented by a single JS object in *localStorage*. Create it // with a meaningful name, like the name you'd give a table. var Store = function(name) { this.name = name; var store = window.localStorage.getItem(this.name); this.data = (store && JSON.parse(store)) || {}; }; _.extend(Store.prototype, { // Save the current state of the **Store** to *localStorage*. save: function() { window.localStorage.setItem(this.name, JSON.stringify(this.data)); }, // Add a model, giving it a (hopefully)-unique GUID, if it doesn't already // have an id of it's own. create: function(model) { if (!model.id) model.id = model.attributes.id = guid(); this.data[model.id] = model; this.save(); return model; }, // Update a model by replacing its copy in `this.data`. update: function(model) { this.data[model.id] = model; this.save(); return model; }, // Retrieve a model from `this.data` by id. find: function(model) { return this.data[model.id]; }, // Return the array of all models currently in storage. findAll: function() { return _.values(this.data); }, // Delete a model from `this.data`, returning it. destroy: function(model) { delete this.data[model.id]; this.save(); return model; } }); // Override `Model.sync`, `Collection.sync`, or `Backbone.sync` to use delegate to the model or collection's // *localStorage* property, which should be an instance of `Store`. localSync = function(method, model, cb) { var resp, store = model.localStorage || model.collection.localStorage; switch (method) { case 'read': resp = model.id ? store.find(model) : store.findAll(); break; case 'create': resp = store.create(model); break; case 'update': resp = store.update(model); break; case 'delete': resp = store.destroy(model); break; } if (resp && cb && cb.success) { cb.success(resp); } else { // Swallow errors for now // error('Record not found'); } }; localStorage = new Store('flickrBombImages'); } else { localStorage = null; } var FlickrImage = Backbone.Model.extend({ sync: localSync, fullsize_url: function () { return this.image_url('medium'); }, thumb_url: function () { return this.image_url('square'); }, image_url: function (size) { var size_code; switch (size) { case 'square': size_code = '_s'; break; // 75x75 case 'medium': size_code = '_z'; break; // 640 on the longest side case 'large': size_code = '_b'; break; // 1024 on the longest side default: size_code = ''; } return 'http://farm' + this.get('farm') + '.static.flickr.com/' + this.get('server') + '/' + this.get('id') + '_' + this.get('secret') + size_code + '.jpg'; } }), Image = Backbone.Model.extend({ sync: localSync, localStorage: localStorage, initialize: function () { _.bindAll(this, 'loadFirstImage'); this.flickrImages = new FlickrImages(); this.flickrImages.fetch(this.get('keywords'), this.loadFirstImage); this.set({id: this.get('id') || this.get('keywords')}); this.bind('change:src', this.changeSrc); }, changeSrc: function () { this.save(); }, loadFirstImage: function () { if (this.get('src') === undefined) { this.set({src: this.flickrImages.first().image_url()}); } } }), FlickrImages = Backbone.Collection.extend({ sync: localSync, model: FlickrImage, key: flickrbombAPIkey, page: 1, fetch: function (keywords, success) { var self = this; success = success || $.noop; this.keywords = keywords || this.keywords; $.ajax({ url: 'http://api.flickr.com/services/rest/', data: { api_key: self.key, format: 'json', method: 'flickr.photos.search', tags: this.keywords, per_page: 9, page: this.page, license: flickrbombLicenseTypes }, dataType: 'jsonp', jsonp: 'jsoncallback', success: function (response) { self.add(response.photos.photo); success(); } }); }, nextPage: function (callback) { this.page += 1; this.remove(this.models); this.fetch(null, callback); }, prevPage: function(callback) { if (this.page > 1) {this.page -= 1;} this.remove(this.models); this.fetch(null, callback); } }), FlickrImageView = Backbone.View.extend({ tagName: 'a', template: _.template("<img src='<%= thumb_url() %>' />"), className: 'photo', events: {'click': 'setImageSrc'}, render: function() { $(this.el).html(this.template(this.model)); $(this.el).addClass('photo'); return this; }, setImageSrc: function (event) { this.options.image.set({'src': this.model.fullsize_url()}); } }), ImageView = Backbone.View.extend({ tagName: 'div', className: 'flickrbombContainer', lock: false, template: _.template('<div id="<%= id %>" class="flickrbombWrapper"><img class="flickrbomb" src="" /><a href="#" title="Setup" class="setupIcon"></a></div><div class="flickrbombFlyout"><div class="flickrbombContent"><a href="#" title="Previous Page" class="prev">&#9664;</a><a href="#" title="Next Page" class="next">&#9654;</a></div></div>'), initialize: function (options) { _.bindAll(this, 'addImage', 'updateSrc', 'setDimentions', 'updateDimentions'); var keywords = options.img.attr('src').replace('flickr://', ''); this.$el = $(this.el); this.ratio = this.options.img.attr('data-ratio'); this.image = new Image({keywords: keywords, id: options.img.attr('id')}); this.image.flickrImages.bind('add', this.addImage); this.image.bind('change:src', this.updateSrc); }, events: { 'click .setupIcon' : 'clickSetup', 'click .flickrbombFlyout a.photo' : 'selectImage', 'click .flickrbombFlyout a.next' : 'nextFlickrPhotos', 'click .flickrbombFlyout a.prev' : 'prevFlickrPhotos' }, render: function() { $(this.el).html(this.template({ id: this.image.id.replace(' ', '') })); this.image.fetch(); if (!this.ratio) { this.resize(); } else { this.$('.flickrbombWrapper').append('<img style="width: 100%;" class="placeholder" src="http://placehold.it/' + this.ratio + '" />'); } return this; }, updateSrc: function (model, src) { var self = this; this.$('img.flickrbomb') .css({top: 'auto', left: 'auto', width: 'auto', height: 'auto'}) .attr('src', '') .bind('load', self.setDimentions) .attr('src', src); }, setDimentions: function (event) { this.image.set({ width: this.$('img').width(), height: this.$('img').height() }); this.updateDimentions(this.image); $(event.target).unbind('load'); }, updateDimentions: function () { var image = this.$('img.flickrbomb'), flickrWidth = this.image.get('width'), flickrHeight = this.image.get('height'), flickrAspectRatio = flickrWidth / flickrHeight, clientWidth = this.$('div.flickrbombWrapper').width(), clientHeight = this.$('div.flickrbombWrapper').height(), clientAspectRatio = clientWidth / clientHeight; if (flickrAspectRatio < clientAspectRatio) { image.css({ width: '100%', height: null }); image.css({ top: ((clientHeight - image.height()) / 2) + 'px', left: null }); } else { image.css({ height: '100%', width: null }); image.css({ left: ((clientWidth - image.width()) / 2) + 'px', top: null }); } }, addImage: function (image) { this.flickrImageView = new FlickrImageView({model: image, image: this.image}); this.$('.flickrbombFlyout').append(this.flickrImageView.render().el); }, clickSetup: function (event) { event.preventDefault(); this.toggleFlyout(); }, toggleFlyout: function (event) { this.$('.flickrbombFlyout').toggle(); }, selectImage: function (event) { event.preventDefault(); this.toggleFlyout(); }, nextFlickrPhotos: function (event) { event.preventDefault(); var self = this; if(!this.lock) { this.lock = true; this.$('.flickrbombFlyout').find('a.photo').remove(); this.image.flickrImages.nextPage(function() { self.lock = false; }); } }, prevFlickrPhotos: function (event) { event.preventDefault(); var self = this; if(!this.lock) { this.lock = true; this.$('.flickrbombFlyout').find('a.photo').remove(); this.image.flickrImages.prevPage(function() { self.lock = false; }); } }, resize: function () { this.$('div.flickrbombWrapper').css({ width: this.width() + 'px', height: this.height() + 'px' }); }, width: function () { return parseInt(this.options.img.width(), 10); }, height: function () { return parseInt(this.options.img.height(), 10); } }); // Replace any placeholders with flickr images this.bomb = function() { var self = this; $("img[src^='flickr://']").each(function () { var img = $(this), imageView = new ImageView({img: img}); img.replaceWith(imageView.render().el); }); }; // Listener to close any open flickrbomb menus if you click on body $('body').click(function(event) { if (!$(event.target).closest('.setupIcon').length && !$(event.target).closest('.flickrbombFlyout').length) { $('.flickrbombFlyout').hide(); } }); }; // Bomb on sight! Just on include. if ($("img[src^='flickr://']").length) flickrBomb().bomb();
cliftonc0613/My-Responsive-Style-Tile
js/libs/flickrbomb.js
JavaScript
gpl-2.0
15,304
/** * @license AngularJS v1.0.0 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) { 'use strict'; /** * @ngdoc overview * @name ngCookies */ angular.module('ngCookies', ['ng']). /** * @ngdoc object * @name ngCookies.$cookies * @requires $browser * * @description * Provides read/write access to browser's cookies. * * Only a simple Object is exposed and by adding or removing properties to/from * this object, new cookies are created/deleted at the end of current $eval. * * @example */ factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) { var cookies = {}, lastCookies = {}, lastBrowserCookies, runEval = false, copy = angular.copy, isUndefined = angular.isUndefined; //creates a poller fn that copies all cookies from the $browser to service & inits the service $browser.addPollFn(function() { var currentCookies = $browser.cookies(); if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl lastBrowserCookies = currentCookies; copy(currentCookies, lastCookies); copy(currentCookies, cookies); if (runEval) $rootScope.$apply(); } })(); runEval = true; //at the end of each eval, push cookies //TODO: this should happen before the "delayed" watches fire, because if some cookies are not // strings or browser refuses to store some cookies, we update the model in the push fn. $rootScope.$watch(push); return cookies; /** * Pushes all the cookies from the service to the browser and verifies if all cookies were stored. */ function push() { var name, value, browserCookies, updated; //delete any cookies deleted in $cookies for (name in lastCookies) { if (isUndefined(cookies[name])) { $browser.cookies(name, undefined); } } //update all cookies updated in $cookies for(name in cookies) { value = cookies[name]; if (!angular.isString(value)) { if (angular.isDefined(lastCookies[name])) { cookies[name] = lastCookies[name]; } else { delete cookies[name]; } } else if (value !== lastCookies[name]) { $browser.cookies(name, value); updated = true; } } //verify what was actually stored if (updated){ updated = false; browserCookies = $browser.cookies(); for (name in cookies) { if (cookies[name] !== browserCookies[name]) { //delete or reset all cookies that the browser dropped from $cookies if (isUndefined(browserCookies[name])) { delete cookies[name]; } else { cookies[name] = browserCookies[name]; } updated = true; } } } } }]). /** * @ngdoc object * @name ngCookies.$cookieStore * @requires $cookies * * @description * Provides a key-value (string-object) storage, that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or * deserialized by angular's toJson/fromJson. * @example */ factory('$cookieStore', ['$cookies', function($cookies) { return { /** * @ngdoc method * @name ngCookies.$cookieStore#get * @methodOf ngCookies.$cookieStore * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value. */ get: function(key) { return angular.fromJson($cookies[key]); }, /** * @ngdoc method * @name ngCookies.$cookieStore#put * @methodOf ngCookies.$cookieStore * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. */ put: function(key, value) { $cookies[key] = angular.toJson(value); }, /** * @ngdoc method * @name ngCookies.$cookieStore#remove * @methodOf ngCookies.$cookieStore * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. */ remove: function(key) { delete $cookies[key]; } }; }]); })(window, window.angular);
clemsos/mitras
ui/public/libs/angular/angular-cookies.js
JavaScript
mit
4,842
var Writable = require('readable-stream').Writable var inherits = require('inherits') var TA = require('typedarray') var U8 = typeof Uint8Array !== 'undefined' ? Uint8Array : TA.Uint8Array function ConcatStream(opts, cb) { if (!(this instanceof ConcatStream)) return new ConcatStream(opts, cb) if (typeof opts === 'function') { cb = opts opts = {} } if (!opts) opts = {} var encoding = opts.encoding var shouldInferEncoding = false if (!encoding) { shouldInferEncoding = true } else { encoding = String(encoding).toLowerCase() if (encoding === 'u8' || encoding === 'uint8') { encoding = 'uint8array' } } Writable.call(this, { objectMode: true }) this.encoding = encoding this.shouldInferEncoding = shouldInferEncoding if (cb) this.on('finish', function () { cb(this.getBody()) }) this.body = [] } module.exports = ConcatStream inherits(ConcatStream, Writable) ConcatStream.prototype._write = function(chunk, enc, next) { this.body.push(chunk) next() } ConcatStream.prototype.inferEncoding = function (buff) { var firstBuffer = buff || this.body[0] if (!firstBuffer) return 'buffer' if (Buffer.isBuffer(firstBuffer)) return 'buffer' if (firstBuffer instanceof Uint8Array) return 'uint8array' if (Array.isArray(firstBuffer)) return 'array' if (typeof firstBuffer === 'string') return 'string' if (Object.prototype.toString.call(firstBuffer) === "[object Object]") return 'object' return 'buffer' } ConcatStream.prototype.getBody = function () { if (this.shouldInferEncoding) this.encoding = this.inferEncoding() if (this.encoding === 'array') return arrayConcat(this.body) if (this.encoding === 'string') return stringConcat(this.body) if (this.encoding === 'buffer') return bufferConcat(this.body) if (this.encoding === 'uint8array') return u8Concat(this.body) return this.body } var isArray = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]' } function isArrayish (arr) { return /Array\]$/.test(Object.prototype.toString.call(arr)) } function stringConcat (parts) { var strings = [] for (var i = 0; i < parts.length; i++) { var p = parts[i] if (typeof p === 'string') { strings.push(p) } else if (Buffer.isBuffer(p)) { strings.push(p.toString('utf8')) } else { strings.push(Buffer(p).toString('utf8')) } } return strings.join('') } function bufferConcat (parts) { var bufs = [] for (var i = 0; i < parts.length; i++) { var p = parts[i] if (Buffer.isBuffer(p)) { bufs.push(p) } else if (typeof p === 'string' || isArrayish(p) || (p && typeof p.subarray === 'function')) { bufs.push(Buffer(p)) } else bufs.push(Buffer(String(p))) } return Buffer.concat(bufs) } function arrayConcat (parts) { var res = [] for (var i = 0; i < parts.length; i++) { res.push.apply(res, parts[i]) } return res } function u8Concat (parts) { var len = 0 for (var i = 0; i < parts.length; i++) { if (typeof parts[i] === 'string') { parts[i] = Buffer(parts[i]) } len += parts[i].length } var u8 = new U8(len) for (var i = 0, offset = 0; i < parts.length; i++) { var part = parts[i] for (var j = 0; j < part.length; j++) { u8[offset++] = part[j] } } return u8 }
pepoviola/cartero
test/example2/node_modules/browserify/node_modules/concat-stream/index.js
JavaScript
mit
3,342
module.exports = require('./test.css!');
webcoding/systemjs
test/tests/cjs-loading-plugin.js
JavaScript
mit
40
/*! * # Semantic UI 2.0.4 - State * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.state = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', hasTouch = ('ontouchstart' in document.documentElement), time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.state.settings, parameters) : $.extend({}, $.fn.state.settings), error = settings.error, metadata = settings.metadata, className = settings.className, namespace = settings.namespace, states = settings.states, text = settings.text, eventNamespace = '.' + namespace, moduleNamespace = namespace + '-module', $module = $(this), element = this, instance = $module.data(moduleNamespace), module ; module = { initialize: function() { module.verbose('Initializing module'); // allow module to guess desired state based on element if(settings.automatic) { module.add.defaults(); } // bind events with delegated events if(settings.context && moduleSelector !== '') { $(settings.context) .on(moduleSelector, 'mouseenter' + eventNamespace, module.change.text) .on(moduleSelector, 'mouseleave' + eventNamespace, module.reset.text) .on(moduleSelector, 'click' + eventNamespace, module.toggle.state) ; } else { $module .on('mouseenter' + eventNamespace, module.change.text) .on('mouseleave' + eventNamespace, module.reset.text) .on('click' + eventNamespace, module.toggle.state) ; } module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying previous module', instance); $module .off(eventNamespace) .removeData(moduleNamespace) ; }, refresh: function() { module.verbose('Refreshing selector cache'); $module = $(element); }, add: { defaults: function() { var userStates = parameters && $.isPlainObject(parameters.states) ? parameters.states : {} ; $.each(settings.defaults, function(type, typeStates) { if( module.is[type] !== undefined && module.is[type]() ) { module.verbose('Adding default states', type, element); $.extend(settings.states, typeStates, userStates); } }); } }, is: { active: function() { return $module.hasClass(className.active); }, loading: function() { return $module.hasClass(className.loading); }, inactive: function() { return !( $module.hasClass(className.active) ); }, state: function(state) { if(className[state] === undefined) { return false; } return $module.hasClass( className[state] ); }, enabled: function() { return !( $module.is(settings.filter.active) ); }, disabled: function() { return ( $module.is(settings.filter.active) ); }, textEnabled: function() { return !( $module.is(settings.filter.text) ); }, // definitions for automatic type detection button: function() { return $module.is('.button:not(a, .submit)'); }, input: function() { return $module.is('input'); }, progress: function() { return $module.is('.ui.progress'); } }, allow: function(state) { module.debug('Now allowing state', state); states[state] = true; }, disallow: function(state) { module.debug('No longer allowing', state); states[state] = false; }, allows: function(state) { return states[state] || false; }, enable: function() { $module.removeClass(className.disabled); }, disable: function() { $module.addClass(className.disabled); }, setState: function(state) { if(module.allows(state)) { $module.addClass( className[state] ); } }, removeState: function(state) { if(module.allows(state)) { $module.removeClass( className[state] ); } }, toggle: { state: function() { var apiRequest, requestCancelled ; if( module.allows('active') && module.is.enabled() ) { module.refresh(); if($.fn.api !== undefined) { apiRequest = $module.api('get request'); requestCancelled = $module.api('was cancelled'); if( requestCancelled ) { module.debug('API Request cancelled by beforesend'); settings.activateTest = function(){ return false; }; settings.deactivateTest = function(){ return false; }; } else if(apiRequest) { module.listenTo(apiRequest); return; } } module.change.state(); } } }, listenTo: function(apiRequest) { module.debug('API request detected, waiting for state signal', apiRequest); if(apiRequest) { if(text.loading) { module.update.text(text.loading); } $.when(apiRequest) .then(function() { if(apiRequest.state() == 'resolved') { module.debug('API request succeeded'); settings.activateTest = function(){ return true; }; settings.deactivateTest = function(){ return true; }; } else { module.debug('API request failed'); settings.activateTest = function(){ return false; }; settings.deactivateTest = function(){ return false; }; } module.change.state(); }) ; } }, // checks whether active/inactive state can be given change: { state: function() { module.debug('Determining state change direction'); // inactive to active change if( module.is.inactive() ) { module.activate(); } else { module.deactivate(); } if(settings.sync) { module.sync(); } settings.onChange.call(element); }, text: function() { if( module.is.textEnabled() ) { if(module.is.disabled() ) { module.verbose('Changing text to disabled text', text.hover); module.update.text(text.disabled); } else if( module.is.active() ) { if(text.hover) { module.verbose('Changing text to hover text', text.hover); module.update.text(text.hover); } else if(text.deactivate) { module.verbose('Changing text to deactivating text', text.deactivate); module.update.text(text.deactivate); } } else { if(text.hover) { module.verbose('Changing text to hover text', text.hover); module.update.text(text.hover); } else if(text.activate){ module.verbose('Changing text to activating text', text.activate); module.update.text(text.activate); } } } } }, activate: function() { if( settings.activateTest.call(element) ) { module.debug('Setting state to active'); $module .addClass(className.active) ; module.update.text(text.active); settings.onActivate.call(element); } }, deactivate: function() { if( settings.deactivateTest.call(element) ) { module.debug('Setting state to inactive'); $module .removeClass(className.active) ; module.update.text(text.inactive); settings.onDeactivate.call(element); } }, sync: function() { module.verbose('Syncing other buttons to current state'); if( module.is.active() ) { $allModules .not($module) .state('activate'); } else { $allModules .not($module) .state('deactivate') ; } }, get: { text: function() { return (settings.selector.text) ? $module.find(settings.selector.text).text() : $module.html() ; }, textFor: function(state) { return text[state] || false; } }, flash: { text: function(text, duration, callback) { var previousText = module.get.text() ; module.debug('Flashing text message', text, duration); text = text || settings.text.flash; duration = duration || settings.flashDuration; callback = callback || function() {}; module.update.text(text); setTimeout(function(){ module.update.text(previousText); callback.call(element); }, duration); } }, reset: { // on mouseout sets text to previous value text: function() { var activeText = text.active || $module.data(metadata.storedText), inactiveText = text.inactive || $module.data(metadata.storedText) ; if( module.is.textEnabled() ) { if( module.is.active() && activeText) { module.verbose('Resetting active text', activeText); module.update.text(activeText); } else if(inactiveText) { module.verbose('Resetting inactive text', activeText); module.update.text(inactiveText); } } } }, update: { text: function(text) { var currentText = module.get.text() ; if(text && text !== currentText) { module.debug('Updating text', text); if(settings.selector.text) { $module .data(metadata.storedText, text) .find(settings.selector.text) .text(text) ; } else { $module .data(metadata.storedText, text) .html(text) ; } } else { module.debug('Text is already set, ignoring update', text); } } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.state.settings = { // module info name : 'State', // debug output debug : false, // verbose debug output verbose : false, // namespace for events namespace : 'state', // debug data includes performance performance : true, // callback occurs on state change onActivate : function() {}, onDeactivate : function() {}, onChange : function() {}, // state test functions activateTest : function() { return true; }, deactivateTest : function() { return true; }, // whether to automatically map default states automatic : true, // activate / deactivate changes all elements instantiated at same time sync : false, // default flash text duration, used for temporarily changing text of an element flashDuration : 1000, // selector filter filter : { text : '.loading, .disabled', active : '.disabled' }, context : false, // error error: { beforeSend : 'The before send function has cancelled state change', method : 'The method you called is not defined.' }, // metadata metadata: { promise : 'promise', storedText : 'stored-text' }, // change class on state className: { active : 'active', disabled : 'disabled', error : 'error', loading : 'loading', success : 'success', warning : 'warning' }, selector: { // selector for text node text: false }, defaults : { input: { disabled : true, loading : true, active : true }, button: { disabled : true, loading : true, active : true, }, progress: { active : true, success : true, warning : true, error : true } }, states : { active : true, disabled : true, error : true, loading : true, success : true, warning : true }, text : { disabled : false, flash : false, hover : false, active : false, inactive : false, activate : false, deactivate : false } }; })( jQuery, window , document );
tisderek/cleansweep
public/semantic/components/state.js
JavaScript
mit
20,409
MessageFormat.locale.sv=function(n){return n===1?"one":"other"}
josedab/spring-boot-angularjs-examples
videostore/src/main/webapp/bower_components/messageformat/locale/sv.js
JavaScript
mit
64
!function(t){"use strict";function e(e){function n(t,e){t&&e&&i[t]&&(i[t]=e)}function o(t){if(t&&i[t])return i[t]}function u(t,r,n,u){var i;if(n=e(n,r))return((i=o(n[1]))&&i[t]||o("general")[t])(r,n,u)}var i={general:{get:function(e,r){return t(e,null).getPropertyValue(r[0])},set:function(t,e,n){n.replace?t.style.setProperty(e[0],n.replace(r,"")||n,r.test(n)?"important":""):t.style[e[1]]=n}}};return{add:n,get:o,process:u}}var r=/\s*!important$/;provide(["../support/css/property"],e)}(getComputedStyle); //# sourceMappingURL=css.js.map
Asaf-S/jsdelivr
files/qoopido.nucleus/3.0.5/hooks/css.js
JavaScript
mit
540
;(function(exports) { // export the class if we are in a Node-like system. if (typeof module === 'object' && module.exports === exports) exports = module.exports = SemVer; // The debug function is excluded entirely from the minified version. // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. exports.SEMVER_SPEC_VERSION = '2.0.0'; // The actual regexps go on exports.re var re = exports.re = []; var src = exports.src = []; var R = 0; // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. var NUMERICIDENTIFIER = R++; src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; var NUMERICIDENTIFIERLOOSE = R++; src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. var NONNUMERICIDENTIFIER = R++; src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version // Three dot-separated numeric identifiers. var MAINVERSION = R++; src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')'; var MAINVERSIONLOOSE = R++; src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. var PRERELEASEIDENTIFIER = R++; src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')'; var PRERELEASEIDENTIFIERLOOSE = R++; src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. var PRERELEASE = R++; src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; var PRERELEASELOOSE = R++; src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. var BUILDIDENTIFIER = R++; src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. var BUILD = R++; src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. var FULL = R++; var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?'; src[FULL] = '^' + FULLPLAIN + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?'; var LOOSE = R++; src[LOOSE] = '^' + LOOSEPLAIN + '$'; var GTLT = R++; src[GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. var XRANGEIDENTIFIERLOOSE = R++; src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; var XRANGEIDENTIFIER = R++; src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; var XRANGEPLAIN = R++; src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:(' + src[PRERELEASE] + ')' + ')?)?)?'; var XRANGEPLAINLOOSE = R++; src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:(' + src[PRERELEASELOOSE] + ')' + ')?)?)?'; // >=2.x, for example, means >=2.0.0-0 // <1.x would be the same as "<1.0.0-0", though. var XRANGE = R++; src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; var XRANGELOOSE = R++; src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; // Tilde ranges. // Meaning is "reasonably at or greater than" var LONETILDE = R++; src[LONETILDE] = '(?:~>?)'; var TILDETRIM = R++; src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); var tildeTrimReplace = '$1~'; var TILDE = R++; src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; var TILDELOOSE = R++; src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; // Caret ranges. // Meaning is "at least and backwards compatible with" var LONECARET = R++; src[LONECARET] = '(?:\\^)'; var CARETTRIM = R++; src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); var caretTrimReplace = '$1^'; var CARET = R++; src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; var CARETLOOSE = R++; src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version" var COMPARATORLOOSE = R++; src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; var COMPARATOR = R++; src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` var COMPARATORTRIM = R++; src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; // this one has to use the /g flag re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. var HYPHENRANGE = R++; src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$'; var HYPHENRANGELOOSE = R++; src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all. var STAR = R++; src[STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects. // All are flag-free, unless they were created above with a flag. for (var i = 0; i < R; i++) { ; if (!re[i]) re[i] = new RegExp(src[i]); } exports.parse = parse; function parse(version, loose) { var r = loose ? re[LOOSE] : re[FULL]; return (r.test(version)) ? new SemVer(version, loose) : null; } exports.valid = valid; function valid(version, loose) { var v = parse(version, loose); return v ? v.version : null; } exports.clean = clean; function clean(version, loose) { var s = parse(version, loose); return s ? s.version : null; } exports.SemVer = SemVer; function SemVer(version, loose) { if (version instanceof SemVer) { if (version.loose === loose) return version; else version = version.version; } else if (typeof version !== 'string') { throw new TypeError('Invalid Version: ' + version); } if (!(this instanceof SemVer)) return new SemVer(version, loose); ; this.loose = loose; var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); if (!m) throw new TypeError('Invalid Version: ' + version); this.raw = version; // these are actually numbers this.major = +m[1]; this.minor = +m[2]; this.patch = +m[3]; // numberify any prerelease numeric ids if (!m[4]) this.prerelease = []; else this.prerelease = m[4].split('.').map(function(id) { return (/^[0-9]+$/.test(id)) ? +id : id; }); this.build = m[5] ? m[5].split('.') : []; this.format(); } SemVer.prototype.format = function() { this.version = this.major + '.' + this.minor + '.' + this.patch; if (this.prerelease.length) this.version += '-' + this.prerelease.join('.'); return this.version; }; SemVer.prototype.inspect = function() { return '<SemVer "' + this + '">'; }; SemVer.prototype.toString = function() { return this.version; }; SemVer.prototype.compare = function(other) { ; if (!(other instanceof SemVer)) other = new SemVer(other, this.loose); return this.compareMain(other) || this.comparePre(other); }; SemVer.prototype.compareMain = function(other) { if (!(other instanceof SemVer)) other = new SemVer(other, this.loose); return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); }; SemVer.prototype.comparePre = function(other) { if (!(other instanceof SemVer)) other = new SemVer(other, this.loose); // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) return -1; else if (!this.prerelease.length && other.prerelease.length) return 1; else if (!this.prerelease.length && !other.prerelease.length) return 0; var i = 0; do { var a = this.prerelease[i]; var b = other.prerelease[i]; ; if (a === undefined && b === undefined) return 0; else if (b === undefined) return 1; else if (a === undefined) return -1; else if (a === b) continue; else return compareIdentifiers(a, b); } while (++i); }; // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. SemVer.prototype.inc = function(release) { switch (release) { case 'premajor': this.inc('major'); this.inc('pre'); break; case 'preminor': this.inc('minor'); this.inc('pre'); break; case 'prepatch': this.inc('patch'); this.inc('pre'); break; // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) this.inc('patch'); this.inc('pre'); break; case 'major': this.major++; this.minor = -1; case 'minor': this.minor++; this.patch = 0; this.prerelease = []; break; case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) this.patch++; this.prerelease = []; break; // This probably shouldn't be used publically. // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. case 'pre': if (this.prerelease.length === 0) this.prerelease = [0]; else { var i = this.prerelease.length; while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++; i = -2; } } if (i === -1) // didn't increment anything this.prerelease.push(0); } break; default: throw new Error('invalid increment argument: ' + release); } this.format(); return this; }; exports.inc = inc; function inc(version, release, loose) { try { return new SemVer(version, loose).inc(release).version; } catch (er) { return null; } } exports.compareIdentifiers = compareIdentifiers; var numeric = /^[0-9]+$/; function compareIdentifiers(a, b) { var anum = numeric.test(a); var bnum = numeric.test(b); if (anum && bnum) { a = +a; b = +b; } return (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : a > b ? 1 : 0; } exports.rcompareIdentifiers = rcompareIdentifiers; function rcompareIdentifiers(a, b) { return compareIdentifiers(b, a); } exports.compare = compare; function compare(a, b, loose) { return new SemVer(a, loose).compare(b); } exports.compareLoose = compareLoose; function compareLoose(a, b) { return compare(a, b, true); } exports.rcompare = rcompare; function rcompare(a, b, loose) { return compare(b, a, loose); } exports.sort = sort; function sort(list, loose) { return list.sort(function(a, b) { return exports.compare(a, b, loose); }); } exports.rsort = rsort; function rsort(list, loose) { return list.sort(function(a, b) { return exports.rcompare(a, b, loose); }); } exports.gt = gt; function gt(a, b, loose) { return compare(a, b, loose) > 0; } exports.lt = lt; function lt(a, b, loose) { return compare(a, b, loose) < 0; } exports.eq = eq; function eq(a, b, loose) { return compare(a, b, loose) === 0; } exports.neq = neq; function neq(a, b, loose) { return compare(a, b, loose) !== 0; } exports.gte = gte; function gte(a, b, loose) { return compare(a, b, loose) >= 0; } exports.lte = lte; function lte(a, b, loose) { return compare(a, b, loose) <= 0; } exports.cmp = cmp; function cmp(a, op, b, loose) { var ret; switch (op) { case '===': ret = a === b; break; case '!==': ret = a !== b; break; case '': case '=': case '==': ret = eq(a, b, loose); break; case '!=': ret = neq(a, b, loose); break; case '>': ret = gt(a, b, loose); break; case '>=': ret = gte(a, b, loose); break; case '<': ret = lt(a, b, loose); break; case '<=': ret = lte(a, b, loose); break; default: throw new TypeError('Invalid operator: ' + op); } return ret; } exports.Comparator = Comparator; function Comparator(comp, loose) { if (comp instanceof Comparator) { if (comp.loose === loose) return comp; else comp = comp.value; } if (!(this instanceof Comparator)) return new Comparator(comp, loose); ; this.loose = loose; this.parse(comp); if (this.semver === ANY) this.value = ''; else this.value = this.operator + this.semver.version; } var ANY = {}; Comparator.prototype.parse = function(comp) { var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; var m = comp.match(r); if (!m) throw new TypeError('Invalid comparator: ' + comp); this.operator = m[1]; // if it literally is just '>' or '' then allow anything. if (!m[2]) this.semver = ANY; else { this.semver = new SemVer(m[2], this.loose); // <1.2.3-rc DOES allow 1.2.3-beta (has prerelease) // >=1.2.3 DOES NOT allow 1.2.3-beta // <=1.2.3 DOES allow 1.2.3-beta // However, <1.2.3 does NOT allow 1.2.3-beta, // even though `1.2.3-beta < 1.2.3` // The assumption is that the 1.2.3 version has something you // *don't* want, so we push the prerelease down to the minimum. if (this.operator === '<' && !this.semver.prerelease.length) { this.semver.prerelease = ['0']; this.semver.format(); } } }; Comparator.prototype.inspect = function() { return '<SemVer Comparator "' + this + '">'; }; Comparator.prototype.toString = function() { return this.value; }; Comparator.prototype.test = function(version) { ; return (this.semver === ANY) ? true : cmp(version, this.operator, this.semver, this.loose); }; exports.Range = Range; function Range(range, loose) { if ((range instanceof Range) && range.loose === loose) return range; if (!(this instanceof Range)) return new Range(range, loose); this.loose = loose; // First, split based on boolean or || this.raw = range; this.set = range.split(/\s*\|\|\s*/).map(function(range) { return this.parseRange(range.trim()); }, this).filter(function(c) { // throw out any that are not relevant for whatever reason return c.length; }); if (!this.set.length) { throw new TypeError('Invalid SemVer Range: ' + range); } this.format(); } Range.prototype.inspect = function() { return '<SemVer Range "' + this.range + '">'; }; Range.prototype.format = function() { this.range = this.set.map(function(comps) { return comps.join(' ').trim(); }).join('||').trim(); return this.range; }; Range.prototype.toString = function() { return this.range; }; Range.prototype.parseRange = function(range) { var loose = this.loose; range = range.trim(); ; // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; range = range.replace(hr, hyphenReplace); ; // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); ; // `~ 1.2.3` => `~1.2.3` range = range.replace(re[TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3` range = range.replace(re[CARETTRIM], caretTrimReplace); // normalize spaces range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and // ready to be split into comparators. var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; var set = range.split(' ').map(function(comp) { return parseComparator(comp, loose); }).join(' ').split(/\s+/); if (this.loose) { // in loose mode, throw out any that are not valid comparators set = set.filter(function(comp) { return !!comp.match(compRe); }); } set = set.map(function(comp) { return new Comparator(comp, loose); }); return set; }; // Mostly just for testing and legacy API reasons exports.toComparators = toComparators; function toComparators(range, loose) { return new Range(range, loose).set.map(function(comp) { return comp.map(function(c) { return c.value; }).join(' ').trim().split(' '); }); } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. function parseComparator(comp, loose) { ; comp = replaceCarets(comp, loose); ; comp = replaceTildes(comp, loose); ; comp = replaceXRanges(comp, loose); ; comp = replaceStars(comp, loose); ; return comp; } function isX(id) { return !id || id.toLowerCase() === 'x' || id === '*'; } // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 function replaceTildes(comp, loose) { return comp.trim().split(/\s+/).map(function(comp) { return replaceTilde(comp, loose); }).join(' '); } function replaceTilde(comp, loose) { var r = loose ? re[TILDELOOSE] : re[TILDE]; return comp.replace(r, function(_, M, m, p, pr) { ; var ret; if (isX(M)) ret = ''; else if (isX(m)) ret = '>=' + M + '.0.0-0 <' + (+M + 1) + '.0.0-0'; else if (isX(p)) // ~1.2 == >=1.2.0- <1.3.0- ret = '>=' + M + '.' + m + '.0-0 <' + M + '.' + (+m + 1) + '.0-0'; else if (pr) { ; if (pr.charAt(0) !== '-') pr = '-' + pr; ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0-0'; } else // ~1.2.3 == >=1.2.3-0 <1.3.0-0 ret = '>=' + M + '.' + m + '.' + p + '-0' + ' <' + M + '.' + (+m + 1) + '.0-0'; ; return ret; }); } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 // ^1.2.3 --> >=1.2.3 <2.0.0 // ^1.2.0 --> >=1.2.0 <2.0.0 function replaceCarets(comp, loose) { return comp.trim().split(/\s+/).map(function(comp) { return replaceCaret(comp, loose); }).join(' '); } function replaceCaret(comp, loose) { var r = loose ? re[CARETLOOSE] : re[CARET]; return comp.replace(r, function(_, M, m, p, pr) { ; var ret; if (isX(M)) ret = ''; else if (isX(m)) ret = '>=' + M + '.0.0-0 <' + (+M + 1) + '.0.0-0'; else if (isX(p)) { if (M === '0') ret = '>=' + M + '.' + m + '.0-0 <' + M + '.' + (+m + 1) + '.0-0'; else ret = '>=' + M + '.' + m + '.0-0 <' + (+M + 1) + '.0.0-0'; } else if (pr) { ; if (pr.charAt(0) !== '-') pr = '-' + pr; if (M === '0') { if (m === '0') ret = '=' + M + '.' + m + '.' + p + pr; else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0-0'; } else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + (+M + 1) + '.0.0-0'; } else { if (M === '0') { if (m === '0') ret = '=' + M + '.' + m + '.' + p; else ret = '>=' + M + '.' + m + '.' + p + '-0' + ' <' + M + '.' + (+m + 1) + '.0-0'; } else ret = '>=' + M + '.' + m + '.' + p + '-0' + ' <' + (+M + 1) + '.0.0-0'; } ; return ret; }); } function replaceXRanges(comp, loose) { ; return comp.split(/\s+/).map(function(comp) { return replaceXRange(comp, loose); }).join(' '); } function replaceXRange(comp, loose) { comp = comp.trim(); var r = loose ? re[XRANGELOOSE] : re[XRANGE]; return comp.replace(r, function(ret, gtlt, M, m, p, pr) { ; var xM = isX(M); var xm = xM || isX(m); var xp = xm || isX(p); var anyX = xp; if (gtlt === '=' && anyX) gtlt = ''; if (gtlt && anyX) { // replace X with 0, and then append the -0 min-prerelease if (xM) M = 0; if (xm) m = 0; if (xp) p = 0; if (gtlt === '>') { // >1 => >=2.0.0-0 // >1.2 => >=1.3.0-0 // >1.2.3 => >= 1.2.4-0 gtlt = '>='; if (xM) { // no change } else if (xm) { M = +M + 1; m = 0; p = 0; } else if (xp) { m = +m + 1; p = 0; } } ret = gtlt + M + '.' + m + '.' + p + '-0'; } else if (xM) { // allow any ret = '*'; } else if (xm) { // append '-0' onto the version, otherwise // '1.x.x' matches '2.0.0-beta', since the tag // *lowers* the version value ret = '>=' + M + '.0.0-0 <' + (+M + 1) + '.0.0-0'; } else if (xp) { ret = '>=' + M + '.' + m + '.0-0 <' + M + '.' + (+m + 1) + '.0-0'; } ; return ret; }); } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. function replaceStars(comp, loose) { ; // Looseness is ignored here. star is always as loose as it gets! return comp.trim().replace(re[STAR], ''); } // This function is passed to string.replace(re[HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0-0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0-0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0-0 <3.5.0-0 function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { if (isX(fM)) from = ''; else if (isX(fm)) from = '>=' + fM + '.0.0-0'; else if (isX(fp)) from = '>=' + fM + '.' + fm + '.0-0'; else from = '>=' + from; if (isX(tM)) to = ''; else if (isX(tm)) to = '<' + (+tM + 1) + '.0.0-0'; else if (isX(tp)) to = '<' + tM + '.' + (+tm + 1) + '.0-0'; else if (tpr) to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; else to = '<=' + to; return (from + ' ' + to).trim(); } // if ANY of the sets match ALL of its comparators, then pass Range.prototype.test = function(version) { if (!version) return false; for (var i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version)) return true; } return false; }; function testSet(set, version) { for (var i = 0; i < set.length; i++) { if (!set[i].test(version)) return false; } return true; } exports.satisfies = satisfies; function satisfies(version, range, loose) { try { range = new Range(range, loose); } catch (er) { return false; } return range.test(version); } exports.maxSatisfying = maxSatisfying; function maxSatisfying(versions, range, loose) { return versions.filter(function(version) { return satisfies(version, range, loose); }).sort(function(a, b) { return rcompare(a, b, loose); })[0] || null; } exports.validRange = validRange; function validRange(range, loose) { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, loose).range || '*'; } catch (er) { return null; } } // Determine if version is less than all the versions possible in the range exports.ltr = ltr; function ltr(version, range, loose) { return outside(version, range, '<', loose); } // Determine if version is greater than all the versions possible in the range. exports.gtr = gtr; function gtr(version, range, loose) { return outside(version, range, '>', loose); } exports.outside = outside; function outside(version, range, hilo, loose) { version = new SemVer(version, loose); range = new Range(range, loose); var gtfn, ltefn, ltfn, comp, ecomp; switch (hilo) { case '>': gtfn = gt; ltefn = lte; ltfn = lt; comp = '>'; ecomp = '>='; break; case '<': gtfn = lt; ltefn = gte; ltfn = gt; comp = '<'; ecomp = '<='; break; default: throw new TypeError('Must provide a hilo val of "<" or ">"'); } // If it satisifes the range it is not outside if (satisfies(version, range, loose)) { return false; } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i]; var high = null; var low = null; comparators.forEach(function(comparator) { high = high || comparator; low = low || comparator; if (gtfn(comparator.semver, high.semver, loose)) { high = comparator; } else if (ltfn(comparator.semver, low.semver, loose)) { low = comparator; } }); // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false; } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false; } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false; } } return true; } // Use the define() function if we're in AMD land if (typeof define === 'function' && define.amd) define(exports); })( typeof exports === 'object' ? exports : typeof define === 'function' && define.amd ? {} : semver = {} );
markredballoon/clivemizen
wp-content/themes/redballoon/bootstrap/node_modules/npm-shrinkwrap/node_modules/npm/node_modules/semver/semver.browser.js
JavaScript
gpl-2.0
27,641
YUI.add('moodle-atto_bold-button', function (Y, NAME) { // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /* * @package atto_bold * @copyright 2013 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ /** * @module moodle-atto_bold-button */ /** * Atto text editor bold plugin. * * @namespace M.atto_bold * @class button * @extends M.editor_atto.EditorPlugin */ Y.namespace('M.atto_bold').Button = Y.Base.create('button', Y.M.editor_atto.EditorPlugin, [], { initializer: function() { this.addBasicButton({ exec: 'bold', // Key code for the keyboard shortcut which triggers this button: keys: '66', // Watch the following tags and add/remove highlighting as appropriate: tags: 'b, strong' }); } }); }, '@VERSION@', {"requires": ["moodle-editor_atto-plugin"]});
sameertechworks/wpmoodle
moodle/lib/editor/atto/plugins/bold/yui/build/moodle-atto_bold-button/moodle-atto_bold-button.js
JavaScript
gpl-2.0
1,557
var passport = require('passport'), errors = require('../errors'), events = require('../events'), labs = require('../utils/labs'), i18n = require('../i18n'), auth; function isBearerAutorizationHeader(req) { var parts, scheme, credentials; if (req.headers && req.headers.authorization) { parts = req.headers.authorization.split(' '); } else if (req.query && req.query.access_token) { return true; } else { return false; } if (parts.length === 2) { scheme = parts[0]; credentials = parts[1]; if (/^Bearer$/i.test(scheme)) { return true; } } return false; } auth = { // ### Authenticate Client Middleware authenticateClient: function authenticateClient(req, res, next) { // skip client authentication if bearer token is present if (isBearerAutorizationHeader(req)) { return next(); } if (req.query && req.query.client_id) { req.body.client_id = req.query.client_id; } if (req.query && req.query.client_secret) { req.body.client_secret = req.query.client_secret; } if (!req.body.client_id || !req.body.client_secret) { errors.logError( i18n.t('errors.middleware.auth.clientAuthenticationFailed'), i18n.t('errors.middleware.auth.clientCredentialsNotProvided'), i18n.t('errors.middleware.auth.forInformationRead', {url: 'http://api.ghost.org/docs/client-authentication'}) ); return errors.handleAPIError(new errors.UnauthorizedError(i18n.t('errors.middleware.auth.accessDenied')), req, res, next); } return passport.authenticate(['oauth2-client-password'], {session: false, failWithError: false}, function authenticate(err, client) { if (err) { return next(err); // will generate a 500 error } // req.body needs to be null for GET requests to build options correctly delete req.body.client_id; delete req.body.client_secret; if (!client) { errors.logError( i18n.t('errors.middleware.auth.clientAuthenticationFailed'), i18n.t('errors.middleware.auth.clientCredentialsNotValid'), i18n.t('errors.middleware.auth.forInformationRead', {url: 'http://api.ghost.org/docs/client-authentication'}) ); return errors.handleAPIError(new errors.UnauthorizedError(i18n.t('errors.middleware.auth.accessDenied')), req, res, next); } req.client = client; events.emit('client.authenticated', client); return next(null, client); } )(req, res, next); }, // ### Authenticate User Middleware authenticateUser: function authenticateUser(req, res, next) { return passport.authenticate('bearer', {session: false, failWithError: false}, function authenticate(err, user, info) { if (err) { return next(err); // will generate a 500 error } if (user) { req.authInfo = info; req.user = user; events.emit('user.authenticated', user); return next(null, user, info); } else if (isBearerAutorizationHeader(req)) { return errors.handleAPIError(new errors.UnauthorizedError(i18n.t('errors.middleware.auth.accessDenied')), req, res, next); } else if (req.client) { req.user = {id: 0}; return next(); } return errors.handleAPIError(new errors.UnauthorizedError(i18n.t('errors.middleware.auth.accessDenied')), req, res, next); } )(req, res, next); }, // Workaround for missing permissions // TODO: rework when https://github.com/TryGhost/Ghost/issues/3911 is done requiresAuthorizedUser: function requiresAuthorizedUser(req, res, next) { if (req.user && req.user.id) { return next(); } else { return errors.handleAPIError(new errors.NoPermissionError(i18n.t('errors.middleware.auth.pleaseSignIn')), req, res, next); } }, // ### Require user depending on public API being activated. requiresAuthorizedUserPublicAPI: function requiresAuthorizedUserPublicAPI(req, res, next) { if (labs.isSet('publicAPI') === true) { return next(); } else { if (req.user && req.user.id) { return next(); } else { return errors.handleAPIError(new errors.NoPermissionError(i18n.t('errors.middleware.auth.pleaseSignIn')), req, res, next); } } } }; module.exports = auth;
norsasono/openshift-ghost-starter
node_modules/ghost/core/server/middleware/auth.js
JavaScript
mit
5,047
/* YUI 3.16.0 (build 76f0e08) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('arraylist', function (Y, NAME) { /** * Collection utilities beyond what is provided in the YUI core * @module collection * @submodule arraylist */ var YArray = Y.Array, YArray_each = YArray.each, ArrayListProto; /** * Generic ArrayList class for managing lists of items and iterating operations * over them. The targeted use for this class is for augmentation onto a * class that is responsible for managing multiple instances of another class * (e.g. NodeList for Nodes). The recommended use is to augment your class with * ArrayList, then use ArrayList.addMethod to mirror the API of the constituent * items on the list's API. * * The default implementation creates immutable lists, but mutability can be * provided via the arraylist-add submodule or by implementing mutation methods * directly on the augmented class's prototype. * * @class ArrayList * @constructor * @param items { Array } array of items this list will be responsible for */ function ArrayList( items ) { if ( items !== undefined ) { this._items = Y.Lang.isArray( items ) ? items : YArray( items ); } else { // ||= to support lazy initialization from augment this._items = this._items || []; } } ArrayListProto = { /** * Get an item by index from the list. Override this method if managing a * list of objects that have a different public representation (e.g. Node * instances vs DOM nodes). The iteration methods that accept a user * function will use this method for access list items for operation. * * @method item * @param i { Integer } index to fetch * @return { mixed } the item at the requested index */ item: function ( i ) { return this._items[i]; }, /** * <p>Execute a function on each item of the list, optionally providing a * custom execution context. Default context is the item.</p> * * <p>The callback signature is <code>callback( item, index )</code>.</p> * * @method each * @param fn { Function } the function to execute * @param context { mixed } optional override 'this' in the function * @return { ArrayList } this instance * @chainable */ each: function ( fn, context ) { YArray_each( this._items, function ( item, i ) { item = this.item( i ); fn.call( context || item, item, i, this ); }, this); return this; }, /** * <p>Execute a function on each item of the list, optionally providing a * custom execution context. Default context is the item.</p> * * <p>The callback signature is <code>callback( item, index )</code>.</p> * * <p>Unlike <code>each</code>, if the callback returns true, the * iteration will stop.</p> * * @method some * @param fn { Function } the function to execute * @param context { mixed } optional override 'this' in the function * @return { Boolean } True if the function returned true on an item */ some: function ( fn, context ) { return YArray.some( this._items, function ( item, i ) { item = this.item( i ); return fn.call( context || item, item, i, this ); }, this); }, /** * Finds the first index of the needle in the managed array of items. * * @method indexOf * @param needle { mixed } The item to search for * @return { Integer } Array index if found. Otherwise -1 */ indexOf: function ( needle ) { return YArray.indexOf( this._items, needle ); }, /** * How many items are in this list? * * @method size * @return { Integer } Number of items in the list */ size: function () { return this._items.length; }, /** * Is this instance managing any items? * * @method isEmpty * @return { Boolean } true if 1 or more items are being managed */ isEmpty: function () { return !this.size(); }, /** * Provides an array-like representation for JSON.stringify. * * @method toJSON * @return { Array } an array representation of the ArrayList */ toJSON: function () { return this._items; } }; // Default implementation does not distinguish between public and private // item getter /** * Protected method for optimizations that may be appropriate for API * mirroring. Similar in functionality to <code>item</code>, but is used by * methods added with <code>ArrayList.addMethod()</code>. * * @method _item * @protected * @param i { Integer } Index of item to fetch * @return { mixed } The item appropriate for pass through API methods */ ArrayListProto._item = ArrayListProto.item; // Mixed onto existing proto to preserve constructor NOT being an own property. // This has bitten me when composing classes by enumerating, copying prototypes. Y.mix(ArrayList.prototype, ArrayListProto); Y.mix( ArrayList, { /** * <p>Adds a pass through method to dest (typically the prototype of a list * class) that calls the named method on each item in the list with * whatever parameters are passed in. Allows for API indirection via list * instances.</p> * * <p>Accepts a single string name or an array of string names.</p> * * <pre><code>list.each( function ( item ) { * item.methodName( 1, 2, 3 ); * } ); * // becomes * list.methodName( 1, 2, 3 );</code></pre> * * <p>Additionally, the pass through methods use the item retrieved by the * <code>_item</code> method in case there is any special behavior that is * appropriate for API mirroring.</p> * * <p>If the iterated method returns a value, the return value from the * added method will be an array of values with each value being at the * corresponding index for that item. If the iterated method does not * return a value, the added method will be chainable. * * @method addMethod * @static * @param dest {Object} Object or prototype to receive the iterator method * @param name {String|String[]} Name of method of methods to create */ addMethod: function ( dest, names ) { names = YArray( names ); YArray_each( names, function ( name ) { dest[ name ] = function () { var args = YArray( arguments, 0, true ), ret = []; YArray_each( this._items, function ( item, i ) { item = this._item( i ); var result = item[ name ].apply( item, args ); if ( result !== undefined && result !== item ) { ret[i] = result; } }, this); return ret.length ? ret : this; }; } ); } } ); Y.ArrayList = ArrayList; }, '3.16.0', {"requires": ["yui-base"]});
ramda/jsdelivr
files/yui/3.16.0/arraylist/arraylist.js
JavaScript
mit
7,124
/**! * AngularJS file upload/drop directive and service with progress and abort * @author Danial <danial.farid@gmail.com> * @version 3.3.0 */ (function () { var key, i; function patchXHR(fnName, newFn) { window.XMLHttpRequest.prototype[fnName] = newFn(window.XMLHttpRequest.prototype[fnName]); } if (window.XMLHttpRequest && !window.XMLHttpRequest.__isFileAPIShim) { patchXHR('setRequestHeader', function (orig) { return function (header, value) { if (header === '__setXHR_') { var val = value(this); // fix for angular < 1.2.0 if (val instanceof Function) { val(this); } } else { orig.apply(this, arguments); } } }); } var angularFileUpload = angular.module('angularFileUpload', []); angularFileUpload.version = '3.3.0'; angularFileUpload.service('$upload', ['$http', '$q', '$timeout', function ($http, $q, $timeout) { function sendHttp(config) { config.method = config.method || 'POST'; config.headers = config.headers || {}; config.transformRequest = config.transformRequest || function (data, headersGetter) { if (window.ArrayBuffer && data instanceof window.ArrayBuffer) { return data; } return $http.defaults.transformRequest[0](data, headersGetter); }; var deferred = $q.defer(); var promise = deferred.promise; config.headers['__setXHR_'] = function () { return function (xhr) { if (!xhr) return; config.__XHR = xhr; config.xhrFn && config.xhrFn(xhr); xhr.upload.addEventListener('progress', function (e) { e.config = config; deferred.notify ? deferred.notify(e) : promise.progress_fn && $timeout(function () { promise.progress_fn(e) }); }, false); //fix for firefox not firing upload progress end, also IE8-9 xhr.upload.addEventListener('load', function (e) { if (e.lengthComputable) { e.config = config; deferred.notify ? deferred.notify(e) : promise.progress_fn && $timeout(function () { promise.progress_fn(e) }); } }, false); }; }; $http(config).then(function (r) { deferred.resolve(r) }, function (e) { deferred.reject(e) }, function (n) { deferred.notify(n) }); promise.success = function (fn) { promise.then(function (response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function (fn) { promise.then(null, function (response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.progress = function (fn) { promise.progress_fn = fn; promise.then(null, null, function (update) { fn(update); }); return promise; }; promise.abort = function () { if (config.__XHR) { $timeout(function () { config.__XHR.abort(); }); } return promise; }; promise.xhr = function (fn) { config.xhrFn = (function (origXhrFn) { return function () { origXhrFn && origXhrFn.apply(promise, arguments); fn.apply(promise, arguments); } })(config.xhrFn); return promise; }; return promise; } this.upload = function (config) { config.headers = config.headers || {}; config.headers['Content-Type'] = undefined; config.transformRequest = config.transformRequest ? (angular.isArray(config.transformRequest) ? config.transformRequest : [config.transformRequest]) : []; config.transformRequest.push(function (data) { var formData = new FormData(); var allFields = {}; for (key in config.fields) { if (config.fields.hasOwnProperty(key)) { allFields[key] = config.fields[key]; } } if (data) allFields['data'] = data; if (config.formDataAppender) { for (key in allFields) { if (allFields.hasOwnProperty(key)) { config.formDataAppender(formData, key, allFields[key]); } } } else { for (key in allFields) { if (allFields.hasOwnProperty(key)) { var val = allFields[key]; if (val !== undefined) { if (angular.isDate(val)) { val = val.toISOString(); } if (angular.isString(val)) { formData.append(key, val); } else { if (config.sendObjectsAsJsonBlob && angular.isObject(val)) { formData.append(key, new Blob([val], {type: 'application/json'})); } else { formData.append(key, JSON.stringify(val)); } } } } } } if (config.file != null) { var fileFormName = config.fileFormDataName || 'file'; if (angular.isArray(config.file)) { var isFileFormNameString = angular.isString(fileFormName); for (i = 0; i < config.file.length; i++) { formData.append(isFileFormNameString ? fileFormName : fileFormName[i], config.file[i], (config.fileName && config.fileName[i]) || config.file[i].name); } } else { formData.append(fileFormName, config.file, config.fileName || config.file.name); } } return formData; }); return sendHttp(config); }; this.http = function (config) { return sendHttp(config); }; }]); angularFileUpload.directive('ngFileSelect', ['$parse', '$timeout', '$compile', function ($parse, $timeout, $compile) { return { restrict: 'AEC', require: '?ngModel', link: function (scope, elem, attr, ngModel) { linkFileSelect(scope, elem, attr, ngModel, $parse, $timeout, $compile); } } }]); function linkFileSelect(scope, elem, attr, ngModel, $parse, $timeout, $compile) { function isInputTypeFile() { return elem[0].tagName.toLowerCase() === 'input' && elem.attr('type') && elem.attr('type').toLowerCase() === 'file'; } var isUpdating = false; function changeFn(evt) { if (!isUpdating) { isUpdating = true; try { var fileList = evt.__files_ || (evt.target && evt.target.files); var files = [], rejFiles = []; var accept = $parse(attr.ngAccept); for (i = 0; i < fileList.length; i++) { var file = fileList.item(i); if (isAccepted(scope, accept, file, evt)) { files.push(file); } else { rejFiles.push(file); } } updateModel($parse, $timeout, scope, ngModel, attr, attr.ngFileChange || (attr.ngFileDrop && attr.ngFileDrop.indexOf('(') > 0), files, rejFiles, evt); if (files.length == 0) evt.target.value = files; // if (evt.target && evt.target.getAttribute('__ngf_gen__')) { // angular.element(evt.target).remove(); // } } finally { isUpdating = false; } } } function bindAttrToFileInput(fileElem) { if (attr.ngMultiple) fileElem.attr('multiple', $parse(attr.ngMultiple)(scope)); if (!$parse(attr.ngMultiple)(scope)) fileElem.attr('multiple', undefined); if (attr['accept']) fileElem.attr('accept', attr['accept']); if (attr.ngCapture) fileElem.attr('capture', $parse(attr.ngCapture)(scope)); if (attr.ngDisabled) fileElem.attr('disabled', $parse(attr.ngDisabled)(scope)); for (var i = 0; i < elem[0].attributes.length; i++) { var attribute = elem[0].attributes[i]; if (attribute.name !== 'type' && attribute.name !== 'class' && attribute.name !== 'id' && attribute.name !== 'style') { fileElem.attr(attribute.name, attribute.value); } } } function createFileInput(evt) { if (elem.attr('disabled')) { return; } var fileElem = angular.element('<input type="file">'); bindAttrToFileInput(fileElem); if (isInputTypeFile()) { elem.replaceWith(fileElem); elem = fileElem; } else { fileElem.css('display', 'none').attr('tabindex', '-1').attr('__ngf_gen__', true); if (elem.__ngf_ref_elem__) {elem.__ngf_ref_elem__.remove();} elem.__ngf_ref_elem__ = fileElem; document.body.appendChild(fileElem[0]); } return fileElem; } function resetModel(evt) { updateModel($parse, $timeout, scope, ngModel, attr, attr.ngFileChange || attr.ngFileSelect, [], [], evt, true); } var clickTouchEvent = 'ontouchend' in document ? 'touchend' : 'click' function clickHandler(evt) { var fileElem = createFileInput(evt); if (fileElem) { fileElem.bind('change', changeFn); resetModel(evt); function clickAndAssign() { fileElem[0].click(); if (isInputTypeFile()) { elem.bind(clickTouchEvent, clickHandler); evt.preventDefault() } } // fix for android native browser if (navigator.userAgent.toLowerCase().match(/android/)) { setTimeout(function() { clickAndAssign(); }, 0); } else { clickAndAssign(); } } } if (window.FileAPI && window.FileAPI.ngfFixIE) { window.FileAPI.ngfFixIE(elem, createFileInput, bindAttrToFileInput, changeFn, resetModel); } else { elem.bind(clickTouchEvent, clickHandler); } } angularFileUpload.directive('ngFileDrop', ['$parse', '$timeout', '$location', function ($parse, $timeout, $location) { return { restrict: 'AEC', require: '?ngModel', link: function (scope, elem, attr, ngModel) { linkDrop(scope, elem, attr, ngModel, $parse, $timeout, $location); } } }]); angularFileUpload.directive('ngNoFileDrop', function () { return function (scope, elem) { if (dropAvailable()) elem.css('display', 'none') } }); //for backward compatibility angularFileUpload.directive('ngFileDropAvailable', ['$parse', '$timeout', function ($parse, $timeout) { return function (scope, elem, attr) { if (dropAvailable()) { var fn = $parse(attr['ngFileDropAvailable']); $timeout(function () { fn(scope); }); } } }]); function linkDrop(scope, elem, attr, ngModel, $parse, $timeout, $location) { var available = dropAvailable(); if (attr.dropAvailable) { $timeout(function () { scope[attr.dropAvailable] ? scope[attr.dropAvailable].value = available : scope[attr.dropAvailable] = available; }); } if (!available) { if ($parse(attr.hideOnDropNotAvailable)(scope) == true) { elem.css('display', 'none'); } return; } var leaveTimeout = null; var stopPropagation = $parse(attr.stopPropagation); var dragOverDelay = 1; var accept = $parse(attr.ngAccept); var disabled = $parse(attr.ngDisabled); var actualDragOverClass; elem[0].addEventListener('dragover', function (evt) { if (disabled(scope)) return; evt.preventDefault(); if (stopPropagation(scope)) evt.stopPropagation(); // handling dragover events from the Chrome download bar if (navigator.userAgent.indexOf("Chrome") > -1) { var b = evt.dataTransfer.effectAllowed; evt.dataTransfer.dropEffect = ('move' === b || 'linkMove' === b) ? 'move' : 'copy'; } $timeout.cancel(leaveTimeout); if (!scope.actualDragOverClass) { actualDragOverClass = calculateDragOverClass(scope, attr, evt); } elem.addClass(actualDragOverClass); }, false); elem[0].addEventListener('dragenter', function (evt) { if (disabled(scope)) return; evt.preventDefault(); if (stopPropagation(scope)) evt.stopPropagation(); }, false); elem[0].addEventListener('dragleave', function () { if (disabled(scope)) return; leaveTimeout = $timeout(function () { elem.removeClass(actualDragOverClass); actualDragOverClass = null; }, dragOverDelay || 1); }, false); elem[0].addEventListener('drop', function (evt) { if (disabled(scope)) return; evt.preventDefault(); if (stopPropagation(scope)) evt.stopPropagation(); elem.removeClass(actualDragOverClass); actualDragOverClass = null; extractFiles(evt, function (files, rejFiles) { updateModel($parse, $timeout, scope, ngModel, attr, attr.ngFileChange || (attr.ngFileDrop && attr.ngFileDrop.indexOf('(') > 0), files, rejFiles, evt) }, $parse(attr.allowDir)(scope) != false, attr.multiple || $parse(attr.ngMultiple)(scope)); }, false); function calculateDragOverClass(scope, attr, evt) { var accepted = true; var items = evt.dataTransfer.items; if (items != null) { for (i = 0; i < items.length && accepted; i++) { accepted = accepted && (items[i].kind == 'file' || items[i].kind == '') && isAccepted(scope, accept, items[i], evt); } } var clazz = $parse(attr.dragOverClass)(scope, {$event: evt}); if (clazz) { if (clazz.delay) dragOverDelay = clazz.delay; if (clazz.accept) clazz = accepted ? clazz.accept : clazz.reject; } return clazz || attr['dragOverClass'] || 'dragover'; } function extractFiles(evt, callback, allowDir, multiple) { var files = [], rejFiles = [], items = evt.dataTransfer.items, processing = 0; function addFile(file) { if (isAccepted(scope, accept, file, evt)) { files.push(file); } else { rejFiles.push(file); } } if (items && items.length > 0 && $location.protocol() != 'file') { for (var i = 0; i < items.length; i++) { if (items[i].webkitGetAsEntry && items[i].webkitGetAsEntry() && items[i].webkitGetAsEntry().isDirectory) { var entry = items[i].webkitGetAsEntry(); if (entry.isDirectory && !allowDir) { continue; } if (entry != null) { traverseFileTree(files, entry); } } else { var f = items[i].getAsFile(); if (f != null) addFile(f); } if (!multiple && files.length > 0) break; } } else { var fileList = evt.dataTransfer.files; if (fileList != null) { for (var i = 0; i < fileList.length; i++) { addFile(fileList.item(i)); if (!multiple && files.length > 0) break; } } } var delays = 0; (function waitForProcess(delay) { $timeout(function () { if (!processing) { if (!multiple && files.length > 1) { i = 0; while (files[i].type == 'directory') i++; files = [files[i]]; } callback(files, rejFiles); } else { if (delays++ * 10 < 20 * 1000) { waitForProcess(10); } } }, delay || 0) })(); function traverseFileTree(files, entry, path) { if (entry != null) { if (entry.isDirectory) { var filePath = (path || '') + entry.name; addFile({name: entry.name, type: 'directory', path: filePath}); var dirReader = entry.createReader(); var entries = []; processing++; var readEntries = function () { dirReader.readEntries(function (results) { try { if (!results.length) { for (i = 0; i < entries.length; i++) { traverseFileTree(files, entries[i], (path ? path : '') + entry.name + '/'); } processing--; } else { entries = entries.concat(Array.prototype.slice.call(results || [], 0)); readEntries(); } } catch (e) { processing--; console.error(e); } }, function () { processing--; }); }; readEntries(); } else { processing++; entry.file(function (file) { try { processing--; file.path = (path ? path : '') + file.name; addFile(file); } catch (e) { processing--; console.error(e); } }, function () { processing--; }); } } } } } function dropAvailable() { var div = document.createElement('div'); return ('draggable' in div) && ('ondrop' in div); } function updateModel($parse, $timeout, scope, ngModel, attr, fileChange, files, rejFiles, evt, noDelay) { function update() { if (ngModel) { $parse(attr.ngModel).assign(scope, files); $timeout(function () { ngModel && ngModel.$setViewValue(files != null && files.length == 0 ? null : files); }); } if (attr.ngModelRejected) { $parse(attr.ngModelRejected).assign(scope, rejFiles); } if (fileChange) { $parse(fileChange)(scope, { $files: files, $rejectedFiles: rejFiles, $event: evt }); } } if (noDelay) { update(); } else { $timeout(function () { update(); }); } } function isAccepted(scope, accept, file, evt) { var val = accept(scope, {$file: file, $event: evt}); if (val == null) { return true; } if (angular.isString(val)) { var regexp = new RegExp(globStringToRegex(val), 'gi') val = (file.type != null && file.type.match(regexp)) || (file.name != null && file.name.match(regexp)); } return val; } function globStringToRegex(str) { if (str.length > 2 && str[0] === '/' && str[str.length - 1] === '/') { return str.substring(1, str.length - 1); } var split = str.split(','), result = ''; if (split.length > 1) { for (i = 0; i < split.length; i++) { result += '(' + globStringToRegex(split[i]) + ')'; if (i < split.length - 1) { result += '|' } } } else { if (str.indexOf('.') == 0) { str = '*' + str; } result = '^' + str.replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + '-]', 'g'), '\\$&') + '$'; result = result.replace(/\\\*/g, '.*').replace(/\\\?/g, '.'); } return result; } var ngFileUpload = angular.module('ngFileUpload', []); for (key in angularFileUpload) { if (angularFileUpload.hasOwnProperty(key)) { ngFileUpload[key] = angularFileUpload[key]; } } })(); /**! * AngularJS file upload/drop directive and service with progress and abort * FileAPI Flash shim for old browsers not supporting FormData * @author Danial <danial.farid@gmail.com> * @version 3.3.0 */ (function() { var hasFlash = function() { try { var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash'); if (fo) return true; } catch(e) { if (navigator.mimeTypes['application/x-shockwave-flash'] != undefined) return true; } return false; } function patchXHR(fnName, newFn) { window.XMLHttpRequest.prototype[fnName] = newFn(window.XMLHttpRequest.prototype[fnName]); }; if ((window.XMLHttpRequest && !window.FormData) || (window.FileAPI && FileAPI.forceLoad)) { var initializeUploadListener = function(xhr) { if (!xhr.__listeners) { if (!xhr.upload) xhr.upload = {}; xhr.__listeners = []; var origAddEventListener = xhr.upload.addEventListener; xhr.upload.addEventListener = function(t, fn, b) { xhr.__listeners[t] = fn; origAddEventListener && origAddEventListener.apply(this, arguments); }; } } patchXHR('open', function(orig) { return function(m, url, b) { initializeUploadListener(this); this.__url = url; try { orig.apply(this, [m, url, b]); } catch (e) { if (e.message.indexOf('Access is denied') > -1) { this.__origError = e; orig.apply(this, [m, '_fix_for_ie_crossdomain__', b]); } } } }); patchXHR('getResponseHeader', function(orig) { return function(h) { return this.__fileApiXHR && this.__fileApiXHR.getResponseHeader ? this.__fileApiXHR.getResponseHeader(h) : (orig == null ? null : orig.apply(this, [h])); }; }); patchXHR('getAllResponseHeaders', function(orig) { return function() { return this.__fileApiXHR && this.__fileApiXHR.getAllResponseHeaders ? this.__fileApiXHR.getAllResponseHeaders() : (orig == null ? null : orig.apply(this)); } }); patchXHR('abort', function(orig) { return function() { return this.__fileApiXHR && this.__fileApiXHR.abort ? this.__fileApiXHR.abort() : (orig == null ? null : orig.apply(this)); } }); patchXHR('setRequestHeader', function(orig) { return function(header, value) { if (header === '__setXHR_') { initializeUploadListener(this); var val = value(this); // fix for angular < 1.2.0 if (val instanceof Function) { val(this); } } else { this.__requestHeaders = this.__requestHeaders || {}; this.__requestHeaders[header] = value; orig.apply(this, arguments); } } }); function redefineProp(xhr, prop, fn) { try { Object.defineProperty(xhr, prop, {get: fn}); } catch (e) {/*ignore*/} } patchXHR('send', function(orig) { return function() { var xhr = this; if (arguments[0] && arguments[0].__isFileAPIShim) { var formData = arguments[0]; var config = { url: xhr.__url, jsonp: false, //removes the callback form param cache: true, //removes the ?fileapiXXX in the url complete: function(err, fileApiXHR) { xhr.__completed = true; if (!err && xhr.__listeners['load']) xhr.__listeners['load']({type: 'load', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true}); if (!err && xhr.__listeners['loadend']) xhr.__listeners['loadend']({type: 'loadend', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true}); if (err === 'abort' && xhr.__listeners['abort']) xhr.__listeners['abort']({type: 'abort', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true}); if (fileApiXHR.status !== undefined) redefineProp(xhr, 'status', function() {return (fileApiXHR.status == 0 && err && err !== 'abort') ? 500 : fileApiXHR.status}); if (fileApiXHR.statusText !== undefined) redefineProp(xhr, 'statusText', function() {return fileApiXHR.statusText}); redefineProp(xhr, 'readyState', function() {return 4}); if (fileApiXHR.response !== undefined) redefineProp(xhr, 'response', function() {return fileApiXHR.response}); var resp = fileApiXHR.responseText || (err && fileApiXHR.status == 0 && err !== 'abort' ? err : undefined); redefineProp(xhr, 'responseText', function() {return resp}); redefineProp(xhr, 'response', function() {return resp}); if (err) redefineProp(xhr, 'err', function() {return err}); xhr.__fileApiXHR = fileApiXHR; if (xhr.onreadystatechange) xhr.onreadystatechange(); if (xhr.onload) xhr.onload(); }, fileprogress: function(e) { e.target = xhr; xhr.__listeners['progress'] && xhr.__listeners['progress'](e); xhr.__total = e.total; xhr.__loaded = e.loaded; if (e.total === e.loaded) { // fix flash issue that doesn't call complete if there is no response text from the server var _this = this setTimeout(function() { if (!xhr.__completed) { xhr.getAllResponseHeaders = function(){}; _this.complete(null, {status: 204, statusText: 'No Content'}); } }, FileAPI.noContentTimeout || 10000); } }, headers: xhr.__requestHeaders } config.data = {}; config.files = {} for (var i = 0; i < formData.data.length; i++) { var item = formData.data[i]; if (item.val != null && item.val.name != null && item.val.size != null && item.val.type != null) { config.files[item.key] = item.val; } else { config.data[item.key] = item.val; } } setTimeout(function() { if (!hasFlash()) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } xhr.__fileApiXHR = FileAPI.upload(config); }, 1); } else { if (this.__origError) { throw this.__origError; } orig.apply(xhr, arguments); } } }); window.XMLHttpRequest.__isFileAPIShim = true; function isInputTypeFile(elem) { return elem[0].tagName.toLowerCase() === 'input' && elem.attr('type') && elem.attr('type').toLowerCase() === 'file'; } FileAPI.ngfFixIE = function(elem, createFileElemFn, bindAttr, changeFn, resetModel) { if (!hasFlash()) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } var makeFlashInput = function(evt) { if (elem.attr('disabled')) { elem.__ngf_elem__.removeClass('js-fileapi-wrapper'); } else { var fileElem = elem.__ngf_elem__; if (!fileElem) { fileElem = elem.__ngf_elem__ = createFileElemFn(); fileElem.addClass('js-fileapi-wrapper'); if (!isInputTypeFile(elem)) { // if (fileElem.parent().css('position') === '' || fileElem.parent().css('position') === 'static') { // fileElem.parent().css('position', 'relative'); // } // elem.parent()[0].insertBefore(fileElem[0], elem[0]); // elem.css('overflow', 'hidden'); } setTimeout(function() { fileElem.bind('mouseenter', makeFlashInput); }, 10); fileElem.bind('change', function(evt) { fileApiChangeFn.apply(this, [evt]); changeFn.apply(this, [evt]); // alert('change' + evt); }); } else { bindAttr(elem.__ngf_elem__); } if (!isInputTypeFile(elem)) { FileAPI.log(getOffset(elem[0]).top, getOffset(elem[0]).left) fileElem.css('position', 'absolute') .css('top', getOffset(elem[0]).top + 'px').css('left', getOffset(elem[0]).left + 'px') .css('width', elem[0].offsetWidth + 'px').css('height', elem[0].offsetHeight + 'px') .css('filter', 'alpha(opacity=0)').css('display', elem.css('display')) .css('overflow', 'hidden').css('z-index', '1'); } } function getOffset(obj) { var left, top; left = top = 0; if (obj.offsetParent) { do { left += obj.offsetLeft; top += obj.offsetTop; } while (obj = obj.offsetParent); } return { left : left, top : top }; }; }; elem.bind('mouseenter', makeFlashInput); var fileApiChangeFn = function(evt) { var files = FileAPI.getFiles(evt); //just a double check for #233 for (var i = 0; i < files.length; i++) { if (files[i].size === undefined) files[i].size = 0; if (files[i].name === undefined) files[i].name = 'file'; if (files[i].type === undefined) files[i].type = 'undefined'; } if (!evt.target) { evt.target = {}; } evt.target.files = files; // if evt.target.files is not writable use helper field if (evt.target.files != files) { evt.__files_ = files; } (evt.__files_ || evt.target.files).item = function(i) { return (evt.__files_ || evt.target.files)[i] || null; }; }; }; window.FormData = FormData = function() { return { append: function(key, val, name) { if (val.__isFileAPIBlobShim) { val = val.data[0]; } this.data.push({ key: key, val: val, name: name }); }, data: [], __isFileAPIShim: true }; }; window.Blob = Blob = function(b) { return { data: b, __isFileAPIBlobShim: true }; }; (function () { //load FileAPI if (!window.FileAPI) { window.FileAPI = {}; } if (FileAPI.forceLoad) { FileAPI.html5 = false; } if (!FileAPI.upload) { var jsUrl, basePath, script = document.createElement('script'), allScripts = document.getElementsByTagName('script'), i, index, src; if (window.FileAPI.jsUrl) { jsUrl = window.FileAPI.jsUrl; } else if (window.FileAPI.jsPath) { basePath = window.FileAPI.jsPath; } else { for (i = 0; i < allScripts.length; i++) { src = allScripts[i].src; index = src.search(/\/angular\-file\-upload[\-a-zA-z0-9\.]*\.js/) if (index > -1) { basePath = src.substring(0, index + 1); break; } } } if (FileAPI.staticPath == null) FileAPI.staticPath = basePath; script.setAttribute('src', jsUrl || basePath + 'FileAPI.js'); document.getElementsByTagName('head')[0].appendChild(script); FileAPI.hasFlash = hasFlash(); } })(); FileAPI.disableFileInput = function(elem, disable) { if (disable) { elem.removeClass('js-fileapi-wrapper') } else { elem.addClass('js-fileapi-wrapper'); } } } if (!window.FileReader) { window.FileReader = function() { var _this = this, loadStarted = false; this.listeners = {}; this.addEventListener = function(type, fn) { _this.listeners[type] = _this.listeners[type] || []; _this.listeners[type].push(fn); }; this.removeEventListener = function(type, fn) { _this.listeners[type] && _this.listeners[type].splice(_this.listeners[type].indexOf(fn), 1); }; this.dispatchEvent = function(evt) { var list = _this.listeners[evt.type]; if (list) { for (var i = 0; i < list.length; i++) { list[i].call(_this, evt); } } }; this.onabort = this.onerror = this.onload = this.onloadstart = this.onloadend = this.onprogress = null; var constructEvent = function(type, evt) { var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error}; if (evt.result != null) e.target.result = evt.result; return e; }; var listener = function(evt) { if (!loadStarted) { loadStarted = true; _this.onloadstart && _this.onloadstart(constructEvent('loadstart', evt)); } if (evt.type === 'load') { _this.onloadend && _this.onloadend(constructEvent('loadend', evt)); var e = constructEvent('load', evt); _this.onload && _this.onload(e); _this.dispatchEvent(e); } else if (evt.type === 'progress') { var e = constructEvent('progress', evt); _this.onprogress && _this.onprogress(e); _this.dispatchEvent(e); } else { var e = constructEvent('error', evt); _this.onerror && _this.onerror(e); _this.dispatchEvent(e); } }; this.readAsArrayBuffer = function(file) { FileAPI.readAsBinaryString(file, listener); } this.readAsBinaryString = function(file) { FileAPI.readAsBinaryString(file, listener); } this.readAsDataURL = function(file) { FileAPI.readAsDataURL(file, listener); } this.readAsText = function(file) { FileAPI.readAsText(file, listener); } } } })();
tmthrgd/pagespeed-libraries-cdnjs
packages/danialfarid-angular-file-upload/3.3.0/angular-file-upload-all.js
JavaScript
mit
33,702
YUI.add('dd-drop', function(Y) { /** * Provides the ability to create a Drop Target. * @module dd * @submodule dd-drop */ /** * Provides the ability to create a Drop Target. * @class Drop * @extends Base * @constructor * @namespace DD */ var NODE = 'node', DDM = Y.DD.DDM, OFFSET_HEIGHT = 'offsetHeight', OFFSET_WIDTH = 'offsetWidth', /** * @event drop:over * @description Fires when a drag element is over this target. * @param {Event.Facade} event An Event Facade object with the following specific property added: * <dl> * <dt>drop</dt><dd>The drop object at the time of the event.</dd> * <dt>drag</dt><dd>The drag object at the time of the event.</dd> * </dl> * @bubbles DDM * @type {Event.Custom} */ EV_DROP_OVER = 'drop:over', /** * @event drop:enter * @description Fires when a drag element enters this target. * @param {Event.Facade} event An Event Facade object with the following specific property added: * <dl> * <dt>drop</dt><dd>The drop object at the time of the event.</dd> * <dt>drag</dt><dd>The drag object at the time of the event.</dd> * </dl> * @bubbles DDM * @type {Event.Custom} */ EV_DROP_ENTER = 'drop:enter', /** * @event drop:exit * @description Fires when a drag element exits this target. * @param {Event.Facade} event An Event Facade object * @bubbles DDM * @type {Event.Custom} */ EV_DROP_EXIT = 'drop:exit', /** * @event drop:hit * @description Fires when a draggable node is dropped on this Drop Target. (Fired from dd-ddm-drop) * @param {Event.Facade} event An Event Facade object with the following specific property added: * <dl> * <dt>drop</dt><dd>The best guess on what was dropped on.</dd> * <dt>drag</dt><dd>The drag object at the time of the event.</dd> * <dt>others</dt><dd>An array of all the other drop targets that was dropped on.</dd> * </dl> * @bubbles DDM * @type {Event.Custom} */ Drop = function() { this._lazyAddAttrs = false; Drop.superclass.constructor.apply(this, arguments); //DD init speed up. Y.on('domready', Y.bind(function() { Y.later(100, this, this._createShim); }, this)); DDM._regTarget(this); /* TODO if (Dom.getStyle(this.el, 'position') == 'fixed') { Event.on(window, 'scroll', function() { this.activateShim(); }, this, true); } */ }; Drop.NAME = 'drop'; Drop.ATTRS = { /** * @attribute node * @description Y.Node instanace to use as the element to make a Drop Target * @type Node */ node: { setter: function(node) { var n = Y.one(node); if (!n) { Y.error('DD.Drop: Invalid Node Given: ' + node); } return n; } }, /** * @attribute groups * @description Array of groups to add this drop into. * @type Array */ groups: { value: ['default'], setter: function(g) { this._groups = {}; Y.each(g, function(v, k) { this._groups[v] = true; }, this); return g; } }, /** * @attribute padding * @description CSS style padding to make the Drop Target bigger than the node. * @type String */ padding: { value: '0', setter: function(p) { return DDM.cssSizestoObject(p); } }, /** * @attribute lock * @description Set to lock this drop element. * @type Boolean */ lock: { value: false, setter: function(lock) { if (lock) { this.get(NODE).addClass(DDM.CSS_PREFIX + '-drop-locked'); } else { this.get(NODE).removeClass(DDM.CSS_PREFIX + '-drop-locked'); } return lock; } }, /** * @deprecated * @attribute bubbles * @description Controls the default bubble parent for this Drop instance. Default: Y.DD.DDM. Set to false to disable bubbling. Use bubbleTargets in config. * @type Object */ bubbles: { setter: function(t) { this.addTarget(t); return t; } }, /** * @deprecated * @attribute useShim * @description Use the Drop shim. Default: true * @type Boolean */ useShim: { value: true, setter: function(v) { Y.DD.DDM._noShim = !v; return v; } } }; Y.extend(Drop, Y.Base, { /** * @private * @property _bubbleTargets * @description The default bubbleTarget for this object. Default: Y.DD.DDM */ _bubbleTargets: Y.DD.DDM, /** * @method addToGroup * @description Add this Drop instance to a group, this should be used for on-the-fly group additions. * @param {String} g The group to add this Drop Instance to. * @return {Self} * @chainable */ addToGroup: function(g) { this._groups[g] = true; return this; }, /** * @method removeFromGroup * @description Remove this Drop instance from a group, this should be used for on-the-fly group removals. * @param {String} g The group to remove this Drop Instance from. * @return {Self} * @chainable */ removeFromGroup: function(g) { delete this._groups[g]; return this; }, /** * @private * @method _createEvents * @description This method creates all the events for this Event Target and publishes them so we get Event Bubbling. */ _createEvents: function() { var ev = [ EV_DROP_OVER, EV_DROP_ENTER, EV_DROP_EXIT, 'drop:hit' ]; Y.each(ev, function(v, k) { this.publish(v, { type: v, emitFacade: true, preventable: false, bubbles: true, queuable: false, prefix: 'drop' }); }, this); }, /** * @private * @property _valid * @description Flag for determining if the target is valid in this operation. * @type Boolean */ _valid: null, /** * @private * @property _groups * @description The groups this target belongs to. * @type Array */ _groups: null, /** * @property shim * @description Node reference to the targets shim * @type {Object} */ shim: null, /** * @property region * @description A region object associated with this target, used for checking regions while dragging. * @type Object */ region: null, /** * @property overTarget * @description This flag is tripped when a drag element is over this target. * @type Boolean */ overTarget: null, /** * @method inGroup * @description Check if this target is in one of the supplied groups. * @param {Array} groups The groups to check against * @return Boolean */ inGroup: function(groups) { this._valid = false; var ret = false; Y.each(groups, function(v, k) { if (this._groups[v]) { ret = true; this._valid = true; } }, this); return ret; }, /** * @private * @method initializer * @description Private lifecycle method */ initializer: function(cfg) { Y.later(100, this, this._createEvents); var node = this.get(NODE), id; if (!node.get('id')) { id = Y.stamp(node); node.set('id', id); } node.addClass(DDM.CSS_PREFIX + '-drop'); //Shouldn't have to do this.. this.set('groups', this.get('groups')); }, /** * @private * @method destructor * @description Lifecycle destructor, unreg the drag from the DDM and remove listeners */ destructor: function() { DDM._unregTarget(this); if (this.shim && (this.shim !== this.get(NODE))) { this.shim.detachAll(); this.shim.remove(); this.shim = null; } this.get(NODE).removeClass(DDM.CSS_PREFIX + '-drop'); this.detachAll(); }, /** * @private * @method _deactivateShim * @description Removes classes from the target, resets some flags and sets the shims deactive position [-999, -999] */ _deactivateShim: function() { if (!this.shim) { return false; } this.get(NODE).removeClass(DDM.CSS_PREFIX + '-drop-active-valid'); this.get(NODE).removeClass(DDM.CSS_PREFIX + '-drop-active-invalid'); this.get(NODE).removeClass(DDM.CSS_PREFIX + '-drop-over'); if (this.get('useShim')) { this.shim.setStyles({ top: '-999px', left: '-999px', zIndex: '1' }); } this.overTarget = false; }, /** * @private * @method _activateShim * @description Activates the shim and adds some interaction CSS classes */ _activateShim: function() { if (!DDM.activeDrag) { return false; //Nothing is dragging, no reason to activate. } if (this.get(NODE) === DDM.activeDrag.get(NODE)) { return false; } if (this.get('lock')) { return false; } var node = this.get(NODE); //TODO Visibility Check.. //if (this.inGroup(DDM.activeDrag.get('groups')) && this.get(NODE).isVisible()) { if (this.inGroup(DDM.activeDrag.get('groups'))) { node.removeClass(DDM.CSS_PREFIX + '-drop-active-invalid'); node.addClass(DDM.CSS_PREFIX + '-drop-active-valid'); DDM._addValid(this); this.overTarget = false; if (!this.get('useShim')) { this.shim = this.get(NODE); } this.sizeShim(); } else { DDM._removeValid(this); node.removeClass(DDM.CSS_PREFIX + '-drop-active-valid'); node.addClass(DDM.CSS_PREFIX + '-drop-active-invalid'); } }, /** * @method sizeShim * @description Positions and sizes the shim with the raw data from the node, this can be used to programatically adjust the Targets shim for Animation.. */ sizeShim: function() { if (!DDM.activeDrag) { return false; //Nothing is dragging, no reason to activate. } if (this.get(NODE) === DDM.activeDrag.get(NODE)) { return false; } //if (this.get('lock') || !this.get('useShim')) { if (this.get('lock')) { return false; } if (!this.shim) { Y.later(100, this, this.sizeShim); return false; } var node = this.get(NODE), nh = node.get(OFFSET_HEIGHT), nw = node.get(OFFSET_WIDTH), xy = node.getXY(), p = this.get('padding'), dd, dH, dW; //Apply padding nw = nw + p.left + p.right; nh = nh + p.top + p.bottom; xy[0] = xy[0] - p.left; xy[1] = xy[1] - p.top; if (DDM.activeDrag.get('dragMode') === DDM.INTERSECT) { //Intersect Mode, make the shim bigger dd = DDM.activeDrag; dH = dd.get(NODE).get(OFFSET_HEIGHT); dW = dd.get(NODE).get(OFFSET_WIDTH); nh = (nh + dH); nw = (nw + dW); xy[0] = xy[0] - (dW - dd.deltaXY[0]); xy[1] = xy[1] - (dH - dd.deltaXY[1]); } if (this.get('useShim')) { //Set the style on the shim this.shim.setStyles({ height: nh + 'px', width: nw + 'px', top: xy[1] + 'px', left: xy[0] + 'px' }); } //Create the region to be used by intersect when a drag node is over us. this.region = { '0': xy[0], '1': xy[1], area: 0, top: xy[1], right: xy[0] + nw, bottom: xy[1] + nh, left: xy[0] }; }, /** * @private * @method _createShim * @description Creates the Target shim and adds it to the DDM's playground.. */ _createShim: function() { //No playground, defer if (!DDM._pg) { Y.later(10, this, this._createShim); return; } //Shim already here, cancel if (this.shim) { return; } var s = this.get('node'); if (this.get('useShim')) { s = Y.Node.create('<div id="' + this.get(NODE).get('id') + '_shim"></div>'); s.setStyles({ height: this.get(NODE).get(OFFSET_HEIGHT) + 'px', width: this.get(NODE).get(OFFSET_WIDTH) + 'px', backgroundColor: 'yellow', opacity: '.5', zIndex: '1', overflow: 'hidden', top: '-900px', left: '-900px', position: 'absolute' }); DDM._pg.appendChild(s); s.on('mouseover', Y.bind(this._handleOverEvent, this)); s.on('mouseout', Y.bind(this._handleOutEvent, this)); } this.shim = s; }, /** * @private * @method _handleOverTarget * @description This handles the over target call made from this object or from the DDM */ _handleTargetOver: function() { if (DDM.isOverTarget(this)) { this.get(NODE).addClass(DDM.CSS_PREFIX + '-drop-over'); DDM.activeDrop = this; DDM.otherDrops[this] = this; if (this.overTarget) { DDM.activeDrag.fire('drag:over', { drop: this, drag: DDM.activeDrag }); this.fire(EV_DROP_OVER, { drop: this, drag: DDM.activeDrag }); } else { //Prevent an enter before a start.. if (DDM.activeDrag.get('dragging')) { this.overTarget = true; this.fire(EV_DROP_ENTER, { drop: this, drag: DDM.activeDrag }); DDM.activeDrag.fire('drag:enter', { drop: this, drag: DDM.activeDrag }); DDM.activeDrag.get(NODE).addClass(DDM.CSS_PREFIX + '-drag-over'); //TODO - Is this needed?? //DDM._handleTargetOver(); } } } else { this._handleOut(); } }, /** * @private * @method _handleOverEvent * @description Handles the mouseover DOM event on the Target Shim */ _handleOverEvent: function() { this.shim.setStyle('zIndex', '999'); DDM._addActiveShim(this); }, /** * @private * @method _handleOutEvent * @description Handles the mouseout DOM event on the Target Shim */ _handleOutEvent: function() { this.shim.setStyle('zIndex', '1'); DDM._removeActiveShim(this); }, /** * @private * @method _handleOut * @description Handles out of target calls/checks */ _handleOut: function(force) { if (!DDM.isOverTarget(this) || force) { if (this.overTarget) { this.overTarget = false; if (!force) { DDM._removeActiveShim(this); } if (DDM.activeDrag) { this.get(NODE).removeClass(DDM.CSS_PREFIX + '-drop-over'); DDM.activeDrag.get(NODE).removeClass(DDM.CSS_PREFIX + '-drag-over'); this.fire(EV_DROP_EXIT); DDM.activeDrag.fire('drag:exit', { drop: this }); delete DDM.otherDrops[this]; } } } } }); Y.DD.Drop = Drop; }, '@VERSION@' ,{skinnable:false, requires:['dd-ddm-drop', 'dd-drag']});
danut007ro/cdnjs
ajax/libs/yui/3.2.0/dd/dd-drop.js
JavaScript
mit
18,181
/*! * Backbone.Marionette, v1.0.0-beta3 * Copyright (c)2012 Derick Bailey, Muted Solutions, LLC. * Distributed under MIT license * http://github.com/marionettejs/backbone.marionette */ /*! * Includes Wreqr * https://github.com/marionettejs/backbone.wreqr/ * Includes EventBinder * https://github.com/marionettejs/backbone.eventbinder/ */ // Backbone.EventBinder, v0.1.0 // Copyright (c)2012 Derick Bailey, Muted Solutions, LLC. // Distributed under MIT license // http://github.com/marionettejs/backbone.eventbinder // EventBinder // ----------- // // The event binder facilitates the binding and unbinding of events // from objects that extend `Backbone.Events`. It makes // unbinding events, even with anonymous callback functions, // easy. // // Inspired by [Johnny Oshika](http://stackoverflow.com/questions/7567404/backbone-js-repopulate-or-recreate-the-view/7607853#7607853) Backbone.EventBinder = (function(Backbone, _){ "use strict"; // A map of objects that support binding/unbinding events. // This allows EventBinder to support events on arbitrary // objects with EB's consistent api. var handlerMap = { // 'default' type accounts for Backbone style objects extending // Backbone.Events "default" : { bindTo : function (obj, eventName, callback, context) { context = context || this; obj.on(eventName, callback, context); var binding = { type : 'default', obj: obj, eventName: eventName, callback: callback, context: context }; return binding; }, unbindFrom : function(binding){ binding.obj.off(binding.eventName, binding.callback, binding.context); } }, // 'jquery' style handlers allow us to bind to jQuery // (or compatible) objects jquery : { bindTo : function (obj, eventName, callback, context) { context = context || this; callback = _(callback).bind(context); obj.on(eventName, callback); var binding = { type : 'jquery', obj: obj, eventName: eventName, callback: callback, context: context }; return binding; }, unbindFrom : function(binding){ binding.obj.off(binding.eventName, binding.callback); } } }; // Use whatever best logic necessary to determine the type // of the supplied object function getHandlerForObject(obj) { if (obj.jquery) { return handlerMap.jquery; } return handlerMap["default"]; } // Constructor function var EventBinder = function(){ this._eventBindings = []; }; // Copy the `extend` function used by Backbone's classes EventBinder.extend = Backbone.View.extend; // Extend the EventBinder with additional methods _.extend(EventBinder.prototype, { // Delegate to the bindTo for the appropriate type and // store the event binding in array so it can be unbound // easily, at a later point in time. bindTo: function(/* args... */) { var obj = arguments[0]; var handlers = getHandlerForObject(obj); var binding = handlers.bindTo.apply(this,arguments); this._eventBindings.push(binding); return binding; }, // Unbind from a single binding object. Binding objects are // returned from the `bindTo` method call. unbindFrom: function(binding) { handlerMap[binding.type].unbindFrom.apply(this,arguments); this._eventBindings = _.reject(this._eventBindings, function(bind){return bind === binding;}); }, // Unbind all of the events that we have stored. unbindAll: function() { // The `unbindFrom` call removes elements from the array // while it is being iterated, so clone it first. var bindings = _.map(this._eventBindings, _.identity); _.each(bindings, this.unbindFrom, this); } }); return EventBinder; })(Backbone, _); // Backbone.Wreqr, v0.0.0 // Copyright (c)2012 Derick Bailey, Muted Solutions, LLC. // Distributed under MIT license // http://github.com/marionettejs/backbone.wreqr Backbone.Wreqr = (function(Backbone, Marionette, _){ "option strict"; var Wreqr = {}; Wreqr.Handlers = (function(Backbone, _){ "option strict"; var Handlers = function(){ "use strict"; this._handlers = {}; }; Handlers.extend = Backbone.Model.extend; _.extend(Handlers.prototype, { addHandler: function(name, handler, context){ var config = { callback: handler, context: context }; this._handlers[name] = config; }, getHandler: function(name){ var config = this._handlers[name]; if (!config){ throw new Error("Handler not found for '" + name + "'"); } return function(){ return config.callback.apply(config.context, arguments); }; }, removeHandler: function(name){ delete this._handlers[name]; }, removeAllHandlers: function(){ this._handlers = {}; } }); return Handlers; })(Backbone, _); // Wreqr.Commands // -------------- // // A simple command pattern implementation. Register a command // handler and execute it. Wreqr.Commands = (function(Wreqr){ "option strict"; return Wreqr.Handlers.extend({ execute: function(name, args){ this.getHandler(name)(args); } }); })(Wreqr); // Wreqr.RequestResponse // --------------------- // // A simple request/response implementation. Register a // request handler, and return a response from it Wreqr.RequestResponse = (function(Wreqr){ "option strict"; return Wreqr.Handlers.extend({ request: function(name, args){ return this.getHandler(name)(args); } }); })(Wreqr); // Event Aggregator // ---------------- // A pub-sub object that can be used to decouple various parts // of an application through event-driven architecture. Wreqr.EventAggregator = (function(Backbone, _){ "option strict"; var EA = function(){}; // Copy the `extend` function used by Backbone's classes EA.extend = Backbone.Model.extend; // Copy the basic Backbone.Events on to the event aggregator _.extend(EA.prototype, Backbone.Events); return EA; })(Backbone, _); return Wreqr; })(Backbone, Backbone.Marionette, _); Backbone.Marionette = Marionette = (function(Backbone, _, $){ var Marionette = {}; // Helpers // ------- // For slicing `arguments` in functions var slice = Array.prototype.slice; // Borrow the Backbone `extend` method so we can use it as needed Marionette.extend = Backbone.Model.extend; // Trigger an event and a corresponding method name. Examples: // // `this.triggerMethod("foo")` will trigger the "foo" event and // call the "onFoo" method. // // `this.triggerMethod("foo:bar") will trigger the "foo:bar" event and // call the "onFooBar" method. Marionette.triggerMethod = function(){ var args = Array.prototype.slice.apply(arguments); var eventName = args[0]; var segments = eventName.split(":"); var segment, capLetter, methodName = "on"; for (var i = 0; i < segments.length; i++){ segment = segments[i]; capLetter = segment.charAt(0).toUpperCase(); methodName += capLetter + segment.slice(1); } this.trigger.apply(this, arguments); if (_.isFunction(this[methodName])){ args.shift(); this[methodName].apply(this, args); } }; // EventBinder // ----------- // Import the event binder from it's new home // https://github.com/marionettejs/backbone.eventbinder Marionette.EventBinder = Backbone.EventBinder; // Add the EventBinder methods to the view directly, // but keep them bound to the EventBinder instance so they work properly. // This allows the event binder's implementation to vary independently // of it being attached to the view... for example the internal structure // used to store the events can change without worry about it interfering // with Marionette's views. Marionette.addEventBinder = function(target){ var eventBinder = new Marionette.EventBinder(); target.eventBinder = eventBinder; target.bindTo = _.bind(eventBinder.bindTo, eventBinder); target.unbindFrom = _.bind(eventBinder.unbindFrom, eventBinder); target.unbindAll = _.bind(eventBinder.unbindAll, eventBinder); }; // Event Aggregator // ---------------- // A pub-sub object that can be used to decouple various parts // of an application through event-driven architecture. // // Extends [Backbone.Wreqr.EventAggregator](https://github.com/marionettejs/backbone.wreqr) // and mixes in an EventBinder from [Backbone.EventBinder](https://github.com/marionettejs/backbone.eventbinder). Marionette.EventAggregator = Backbone.Wreqr.EventAggregator.extend({ constructor: function(){ Marionette.addEventBinder(this); Backbone.Wreqr.EventAggregator.prototype.constructor.apply(this, arguments); } }); // Marionette.View // --------------- // The core view type that other Marionette views extend from. Marionette.View = Backbone.View.extend({ constructor: function(){ _.bindAll(this, "render"); Marionette.addEventBinder(this); Backbone.View.prototype.constructor.apply(this, arguments); this.bindBackboneEntityTo(this.model, this.modelEvents); this.bindBackboneEntityTo(this.collection, this.collectionEvents); this.bindTo(this, "show", this.onShowCalled, this); }, // import the "triggerMethod" to trigger events with corresponding // methods if the method exists triggerMethod: Marionette.triggerMethod, // Get the template for this view // instance. You can set a `template` attribute in the view // definition or pass a `template: "whatever"` parameter in // to the constructor options. getTemplate: function(){ var template; // Get the template from `this.options.template` or // `this.template`. The `options` takes precedence. if (this.options && this.options.template){ template = this.options.template; } else { template = this.template; } return template; }, // Mix in template helper methods. Looks for a // `templateHelpers` attribute, which can either be an // object literal, or a function that returns an object // literal. All methods and attributes from this object // are copies to the object passed in. mixinTemplateHelpers: function(target){ target = target || {}; var templateHelpers = this.templateHelpers; if (_.isFunction(templateHelpers)){ templateHelpers = templateHelpers.call(this); } return _.extend(target, templateHelpers); }, // Configure `triggers` to forward DOM events to view // events. `triggers: {"click .foo": "do:foo"}` configureTriggers: function(){ if (!this.triggers) { return; } var that = this; var triggerEvents = {}; // Allow `triggers` to be configured as a function var triggers = _.result(this, "triggers"); // Configure the triggers, prevent default // action and stop propagation of DOM events _.each(triggers, function(value, key){ triggerEvents[key] = function(e){ if (e && e.preventDefault){ e.preventDefault(); } if (e && e.stopPropagation){ e.stopPropagation(); } that.trigger(value); }; }); return triggerEvents; }, // Overriding Backbone.View's delegateEvents specifically // to handle the `triggers` configuration delegateEvents: function(events){ events = events || this.events; if (_.isFunction(events)){ events = events.call(this); } var combinedEvents = {}; var triggers = this.configureTriggers(); _.extend(combinedEvents, events, triggers); Backbone.View.prototype.delegateEvents.call(this, combinedEvents); }, // Internal method, handles the `show` event. onShowCalled: function(){}, // Default `close` implementation, for removing a view from the // DOM and unbinding it. Regions will call this method // for you. You can specify an `onClose` method in your view to // add custom code that is called after the view is closed. close: function(){ if (this.isClosed) { return; } this.triggerMethod("before:close"); this.remove(); this.unbindAll(); this.triggerMethod("close"); this.isClosed = true; }, // This method binds the elements specified in the "ui" hash inside the view's code with // the associated jQuery selectors. bindUIElements: function(){ if (!this.ui) { return; } var that = this; if (!this.uiBindings) { // We want to store the ui hash in uiBindings, since afterwards the values in the ui hash // will be overridden with jQuery selectors. this.uiBindings = this.ui; } // refreshing the associated selectors since they should point to the newly rendered elements. this.ui = {}; _.each(_.keys(this.uiBindings), function(key) { var selector = that.uiBindings[key]; that.ui[key] = that.$(selector); }); }, // This method is used to bind a backbone "entity" (collection/model) to methods on the view. bindBackboneEntityTo: function(entity, bindings){ if (!entity || !bindings) { return; } var view = this; _.each(bindings, function(methodName, evt){ var method = view[methodName]; if(!method) { throw new Error("View method '"+ methodName +"' was configured as an event handler, but does not exist."); } view.bindTo(entity, evt, method, view); }); } }); // Item View // --------- // A single item view implementation that contains code for rendering // with underscore.js templates, serializing the view's model or collection, // and calling several methods on extended views, such as `onRender`. Marionette.ItemView = Marionette.View.extend({ constructor: function(){ Marionette.View.prototype.constructor.apply(this, arguments); if (this.initialEvents){ this.initialEvents(); } }, // Serialize the model or collection for the view. If a model is // found, `.toJSON()` is called. If a collection is found, `.toJSON()` // is also called, but is used to populate an `items` array in the // resulting data. If both are found, defaults to the model. // You can override the `serializeData` method in your own view // definition, to provide custom serialization for your view's data. serializeData: function(){ var data = {}; if (this.model) { data = this.model.toJSON(); } else if (this.collection) { data = { items: this.collection.toJSON() }; } return data; }, // Render the view, defaulting to underscore.js templates. // You can override this in your view definition to provide // a very specific rendering for your view. In general, though, // you should override the `Marionette.Renderer` object to // change how Marionette renders views. render: function(){ this.isClosed = false; this.triggerMethod("before:render", this); this.triggerMethod("item:before:render", this); var data = this.serializeData(); data = this.mixinTemplateHelpers(data); var template = this.getTemplate(); var html = Marionette.Renderer.render(template, data); this.$el.html(html); this.bindUIElements(); this.triggerMethod("render", this); this.triggerMethod("item:rendered", this); return this; }, // Override the default close event to add a few // more events that are triggered. close: function(){ if (this.isClosed){ return; } this.triggerMethod('item:before:close'); Marionette.View.prototype.close.apply(this, arguments); this.triggerMethod('item:closed'); } }); // Collection View // --------------- // A view that iterates over a Backbone.Collection // and renders an individual ItemView for each model. Marionette.CollectionView = Marionette.View.extend({ constructor: function(options){ this.initChildViewStorage(); Marionette.View.prototype.constructor.apply(this, arguments); this.initialEvents(); this.onShowCallbacks = new Marionette.Callbacks(); if (options && options.itemViewOptions) { this.itemViewOptions = options.itemViewOptions; } }, // Configured the initial events that the collection view // binds to. Override this method to prevent the initial // events, or to add your own initial events. initialEvents: function(){ if (this.collection){ this.bindTo(this.collection, "add", this.addChildView, this); this.bindTo(this.collection, "remove", this.removeItemView, this); this.bindTo(this.collection, "reset", this.render, this); } }, // Handle a child item added to the collection addChildView: function(item, collection, options){ this.closeEmptyView(); var ItemView = this.getItemView(item); var index; if(options && options.index){ index = options.index; } else { index = 0; } return this.addItemView(item, ItemView, index); }, // Override from `Marionette.View` to guarantee the `onShow` method // of child views is called. onShowCalled: function(){ this.onShowCallbacks.run(); }, // Internal method to trigger the before render callbacks // and events triggerBeforeRender: function(){ this.triggerMethod("before:render", this); this.triggerMethod("collection:before:render", this); }, // Internal method to trigger the rendered callbacks and // events triggerRendered: function(){ this.triggerMethod("render", this); this.triggerMethod("collection:rendered", this); }, // Render the collection of items. Override this method to // provide your own implementation of a render function for // the collection view. render: function(){ this.isClosed = false; this.triggerBeforeRender(); this.closeEmptyView(); this.closeChildren(); if (this.collection && this.collection.length > 0) { this.showCollection(); } else { this.showEmptyView(); } this.triggerRendered(); return this; }, // Internal method to loop through each item in the // collection view and show it showCollection: function(){ var that = this; var ItemView; this.collection.each(function(item, index){ ItemView = that.getItemView(item); that.addItemView(item, ItemView, index); }); }, // Internal method to show an empty view in place of // a collection of item views, when the collection is // empty showEmptyView: function(){ var EmptyView = this.options.emptyView || this.emptyView; if (EmptyView && !this._showingEmptyView){ this._showingEmptyView = true; var model = new Backbone.Model(); this.addItemView(model, EmptyView, 0); } }, // Internal method to close an existing emptyView instance // if one exists. Called when a collection view has been // rendered empty, and then an item is added to the collection. closeEmptyView: function(){ if (this._showingEmptyView){ this.closeChildren(); delete this._showingEmptyView; } }, // Retrieve the itemView type, either from `this.options.itemView` // or from the `itemView` in the object definition. The "options" // takes precedence. getItemView: function(item){ var itemView = this.options.itemView || this.itemView; if (!itemView){ var err = new Error("An `itemView` must be specified"); err.name = "NoItemViewError"; throw err; } return itemView; }, // Render the child item's view and add it to the // HTML for the collection view. addItemView: function(item, ItemView, index){ var that = this; var view = this.buildItemView(item, ItemView); // Store the child view itself so we can properly // remove and/or close it later this.storeChild(view); this.triggerMethod("item:added", view); // Forward all child item view events through the parent, // prepending "itemview:" to the event name var childBinding = this.bindTo(view, "all", function(){ var args = slice.call(arguments); args[0] = "itemview:" + args[0]; args.splice(1, 0, view); that.triggerMethod.apply(that, args); }); // Store all child event bindings so we can unbind // them when removing / closing the child view this.childBindings = this.childBindings || {}; this.childBindings[view.cid] = childBinding; // Render it and show it var renderResult = this.renderItemView(view, index); // call onShow for child item views if (view.onShow){ this.onShowCallbacks.add(view.onShow, view); } return renderResult; }, // render the item view renderItemView: function(view, index) { view.render(); this.appendHtml(this, view, index); }, // Build an `itemView` for every model in the collection. buildItemView: function(item, ItemView){ var itemViewOptions; if (_.isFunction(this.itemViewOptions)){ itemViewOptions = this.itemViewOptions(item); } else { itemViewOptions = this.itemViewOptions; } var options = _.extend({model: item}, itemViewOptions); var view = new ItemView(options); return view; }, // Remove the child view and close it removeItemView: function(item){ var view = this.children[item.cid]; if (view){ var childBinding = this.childBindings[view.cid]; if (childBinding) { this.unbindFrom(childBinding); delete this.childBindings[view.cid]; } view.close(); delete this.children[item.cid]; } if (!this.collection || this.collection.length === 0){ this.showEmptyView(); } this.triggerMethod("item:removed", view); }, // Append the HTML to the collection's `el`. // Override this method to do something other // then `.append`. appendHtml: function(collectionView, itemView, index){ collectionView.$el.append(itemView.el); }, // Store references to all of the child `itemView` // instances so they can be managed and cleaned up, later. storeChild: function(view){ this.children[view.model.cid] = view; }, // Internal method to set up the `children` object for // storing all of the child views initChildViewStorage: function(){ this.children = {}; }, // Handle cleanup and other closing needs for // the collection of views. close: function(){ if (this.isClosed){ return; } this.triggerMethod("collection:before:close"); this.closeChildren(); this.triggerMethod("collection:closed"); Marionette.View.prototype.close.apply(this, arguments); }, // Close the child views that this collection view // is holding on to, if any closeChildren: function(){ var that = this; if (this.children){ _.each(_.clone(this.children), function(childView){ that.removeItemView(childView.model); }); } } }); // Composite View // -------------- // Used for rendering a branch-leaf, hierarchical structure. // Extends directly from CollectionView and also renders an // an item view as `modelView`, for the top leaf Marionette.CompositeView = Marionette.CollectionView.extend({ constructor: function(options){ Marionette.CollectionView.apply(this, arguments); this.itemView = this.getItemView(); }, // Configured the initial events that the composite view // binds to. Override this method to prevent the initial // events, or to add your own initial events. initialEvents: function(){ if (this.collection){ this.bindTo(this.collection, "add", this.addChildView, this); this.bindTo(this.collection, "remove", this.removeItemView, this); this.bindTo(this.collection, "reset", this.renderCollection, this); } }, // Retrieve the `itemView` to be used when rendering each of // the items in the collection. The default is to return // `this.itemView` or Marionette.CompositeView if no `itemView` // has been defined getItemView: function(item){ var itemView = this.options.itemView || this.itemView || this.constructor; if (!itemView){ var err = new Error("An `itemView` must be specified"); err.name = "NoItemViewError"; throw err; } return itemView; }, // Serialize the collection for the view. // You can override the `serializeData` method in your own view // definition, to provide custom serialization for your view's data. serializeData: function(){ var data = {}; if (this.model){ data = this.model.toJSON(); } data = this.mixinTemplateHelpers(data); return data; }, // Renders the model once, and the collection once. Calling // this again will tell the model's view to re-render itself // but the collection will not re-render. render: function(){ this.isClosed = false; this.resetItemViewContainer(); var html = this.renderModel(); this.$el.html(html); // the ui bindings is done here and not at the end of render since they // will not be available until after the model is rendered, but should be // available before the collection is rendered. this.bindUIElements(); this.triggerMethod("composite:model:rendered"); this.renderCollection(); this.triggerMethod("composite:rendered"); return this; }, // Render the collection for the composite view renderCollection: function(){ Marionette.CollectionView.prototype.render.apply(this, arguments); this.triggerMethod("composite:collection:rendered"); }, // Render an individual model, if we have one, as // part of a composite view (branch / leaf). For example: // a treeview. renderModel: function(){ var data = {}; data = this.serializeData(); var template = this.getTemplate(); return Marionette.Renderer.render(template, data); }, // Appends the `el` of itemView instances to the specified // `itemViewContainer` (a jQuery selector). Override this method to // provide custom logic of how the child item view instances have their // HTML appended to the composite view instance. appendHtml: function(cv, iv){ var $container = this.getItemViewContainer(cv); $container.append(iv.el); }, // Internal method to ensure an `$itemViewContainer` exists, for the // `appendHtml` method to use. getItemViewContainer: function(containerView){ if ("$itemViewContainer" in containerView){ return containerView.$itemViewContainer; } var container; if (containerView.itemViewContainer){ var selector = _.result(containerView, "itemViewContainer"); container = containerView.$(selector); if (container.length <= 0) { var err = new Error("The specified `itemViewContainer` was not found: " + containerView.itemViewContainer); err.name = "ItemViewContainerMissingError"; throw err; } } else { container = containerView.$el; } containerView.$itemViewContainer = container; return container; }, // Internal method to reset the `$itemViewContainer` on render resetItemViewContainer: function(){ if (this.$itemViewContainer){ delete this.$itemViewContainer; } } }); // Region // ------ // // Manage the visual regions of your composite application. See // http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/ Marionette.Region = function(options){ this.options = options || {}; var el = this.options.el; delete this.options.el; Marionette.addEventBinder(this); if (el){ this.el = el; } if (!this.el){ var err = new Error("An 'el' must be specified for a region."); err.name = "NoElError"; throw err; } if (this.initialize){ this.initialize.apply(this, arguments); } }; // Region Type methods // ------------------- _.extend(Marionette.Region, { // Build an instance of a region by passing in a configuration object // and a default region type to use if none is specified in the config. // // The config object should either be a string as a jQuery DOM selector, // a Region type directly, or an object literal that specifies both // a selector and regionType: // // ```js // { // selector: "#foo", // regionType: MyCustomRegion // } // ``` // buildRegion: function(regionConfig, defaultRegionType){ var regionIsString = (typeof regionConfig === "string"); var regionSelectorIsString = (typeof regionConfig.selector === "string"); var regionTypeIsUndefined = (typeof regionConfig.regionType === "undefined"); var regionIsType = (typeof regionConfig === "function"); if (!regionIsType && !regionIsString && !regionSelectorIsString) { throw new Error("Region must be specified as a Region type, a selector string or an object with selector property"); } var selector, RegionType; // get the selector for the region if (regionIsString) { selector = regionConfig; } if (regionConfig.selector) { selector = regionConfig.selector; } // get the type for the region if (regionIsType){ RegionType = regionConfig; } if (!regionIsType && regionTypeIsUndefined) { RegionType = defaultRegionType; } if (regionConfig.regionType) { RegionType = regionConfig.regionType; } // build the region instance var regionManager = new RegionType({ el: selector }); return regionManager; } }); // Region Instance Methods // ----------------------- _.extend(Marionette.Region.prototype, Backbone.Events, { // Displays a backbone view instance inside of the region. // Handles calling the `render` method for you. Reads content // directly from the `el` attribute. Also calls an optional // `onShow` and `close` method on your view, just after showing // or just before closing the view, respectively. show: function(view){ this.ensureEl(); this.close(); view.render(); this.open(view); Marionette.triggerMethod.call(view, "show"); Marionette.triggerMethod.call(this, "show", view); this.currentView = view; }, ensureEl: function(){ if (!this.$el || this.$el.length === 0){ this.$el = this.getEl(this.el); } }, // Override this method to change how the region finds the // DOM element that it manages. Return a jQuery selector object. getEl: function(selector){ return $(selector); }, // Override this method to change how the new view is // appended to the `$el` that the region is managing open: function(view){ this.$el.html(view.el); }, // Close the current view, if there is one. If there is no // current view, it does nothing and returns immediately. close: function(){ var view = this.currentView; if (!view || view.isClosed){ return; } if (view.close) { view.close(); } Marionette.triggerMethod.call(this, "close"); delete this.currentView; }, // Attach an existing view to the region. This // will not call `render` or `onShow` for the new view, // and will not replace the current HTML for the `el` // of the region. attachView: function(view){ this.currentView = view; }, // Reset the region by closing any existing view and // clearing out the cached `$el`. The next time a view // is shown via this region, the region will re-query the // DOM for the region's `el`. reset: function(){ this.close(); delete this.$el; } }); // Copy the `extend` function used by Backbone's classes Marionette.Region.extend = Marionette.extend; // Layout // ------ // Used for managing application layouts, nested layouts and // multiple regions within an application or sub-application. // // A specialized view type that renders an area of HTML and then // attaches `Region` instances to the specified `regions`. // Used for composite view management and sub-application areas. Marionette.Layout = Marionette.ItemView.extend({ regionType: Marionette.Region, // Ensure the regions are avialable when the `initialize` method // is called. constructor: function () { this._firstRender = true; this.initializeRegions(); Backbone.Marionette.ItemView.apply(this, arguments); }, // Layout's render will use the existing region objects the // first time it is called. Subsequent calls will close the // views that the regions are showing and then reset the `el` // for the regions to the newly rendered DOM elements. render: function(){ if (this._firstRender){ // if this is the first render, don't do anything to // reset the regions this._firstRender = false; } else { // If this is not the first render call, then we need to // re-initializing the `el` for each region this.closeRegions(); this.reInitializeRegions(); } var result = Marionette.ItemView.prototype.render.apply(this, arguments); return result; }, // Handle closing regions, and then close the view itself. close: function () { if (this.isClosed){ return; } this.closeRegions(); this.destroyRegions(); Backbone.Marionette.ItemView.prototype.close.call(this, arguments); }, // Initialize the regions that have been defined in a // `regions` attribute on this layout. The key of the // hash becomes an attribute on the layout object directly. // For example: `regions: { menu: ".menu-container" }` // will product a `layout.menu` object which is a region // that controls the `.menu-container` DOM element. initializeRegions: function () { if (!this.regionManagers){ this.regionManagers = {}; } var that = this; var regions = this.regions || {}; _.each(regions, function (region, name) { var regionManager = Marionette.Region.buildRegion(region, that.regionType); regionManager.getEl = function(selector){ return that.$(selector); }; that.regionManagers[name] = regionManager; that[name] = regionManager; }); }, // Re-initialize all of the regions by updating the `el` that // they point to reInitializeRegions: function(){ if (this.regionManagers && _.size(this.regionManagers)===0){ this.initializeRegions(); } else { _.each(this.regionManagers, function(region){ region.reset(); }); } }, // Close all of the regions that have been opened by // this layout. This method is called when the layout // itself is closed. closeRegions: function () { var that = this; _.each(this.regionManagers, function (manager, name) { manager.close(); }); }, // Destroys all of the regions by removing references // from the Layout destroyRegions: function(){ var that = this; _.each(this.regionManagers, function (manager, name) { delete that[name]; }); this.regionManagers = {}; } }); // Application // ----------- // Contain and manage the composite application as a whole. // Stores and starts up `Region` objects, includes an // event aggregator as `app.vent` Marionette.Application = function(options){ this.initCallbacks = new Marionette.Callbacks(); this.vent = new Marionette.EventAggregator(); this.commands = new Backbone.Wreqr.Commands(); this.reqres = new Backbone.Wreqr.RequestResponse(); this.submodules = {}; _.extend(this, options); Marionette.addEventBinder(this); this.triggerMethod = Marionette.triggerMethod; }; _.extend(Marionette.Application.prototype, Backbone.Events, { // Command execution, facilitated by Backbone.Wreqr.Commands execute: function(){ this.commands.execute.apply(this.commands, arguments); }, // Request/response, facilitated by Backbone.Wreqr.RequestResponse request: function(){ return this.reqres.request.apply(this.reqres, arguments); }, // Add an initializer that is either run at when the `start` // method is called, or run immediately if added after `start` // has already been called. addInitializer: function(initializer){ this.initCallbacks.add(initializer); }, // kick off all of the application's processes. // initializes all of the regions that have been added // to the app, and runs all of the initializer functions start: function(options){ this.triggerMethod("initialize:before", options); this.initCallbacks.run(options, this); this.triggerMethod("initialize:after", options); this.triggerMethod("start", options); }, // Add regions to your app. // Accepts a hash of named strings or Region objects // addRegions({something: "#someRegion"}) // addRegions{{something: Region.extend({el: "#someRegion"}) }); addRegions: function(regions){ var that = this; _.each(regions, function (region, name) { var regionManager = Marionette.Region.buildRegion(region, Marionette.Region); that[name] = regionManager; }); }, // Removes a region from your app. // Accepts the regions name // removeRegion('myRegion') removeRegion: function(region) { this[region].close(); delete this[region]; }, // Create a module, attached to the application module: function(moduleNames, moduleDefinition){ // slice the args, and add this application object as the // first argument of the array var args = slice.call(arguments); args.unshift(this); // see the Marionette.Module object for more information return Marionette.Module.create.apply(Marionette.Module, args); } }); // Copy the `extend` function used by Backbone's classes Marionette.Application.extend = Marionette.extend; // AppRouter // --------- // Reduce the boilerplate code of handling route events // and then calling a single method on another object. // Have your routers configured to call the method on // your object, directly. // // Configure an AppRouter with `appRoutes`. // // App routers can only take one `controller` object. // It is recommended that you divide your controller // objects in to smaller peices of related functionality // and have multiple routers / controllers, instead of // just one giant router and controller. // // You can also add standard routes to an AppRouter. Marionette.AppRouter = Backbone.Router.extend({ constructor: function(options){ Backbone.Router.prototype.constructor.call(this, options); if (this.appRoutes){ var controller = this.controller; if (options && options.controller) { controller = options.controller; } this.processAppRoutes(controller, this.appRoutes); } }, // Internal method to process the `appRoutes` for the // router, and turn them in to routes that trigger the // specified method on the specified `controller`. processAppRoutes: function(controller, appRoutes){ var method, methodName; var route, routesLength, i; var routes = []; var router = this; for(route in appRoutes){ if (appRoutes.hasOwnProperty(route)){ routes.unshift([route, appRoutes[route]]); } } routesLength = routes.length; for (i = 0; i < routesLength; i++){ route = routes[i][0]; methodName = routes[i][1]; method = controller[methodName]; if (!method){ var msg = "Method '" + methodName + "' was not found on the controller"; var err = new Error(msg); err.name = "NoMethodError"; throw err; } method = _.bind(method, controller); router.route(route, methodName, method); } } }); // Module // ------ // A simple module system, used to create privacy and encapsulation in // Marionette applications Marionette.Module = function(moduleName, app){ this.moduleName = moduleName; // store sub-modules this.submodules = {}; this._setupInitializersAndFinalizers(); // store the configuration for this module this.config = {}; this.config.app = app; // extend this module with an event binder Marionette.addEventBinder(this); }; // Extend the Module prototype with events / bindTo, so that the module // can be used as an event aggregator or pub/sub. _.extend(Marionette.Module.prototype, Backbone.Events, { // Initializer for a specific module. Initializers are run when the // module's `start` method is called. addInitializer: function(callback){ this._initializerCallbacks.add(callback); }, // Finalizers are run when a module is stopped. They are used to teardown // and finalize any variables, references, events and other code that the // module had set up. addFinalizer: function(callback){ this._finalizerCallbacks.add(callback); }, // Start the module, and run all of it's initializers start: function(options){ // Prevent re-start the module if (this._isInitialized){ return; } // start the sub-modules (depth-first hierarchy) _.each(this.submodules, function(mod){ if (mod.config.options.startWithParent){ mod.start(options); } }); // run the callbacks to "start" the current module this._initializerCallbacks.run(options, this); this._isInitialized = true; }, // Stop this module by running its finalizers and then stop all of // the sub-modules for this module stop: function(){ // if we are not initialized, don't bother finalizing if (!this._isInitialized){ return; } this._isInitialized = false; // stop the sub-modules; depth-first, to make sure the // sub-modules are stopped / finalized before parents _.each(this.submodules, function(mod){ mod.stop(); }); // run the finalizers this._finalizerCallbacks.run(); // reset the initializers and finalizers this._initializerCallbacks.reset(); this._finalizerCallbacks.reset(); }, // Configure the module with a definition function and any custom args // that are to be passed in to the definition function addDefinition: function(moduleDefinition, customArgs){ this._runModuleDefinition(moduleDefinition, customArgs); }, // Internal method: run the module definition function with the correct // arguments _runModuleDefinition: function(definition, customArgs){ if (!definition){ return; } // build the correct list of arguments for the module definition var args = _.flatten([ this, this.config.app, Backbone, Marionette, $, _, customArgs ]); definition.apply(this, args); }, // Internal method: set up new copies of initializers and finalizers. // Calling this method will wipe out all existing initializers and // finalizers. _setupInitializersAndFinalizers: function(){ this._initializerCallbacks = new Marionette.Callbacks(); this._finalizerCallbacks = new Marionette.Callbacks(); } }); // Function level methods to create modules _.extend(Marionette.Module, { // Create a module, hanging off the app parameter as the parent object. create: function(app, moduleNames, moduleDefinition){ var that = this; var parentModule = app; moduleNames = moduleNames.split("."); // get the custom args passed in after the module definition and // get rid of the module name and definition function var customArgs = slice.apply(arguments); customArgs.splice(0, 3); // Loop through all the parts of the module definition var length = moduleNames.length; _.each(moduleNames, function(moduleName, i){ var isLastModuleInChain = (i === length-1); var module = that._getModuleDefinition(parentModule, moduleName, app); module.config.options = that._getModuleOptions(parentModule, moduleDefinition); // if it's the first module in the chain, configure it // for auto-start, as specified by the options if (isLastModuleInChain){ that._configureAutoStart(app, module); } // Only add a module definition and initializer when this is // the last module in a "parent.child.grandchild" hierarchy of // module names if (isLastModuleInChain && module.config.options.hasDefinition){ module.addDefinition(module.config.options.definition, customArgs); } // Reset the parent module so that the next child // in the list will be added to the correct parent parentModule = module; }); // Return the last module in the definition chain return parentModule; }, _configureAutoStart: function(app, module){ // Only add the initializer if it's the first module, and // if it is set to auto-start, and if it has not yet been added if (module.config.options.startWithParent && !module.config.autoStartConfigured){ // start the module when the app starts app.addInitializer(function(options){ module.start(options); }); } // prevent this module from being configured for // auto start again. the first time the module // is defined, determines it's auto-start module.config.autoStartConfigured = true; }, _getModuleDefinition: function(parentModule, moduleName, app){ // Get an existing module of this name if we have one var module = parentModule[moduleName]; if (!module){ // Create a new module if we don't have one module = new Marionette.Module(moduleName, app); parentModule[moduleName] = module; // store the module on the parent parentModule.submodules[moduleName] = module; } return module; }, _getModuleOptions: function(parentModule, moduleDefinition){ // default to starting the module with the app var options = { startWithParent: true, hasDefinition: !!moduleDefinition }; // short circuit if we don't have a module definition if (!options.hasDefinition){ return options; } if (_.isFunction(moduleDefinition)){ // if the definition is a function, assign it directly // and use the defaults options.definition = moduleDefinition; } else { // the definition is an object. // grab the "define" attribute options.hasDefinition = !!moduleDefinition.define; options.definition = moduleDefinition.define; // grab the "startWithParent" attribute if one exists if (moduleDefinition.hasOwnProperty("startWithParent")){ options.startWithParent = moduleDefinition.startWithParent; } } return options; } }); // Template Cache // -------------- // Manage templates stored in `<script>` blocks, // caching them for faster access. Marionette.TemplateCache = function(templateId){ this.templateId = templateId; }; // TemplateCache object-level methods. Manage the template // caches from these method calls instead of creating // your own TemplateCache instances _.extend(Marionette.TemplateCache, { templateCaches: {}, // Get the specified template by id. Either // retrieves the cached version, or loads it // from the DOM. get: function(templateId){ var that = this; var cachedTemplate = this.templateCaches[templateId]; if (!cachedTemplate){ cachedTemplate = new Marionette.TemplateCache(templateId); this.templateCaches[templateId] = cachedTemplate; } return cachedTemplate.load(); }, // Clear templates from the cache. If no arguments // are specified, clears all templates: // `clear()` // // If arguments are specified, clears each of the // specified templates from the cache: // `clear("#t1", "#t2", "...")` clear: function(){ var i; var length = arguments.length; if (length > 0){ for(i=0; i<length; i++){ delete this.templateCaches[arguments[i]]; } } else { this.templateCaches = {}; } } }); // TemplateCache instance methods, allowing each // template cache object to manage it's own state // and know whether or not it has been loaded _.extend(Marionette.TemplateCache.prototype, { // Internal method to load the template asynchronously. load: function(){ var that = this; // Guard clause to prevent loading this template more than once if (this.compiledTemplate){ return this.compiledTemplate; } // Load the template and compile it var template = this.loadTemplate(this.templateId); this.compiledTemplate = this.compileTemplate(template); return this.compiledTemplate; }, // Load a template from the DOM, by default. Override // this method to provide your own template retrieval, // such as asynchronous loading from a server. loadTemplate: function(templateId){ var template = $(templateId).html(); if (!template || template.length === 0){ var msg = "Could not find template: '" + templateId + "'"; var err = new Error(msg); err.name = "NoTemplateError"; throw err; } return template; }, // Pre-compile the template before caching it. Override // this method if you do not need to pre-compile a template // (JST / RequireJS for example) or if you want to change // the template engine used (Handebars, etc). compileTemplate: function(rawTemplate){ return _.template(rawTemplate); } }); // Renderer // -------- // Render a template with data by passing in the template // selector and the data to render. Marionette.Renderer = { // Render a template with data. The `template` parameter is // passed to the `TemplateCache` object to retrieve the // template function. Override this method to provide your own // custom rendering and template handling for all of Marionette. render: function(template, data){ var templateFunc = typeof template === 'function' ? template : Marionette.TemplateCache.get(template); var html = templateFunc(data); return html; } }; // Callbacks // --------- // A simple way of managing a collection of callbacks // and executing them at a later point in time, using jQuery's // `Deferred` object. Marionette.Callbacks = function(){ this._deferred = $.Deferred(); this._callbacks = []; }; _.extend(Marionette.Callbacks.prototype, { // Add a callback to be executed. Callbacks added here are // guaranteed to execute, even if they are added after the // `run` method is called. add: function(callback, contextOverride){ this._callbacks.push({cb: callback, ctx: contextOverride}); this._deferred.done(function(context, options){ if (contextOverride){ context = contextOverride; } callback.call(context, options); }); }, // Run all registered callbacks with the context specified. // Additional callbacks can be added after this has been run // and they will still be executed. run: function(options, context){ this._deferred.resolve(context, options); }, // Resets the list of callbacks to be run, allowing the same list // to be run multiple times - whenever the `run` method is called. reset: function(){ var that = this; var callbacks = this._callbacks; this._deferred = $.Deferred(); this._callbacks = []; _.each(callbacks, function(cb){ that.add(cb.cb, cb.ctx); }); } }); return Marionette; })(Backbone, _, $ || window.jQuery || window.Zepto || window.ender);
eladmoshe/storm-example
vendor/marionette/backbone.marionette.js
JavaScript
mit
51,192
"use strict"; exports.__esModule = true; exports.matchesPattern = matchesPattern; exports.has = has; exports.isnt = isnt; exports.equals = equals; exports.isNodeType = isNodeType; exports.canHaveVariableDeclarationOrExpression = canHaveVariableDeclarationOrExpression; exports.canSwapBetweenExpressionAndStatement = canSwapBetweenExpressionAndStatement; exports.isCompletionRecord = isCompletionRecord; exports.isStatementOrBlock = isStatementOrBlock; exports.referencesImport = referencesImport; exports.getSource = getSource; exports.willIMaybeExecuteBefore = willIMaybeExecuteBefore; exports._guessExecutionStatusRelativeTo = _guessExecutionStatusRelativeTo; exports.resolve = resolve; exports._resolve = _resolve; // istanbul ignore next function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } // istanbul ignore next function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _lodashCollectionIncludes = require("lodash/collection/includes"); var _lodashCollectionIncludes2 = _interopRequireDefault(_lodashCollectionIncludes); var _types = require("../../types"); var t = _interopRequireWildcard(_types); /** * Match the current node if it matches the provided `pattern`. * * For example, given the match `React.createClass` it would match the * parsed nodes of `React.createClass` and `React["createClass"]`. */ function matchesPattern(pattern, allowPartial) { // not a member expression if (!this.isMemberExpression()) return false; var parts = pattern.split("."); var search = [this.node]; var i = 0; function matches(name) { var part = parts[i]; return part === "*" || name === part; } while (search.length) { var node = search.shift(); if (allowPartial && i === parts.length) { return true; } if (t.isIdentifier(node)) { // this part doesn't match if (!matches(node.name)) return false; } else if (t.isLiteral(node)) { // this part doesn't match if (!matches(node.value)) return false; } else if (t.isMemberExpression(node)) { if (node.computed && !t.isLiteral(node.property)) { // we can't deal with this return false; } else { search.unshift(node.property); search.unshift(node.object); continue; } } else if (t.isThisExpression(node)) { if (!matches("this")) return false; } else { // we can't deal with this return false; } // too many parts if (++i > parts.length) { return false; } } return i === parts.length; } /** * Check whether we have the input `key`. If the `key` references an array then we check * if the array has any items, otherwise we just check if it's falsy. */ function has(key) { var val = this.node[key]; if (val && Array.isArray(val)) { return !!val.length; } else { return !!val; } } /** * Alias of `has`. */ var is = has; exports.is = is; /** * Opposite of `has`. */ function isnt(key) { return !this.has(key); } /** * Check whether the path node `key` strict equals `value`. */ function equals(key, value) { return this.node[key] === value; } /** * Check the type against our stored internal type of the node. This is handy when a node has * been removed yet we still internally know the type and need it to calculate node replacement. */ function isNodeType(type) { return t.isType(this.type, type); } /** * This checks whether or not we're in one of the following positions: * * for (KEY in right); * for (KEY;;); * * This is because these spots allow VariableDeclarations AND normal expressions so we need * to tell the path replacement that it's ok to replace this with an expression. */ function canHaveVariableDeclarationOrExpression() { return (this.key === "init" || this.key === "left") && this.parentPath.isFor(); } /** * This checks whether we are swapping an arrow function's body between an * expression and a block statement (or vice versa). * * This is because arrow functions may implicitly return an expression, which * is the same as containing a block statement. */ function canSwapBetweenExpressionAndStatement(replacement) { if (this.key !== "body" || !this.parentPath.isArrowFunctionExpression()) { return false; } if (this.isExpression()) { return t.isBlockStatement(replacement); } else if (this.isBlockStatement()) { return t.isExpression(replacement); } return false; } /** * Check whether the current path references a completion record */ function isCompletionRecord(allowInsideFunction) { var path = this; var first = true; do { var container = path.container; // we're in a function so can't be a completion record if (path.isFunction() && !first) { return !!allowInsideFunction; } first = false; // check to see if we're the last item in the container and if we are // we're a completion record! if (Array.isArray(container) && path.key !== container.length - 1) { return false; } } while ((path = path.parentPath) && !path.isProgram()); return true; } /** * Check whether or not the current `key` allows either a single statement or block statement * so we can explode it if necessary. */ function isStatementOrBlock() { if (this.parentPath.isLabeledStatement() || t.isBlockStatement(this.container)) { return false; } else { return _lodashCollectionIncludes2["default"](t.STATEMENT_OR_BLOCK_KEYS, this.key); } } /** * Check if the currently assigned path references the `importName` of `moduleSource`. */ function referencesImport(moduleSource, importName) { if (!this.isReferencedIdentifier()) return false; var binding = this.scope.getBinding(this.node.name); if (!binding || binding.kind !== "module") return false; var path = binding.path; var parent = path.parentPath; if (!parent.isImportDeclaration()) return false; // check moduleSource if (parent.node.source.value === moduleSource) { if (!importName) return true; } else { return false; } if (path.isImportDefaultSpecifier() && importName === "default") { return true; } if (path.isImportNamespaceSpecifier() && importName === "*") { return true; } if (path.isImportSpecifier() && path.node.imported.name === importName) { return true; } return false; } /** * Get the source code associated with this node. */ function getSource() { var node = this.node; if (node.end) { return this.hub.file.code.slice(node.start, node.end); } else { return ""; } } /** * [Please add a description.] */ function willIMaybeExecuteBefore(target) { return this._guessExecutionStatusRelativeTo(target) !== "after"; } /** * Given a `target` check the execution status of it relative to the current path. * * "Execution status" simply refers to where or not we **think** this will execuete * before or after the input `target` element. */ function _guessExecutionStatusRelativeTo(target) { // check if the two paths are in different functions, we can't track execution of these var targetFuncParent = target.scope.getFunctionParent(); var selfFuncParent = this.scope.getFunctionParent(); if (targetFuncParent !== selfFuncParent) { return "function"; } var targetPaths = target.getAncestry(); //if (targetPaths.indexOf(this) >= 0) return "after"; var selfPaths = this.getAncestry(); // get ancestor where the branches intersect var commonPath; var targetIndex; var selfIndex; for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) { var selfPath = selfPaths[selfIndex]; targetIndex = targetPaths.indexOf(selfPath); if (targetIndex >= 0) { commonPath = selfPath; break; } } if (!commonPath) { return "before"; } // get the relationship paths that associate these nodes to their common ancestor var targetRelationship = targetPaths[targetIndex - 1]; var selfRelationship = selfPaths[selfIndex - 1]; if (!targetRelationship || !selfRelationship) { return "before"; } // container list so let's see which one is after the other if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) { return targetRelationship.key > selfRelationship.key ? "before" : "after"; } // otherwise we're associated by a parent node, check which key comes before the other var targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key); var selfKeyPosition = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key); return targetKeyPosition > selfKeyPosition ? "before" : "after"; } /** * Resolve a "pointer" `NodePath` to it's absolute path. */ function resolve(dangerous, resolved) { return this._resolve(dangerous, resolved) || this; } /** * [Please add a description.] */ function _resolve(dangerous, resolved) { // detect infinite recursion // todo: possibly have a max length on this just to be safe if (resolved && resolved.indexOf(this) >= 0) return; // we store all the paths we've "resolved" in this array to prevent infinite recursion resolved = resolved || []; resolved.push(this); if (this.isVariableDeclarator()) { if (this.get("id").isIdentifier()) { return this.get("init").resolve(dangerous, resolved); } else { // otherwise it's a request for a pattern and that's a bit more tricky } } else if (this.isReferencedIdentifier()) { var binding = this.scope.getBinding(this.node.name); if (!binding) return; // reassigned so we can't really resolve it if (!binding.constant) return; // todo - lookup module in dependency graph if (binding.kind === "module") return; if (binding.path !== this) { return binding.path.resolve(dangerous, resolved); } } else if (this.isTypeCastExpression()) { return this.get("expression").resolve(dangerous, resolved); } else if (dangerous && this.isMemberExpression()) { // this is dangerous, as non-direct target assignments will mutate it's state // making this resolution inaccurate var targetKey = this.toComputedKey(); if (!t.isLiteral(targetKey)) return; var targetName = targetKey.value; var target = this.get("object").resolve(dangerous, resolved); if (target.isObjectExpression()) { var props = target.get("properties"); var _arr = props; for (var _i = 0; _i < _arr.length; _i++) { var prop = _arr[_i]; if (!prop.isProperty()) continue; var key = prop.get("key"); // { foo: obj } var match = prop.isnt("computed") && key.isIdentifier({ name: targetName }); // { "foo": "obj" } or { ["foo"]: "obj" } match = match || key.isLiteral({ value: targetName }); if (match) return prop.get("value").resolve(dangerous, resolved); } } else if (target.isArrayExpression() && !isNaN(+targetName)) { var elems = target.get("elements"); var elem = elems[targetName]; if (elem) return elem.resolve(dangerous, resolved); } } }
yuyang545262477/Resume
项目三jQueryMobile/node_modules/babel-core/lib/traversal/path/introspection.js
JavaScript
mit
11,416
'use strict' const val = require('./val') const valUpdate = val.update const valCreate = val.create const simpleUpdate = val.simpleUpdate const remove = require('./remove') const composite = require('./composite') module.exports = function struct (key, target, subs, update, tree, treeKey, stamp, self, force) { var changed if (target && (!('val' in target) || target.val !== null)) { let leafStamp = (target._sid || target.sid()) + target.stamp let traveltarget if (target.val && !self && target.val.isBase) { traveltarget = target.origin() } else { traveltarget = target } if (!treeKey) { treeKey = tree[key] = { _p: tree, _key: key } treeKey.$ = leafStamp valCreate(target, traveltarget, subs, update, treeKey, stamp, force) changed = true } else { if (treeKey.$ !== leafStamp || force && force[target._sid]) { treeKey.$ = leafStamp valUpdate(target, traveltarget, subs, update, treeKey, stamp, force) changed = true } else if ('$c' in treeKey) { changed = composite(traveltarget, subs, update, treeKey, stamp, void 0, force) if (changed) { simpleUpdate(target, subs, update, treeKey, stamp) } } } } else if (treeKey) { remove(key, target, target, subs, update, tree, treeKey, stamp) changed = true } return changed }
vigour-io/state
lib/subscribe/struct.js
JavaScript
isc
1,384
import { t, localizer } from '../../core/localizer'; import { localize } from './helper'; import { presetManager } from '../../presets'; import { prefs } from '../../core/preferences'; import { fileFetcher } from '../../core/file_fetcher'; import { coreGraph } from '../../core/graph'; import { modeBrowse } from '../../modes/browse'; import { osmEntity } from '../../osm/entity'; import { svgIcon } from '../../svg/icon'; import { uiCurtain } from '../curtain'; import { utilArrayDifference, utilArrayUniq } from '../../util'; import { uiIntroWelcome } from './welcome'; import { uiIntroNavigation } from './navigation'; import { uiIntroPoint } from './point'; import { uiIntroArea } from './area'; import { uiIntroLine } from './line'; import { uiIntroBuilding } from './building'; import { uiIntroStartEditing } from './start_editing'; const chapterUi = { welcome: uiIntroWelcome, navigation: uiIntroNavigation, point: uiIntroPoint, area: uiIntroArea, line: uiIntroLine, building: uiIntroBuilding, startEditing: uiIntroStartEditing }; const chapterFlow = [ 'welcome', 'navigation', 'point', 'area', 'line', 'building', 'startEditing' ]; export function uiIntro(context) { const INTRO_IMAGERY = 'EsriWorldImageryClarity'; let _introGraph = {}; let _currChapter; function intro(selection) { fileFetcher.get('intro_graph') .then(dataIntroGraph => { // create entities for intro graph and localize names for (let id in dataIntroGraph) { if (!_introGraph[id]) { _introGraph[id] = osmEntity(localize(dataIntroGraph[id])); } } selection.call(startIntro); }) .catch(function() { /* ignore */ }); } function startIntro(selection) { context.enter(modeBrowse(context)); // Save current map state let osm = context.connection(); let history = context.history().toJSON(); let hash = window.location.hash; let center = context.map().center(); let zoom = context.map().zoom(); let background = context.background().baseLayerSource(); let overlays = context.background().overlayLayerSources(); let opacity = context.container().selectAll('.main-map .layer-background').style('opacity'); let caches = osm && osm.caches(); let baseEntities = context.history().graph().base().entities; // Show sidebar and disable the sidebar resizing button // (this needs to be before `context.inIntro(true)`) context.ui().sidebar.expand(); context.container().selectAll('button.sidebar-toggle').classed('disabled', true); // Block saving context.inIntro(true); // Load semi-real data used in intro if (osm) { osm.toggle(false).reset(); } context.history().reset(); context.history().merge(Object.values(coreGraph().load(_introGraph).entities)); context.history().checkpoint('initial'); // Setup imagery let imagery = context.background().findSource(INTRO_IMAGERY); if (imagery) { context.background().baseLayerSource(imagery); } else { context.background().bing(); } overlays.forEach(d => context.background().toggleOverlayLayer(d)); // Setup data layers (only OSM) let layers = context.layers(); layers.all().forEach(item => { // if the layer has the function `enabled` if (typeof item.layer.enabled === 'function') { item.layer.enabled(item.id === 'osm'); } }); context.container().selectAll('.main-map .layer-background').style('opacity', 1); let curtain = uiCurtain(); selection.call(curtain); // Store that the user started the walkthrough.. prefs('walkthrough_started', 'yes'); // Restore previous walkthrough progress.. let storedProgress = prefs('walkthrough_progress') || ''; let progress = storedProgress.split(';').filter(Boolean); let chapters = chapterFlow.map((chapter, i) => { let s = chapterUi[chapter](context, curtain.reveal) .on('done', () => { presetManager.init(); // clear away "recent" presets buttons .filter(d => d.title === s.title) .classed('finished', true); if (i < chapterFlow.length - 1) { const next = chapterFlow[i + 1]; context.container().select(`button.chapter-${next}`) .classed('next', true); } // Store walkthrough progress.. progress.push(chapter); prefs('walkthrough_progress', utilArrayUniq(progress).join(';')); }); return s; }); chapters[chapters.length - 1].on('startEditing', () => { // Store walkthrough progress.. progress.push('startEditing'); prefs('walkthrough_progress', utilArrayUniq(progress).join(';')); // Store if walkthrough is completed.. let incomplete = utilArrayDifference(chapterFlow, progress); if (!incomplete.length) { prefs('walkthrough_completed', 'yes'); } curtain.remove(); navwrap.remove(); context.container().selectAll('.main-map .layer-background').style('opacity', opacity); context.container().selectAll('button.sidebar-toggle').classed('disabled', false); if (osm) { osm.toggle(true).reset().caches(caches); } context.history().reset().merge(Object.values(baseEntities)); context.background().baseLayerSource(background); overlays.forEach(d => context.background().toggleOverlayLayer(d)); if (history) { context.history().fromJSON(history, false); } context.map().centerZoom(center, zoom); window.location.replace(hash); context.inIntro(false); }); let navwrap = selection .append('div') .attr('class', 'intro-nav-wrap fillD'); navwrap .append('svg') .attr('class', 'intro-nav-wrap-logo') .append('use') .attr('xlink:href', '#iD-logo-walkthrough'); let buttonwrap = navwrap .append('div') .attr('class', 'joined') .selectAll('button.chapter'); let buttons = buttonwrap .data(chapters) .enter() .append('button') .attr('class', (d, i) => `chapter chapter-${chapterFlow[i]}`) .on('click', enterChapter); buttons .append('span') .text(d => t(d.title)); buttons .append('span') .attr('class', 'status') .call(svgIcon((localizer.textDirection() === 'rtl' ? '#iD-icon-backward' : '#iD-icon-forward'), 'inline')); enterChapter(chapters[0]); function enterChapter(newChapter) { if (_currChapter) { _currChapter.exit(); } context.enter(modeBrowse(context)); _currChapter = newChapter; _currChapter.enter(); buttons .classed('next', false) .classed('active', d => d.title === _currChapter.title); } } return intro; }
morray/iD
modules/ui/intro/intro.js
JavaScript
isc
6,823
import mod123 from './mod123'; var value=mod123+1; export default value;
MirekSz/webpack-es6-ts
app/mods/mod124.js
JavaScript
isc
73
var login = { pokemon = "PutYourTokenHere"; } module.exports = login;
EspritOrgue/PokeBot
login.template.js
JavaScript
isc
73
// Copyright (c) 2016, David M. Lee, II require('babel-polyfill'); require('babel-register')({ retainLines: typeof v8debug !== 'undefined', }); require('./src/cli');
building5/utf8mb4-converter
server.js
JavaScript
isc
168
const Either = require('data.either') const parseCommentRenderer = require('./parse-comment-renderer') const traverse = require('./utils/traverse-array') const { cheerioFindAll } = require('./utils/cheerio-utils') const parseReplies = $replies => cheerioFindAll($replies, '.comment-renderer').chain($commentRenderers => traverse($commentRenderers, Either.of, parseCommentRenderer) ) module.exports = parseReplies
philbot9/youtube-comments-task
src/lib/parse-replies.js
JavaScript
isc
425
import * as mat3 from '../../../gl-matrix/esm/mat3.js' export default class Matrix3 extends Float32Array { constructor(array = [1, 0, 0, 0, 1, 0, 0, 0, 1]) { super(array) return this } set x(value) { this[6] = value } get x() { return this[6] } set y(value) { this[7] = value } get y() { return this[7] } set z(value) { this[8] = value } get z() { return this[8] } set(m00, m01, m02, m10, m11, m12, m20, m21, m22) { mat3.set(this, m00, m01, m02, m10, m11, m12, m20, m21, m22) return this } translate(vector2, matrix3 = this) { mat3.translate(this, matrix3, vector2) return this } rotate(value, matrix3 = this) { mat3.rotate(this, matrix3, value) return this } scale(vector2, matrix3 = this) { mat3.scale(this, matrix3, vector2) return this } multiply(matrix3a, matrix3b) { if (matrix3b) { mat3.multiply(this, matrix3a, matrix3b) } else { mat3.multiply(this, this, matrix3a) } return this } identity() { mat3.identity(this) return this } copy(matrix3) { mat3.copy(this, matrix3) return this } fromMatrix4(matrix4) { mat3.fromMat4(this, matrix4) return this } fromQuaternion(quaternion) { mat3.fromQuat(this, quaternion) return this } fromBasis(vector3a, vector3b, vector3c) { this.set(vector3a[0], vector3a[1], vector3a[2], vector3b[0], vector3b[1], vector3b[2], vector3c[0], vector3c[1], vector3c[2]) return this } normalMatrixFromTransform(matrix4) { mat3.normalFromMat4(this, matrix4) return this } invert(matrix3 = this) { mat3.invert(this, matrix3) return this } }
damienmortini/dlib
packages/core/math/Matrix3.js
JavaScript
isc
1,712
import Vue from 'vue' import FacebookButton from '~/components/FacebookButton' import TwitterButton from '~/components/TwitterButton' import Modal from '~/components/Modal' import Disclaimer from '~/components/Disclaimer' import PageFooter from '~/components/PageFooter' import DonateButton from '~/components/DonateButton' const components = { FacebookButton, TwitterButton, Modal, Disclaimer, PageFooter, DonateButton } Object.keys(components).forEach(key => { Vue.component(key, components[key]) })
fightforthefuture/battleforthenet
plugins/components.js
JavaScript
isc
518
import a from './a'; import other from './other'; export default [a, other];
mzgoddard/hard-source-webpack-plugin
tests/fixtures/base-change-es2015-export-order-module/index.js
JavaScript
isc
77
describe('iD.behaviorLasso', function () { var context, lasso; beforeEach(function () { context = iD.coreContext().assetPath('../dist/').init(); d3.select(document.createElement('div')) .attr('class', 'main-map') .call(context.map()); lasso = iD.behaviorLasso(context); }); afterEach(function () { lasso.off(context.surface()); }); it('can be initialized', function () { expect(context.surface().call(lasso)).to.be.ok; }); });
openstreetmap/iD
test/spec/behavior/lasso.js
JavaScript
isc
522
/** @license ISC License (c) copyright 2016 original and current authors */ /** @author Ian Hofmann-Hicks (evil) */ const compose = require('../core/compose') const curry = require('../core/curry') const isFunction = require('../core/isFunction') // contramap : Functor f => (b -> a) -> f b -> f a function contramap(fn, m) { if(!isFunction(fn)) { throw new TypeError( 'contramap: Function required for first argument' ) } if(isFunction(m)) { return compose(m, fn) } if(m && isFunction(m.contramap)) { return m.contramap(fn) } throw new TypeError( 'contramap: Function or Contavariant Functor of the same type required for second argument' ) } module.exports = curry(contramap)
rstegg/crocks
src/pointfree/contramap.js
JavaScript
isc
725
import template from './me.html'; import styles from './me.scss'; export default { template, bindings: { myname: '<', userData: '<' }, controller }; function controller() { this.styles = styles; this.activityLevels = [ {desc: 'None', value: 1}, {desc: 'Average', value: 2}, {desc: 'Active', value: 3}, {desc: 'Very Active', value: 4} ]; this.dietaryGuide = {}; this.$onInit = () => { this.myData = this.userData[0]; this.currentUser = JSON.parse(localStorage.getItem('user')); this.myActivityLevel = this.activityLevels[1]; this.dietaryGuide = this.makeGuide(this.myActivityLevel.value); }; this.getEaten = () => { const storedEaten = this.myData.eaten; let displayEaten = []; if (storedEaten.length > 7) { displayEaten = storedEaten.slice(-7); } else { dispalyEaten = storedEaten.slice(0); } // calories let theChartTitle = 'Nutritional Info'; let theChartData = []; displayEaten.forEach(function(element, idx, array ) { totCals.push(element.Calories || 0); totCarbs.push(element.Carbs || 0); totFats.push(element.totalFats || 0); totProtein.push(element.totalProtein || 0); theChartLabels.push(element.time || 'none'); }); }; this.showChart = () => { }; this.updateView = (newActivityLevel) => { this.dietaryGuide = this.makeGuide(newActivityLevel); }; //AJ's formula will go here to calculate a person's daily calorie needs; this.makeGuide = (activityLevel) => { let age = this.myData.age; let height = this.myData.height; let weight = this.myData.weight; let gender = this.myData.gender; let bEE = 0; let metricWeight = (weight / 2.2); let metricHeight = (height * 2.54); let dietGuide = {}; // Determine the Basal Energy Expenditure if (gender === 'male') { bEE = (66.5 + (13.8 * metricWeight) + (5.0 * metricHeight) - (6.8 * age)); } else { bEE = (655.1 + (9.6 * metricWeight) + (1.9 * metricHeight) - (4.7 * age)); }; // Activity level, 0 = none, 1 = average, 3 = active, 4 = Very active if (activityLevel === 4) { bEE = bEE * 1.5; } else if (activityLevel === 3) { bEE = bEE * 1.25; } else if (activityLevel === 2) { bEE = bEE * 1.1; } else { bEE = bEE; // Get up and move }; dietGuide.calories = bEE.toFixed(0); dietGuide.carbTarget = ((bEE * .5) / 4).toFixed(0); // 45% - 65% cals from carbs dietGuide.fatMax = ((bEE * .33) / 9).toFixed(0); // 1/3 cals from fats dietGuide.proteinTarget = (metricWeight * .9).toFixed(0); // .8 - 1.0 grams per kilo return dietGuide; }; //also any custom nutrition informationconsole.log(this.currentUser); }
FoodDudes/WikiDiet
app/src/components/me/me.js
JavaScript
isc
3,073
var previous_method = _.isApi(); _.isApi = function isApi() { return true; }; var api_server = new Test_ApiServer(function handler(request, callback) { Logger.errorAndExit(` API should not recursively perform API calls `); }); function handler(error, results) { if (error) { return void Logger.errorAndExit(error); } _.isApi = previous_method; api_server.destroy(); Logger.successAndExit(` Test completed successfully `); } var resource_map = new API_ResourceMap(); var account_resource = new API_Resource_Accounts({ resource_map: resource_map }); account_resource.setResourceMap(resource_map); (new Validator_Account_Username()) .setKey('username') .setValue('meansucker') .setAccessType(API_Enum_AccessTypes.COLLECT) .setAttributes({ }) .setResource(account_resource) .validate(handler);
burninggarden/burninggarden
test/integration/validator/account/username.js
JavaScript
isc
821
const config = require('./config'); const sqlite3 = require('sqlite3').verbose(); const sqliteDB = new sqlite3.Database(config.database); module.exports = { dbGetAll : function(sql, parameters){ return new Promise((resolve, reject) => { sqliteDB.all(sql, parameters, (err, rows) => { if(err){ return reject(err); } return resolve(rows); }); }); }, dbGetSingle : function(sql, parameters){ return new Promise((resolve, reject) => { sqliteDB.get(sql, parameters, (err, row) => { if(err){ return reject(err); } return resolve(row); }); }); }, dbGetSingleField : function(sql, parameters, field){ let _self = this; return new Promise((resolve, reject) => { _self.dbGetSingle(sql, parameters).then((row) => { return resolve(row[field]) }).catch((err) => { return reject(err); }); }); }, dbInsert : function(table, qdata){ return new Promise((resolve, reject) => { let placeholder_keys = []; let placeholders = {}; let key_string = []; Object.getOwnPropertyNames(qdata).forEach((v, i, a) => { let key = '$'+ v; placeholder_keys.push(key); placeholders[key] = qdata[v]; key_string.push(v); }); let sql = "INSERT INTO "+ table +" ("+ key_string.join(',') +") VALUES ("+ placeholder_keys.join(',') +");"; let stmt = sqliteDB.prepare(sql); stmt.run(placeholders, (err) => { if(err){ return reject(err); } return resolve(); }); }); }, dbRun : function(sql, conlog){ return new Promise((resolve, reject) => { sqliteDB.serialize(() => { sqliteDB.run(sql, (err) => { if(err){ return reject(err); } if(conlog){ console.log(conlog); } return resolve(); }); }); }); } }
lewiswalsh/lwLog
_db_sqlite.js
JavaScript
isc
1,989
version https://git-lfs.github.com/spec/v1 oid sha256:afb0d16c5aa4e99452be348057be14cf182ba53251d9cd0bd096274f99b442f0 size 29432
yogeshsaroya/new-cdnjs
ajax/libs/shepherd/0.6.14/shepherd.min.js
JavaScript
mit
130
// i truly apologize for this: // the dirtiest multipart parser ever // (c) Copyright 2011, Christopher Jeffrey (//github.com/chjj) (MIT Licensed) module.exports = function evilpart(type, body) { var parts = {}, key, part; type = (type || '').match(/boundary=([^;]+)/); if (!type || !body) return parts; key = '--' + type[1].trim() .replace(/^["']|["']$/g, '') .replace(/([-.*+?^${}()|\[\]\\])/g, '\\$1'); part = new RegExp(key + '\\r\\n([\\s\\S]+?)\\r\\n(?=' + key + ')', 'g'); body.replace(part, function(__, data) { var head = {}, meta = {}; data = data.match(/^([\s\S]+?)(?:\r\n){2}([\s\S]+)$/); if (!data) return; data[1].replace(/([^\s:]+):([^\r\n]+)/g, function(__, key, val) { head[key.toLowerCase()] = val.trim(); }); if (!head['content-disposition']) return; head['content-disposition'] .replace(/([^;\s=]+)=([^;]+)/g, function(__, key, val) { key = key.trim().replace(/^["']|["']$/g, '').toLowerCase(); val = val.trim().replace(/^["']|["']$/g, ''); meta[key] = val; }); if (!meta.name && !meta.filename) return; data = data[2]; if (head['content-encoding'] === 'base64') { data = new Buffer(data, 'base64'); } parts[meta.name || meta.filename] = { name: meta.name, filename: meta.filename, data: data }; }); return parts; };
chjj/evilpart
evilpart.js
JavaScript
mit
1,390
const EventEmitter = require('events'); const emitterProxy = require('../lib/ee-proxy'); const user = new EventEmitter(); user.once('disconnect', () => console.log('User disconnected')); class Game extends EventEmitter { constructor(user) { super(); this._user = emitterProxy(user); this._user.once('game:cancel', () => this._onUserLeft()); this._user.once('disconnect', () => this._onUserLeft()); } start() { this._user.on('game:message', message => console.log('game:message', message)); this._user.on('game:command', command => console.log('game:command', command)); } _onUserLeft() { console.log('User left the game'); this._user.stopListening(); // removes only game listeners ("game:message" and "game:command" events) this.emit('canceled'); } } const game = new Game(user); game.start(); console.log(user.eventNames()); game.once('canceled', () => { console.log(user.eventNames()); }); user.emit('game:cancel');
Jokero/events-cleanup
examples/index.js
JavaScript
mit
1,025
/** * Sort Stack * * Write a program to sort a stack such that the smallest items are on the top. * You can use an additional temporary stack, but you may not copy the elements into any other data structure * (such as an array). The stack supports the following operations: push(), pop(), peek() and isEmpty() * */ const Stack = require('../../../collections/Stack'); // Approach: push onto a temp stack while the data is larger than temp.peek() // if the data is smaller, shift data from temp onto the main stack until the smaller data can be added in order // once all the data is in temp, shift it back onto the main stack such that the smallest data is on top // // Worst case run time is O(n^2) // function sortStack(stack) { let temp = new Stack(); while (stack.count) { let data = stack.pop(); if (!temp.isEmpty() && data < temp.peek()) { while (data < temp.peek()) { stack.push(temp.pop()); } } temp.push(data); } while (temp.count) { stack.push(temp.pop()); } return stack; } const should = require('should'); const tests = [ new Stack({data: [2, 5, 3, 1, 6, 9, 7]}), new Stack({data: [8, 4, 4, 7, 1, 2, 2, 3]}) ]; const expected = [ new Stack({data: [9, 7, 6, 5, 3, 2, 1]}), new Stack({data: [8, 7, 4, 4, 3, 2, 2, 1]}) ]; for (let i in tests) { let input = tests[i].getData(); sortStack(tests[i]).getData().should.eql(expected[i].getData()); console.log('sortStack([' + input.join() + ']) -> [' + expected[i].getData().join() + ']'); } console.log('\nSuccess!\n'); module.exports = sortStack;
pbodalia/algorithms-js
src/exercises/cracking_the_coding_interview/stacks_queues/SortStack.js
JavaScript
mit
1,681
// check that the userId specified owns the documents ownsDocument = function(userId, doc) { return doc && doc.userId === userId; } memberInProject = function(userId, pm, projectUsers) { return (_.contains(projectUsers, userId) || userId == pm); }
kchen17/pm-tool-tmp
lib/permissions.js
JavaScript
mit
251
// Boiler plate code for adding stage // Declare state vars only used in this state var state_var_1; var state_var_2; // Change boilerplate to whatever name demo.boilerplate = function(){}; demo.boilerplate.prototype = { preload: function(){ // Always include this line loadImages(); // Make this equal to the size of the tilemap var tilemap_height = 3600; game.world.setBounds(0, 0, 1000, tilemap_height); // Load any tiles required for tile map // This should be customized for each stage game.load.tilemap('stage', 'assets/tilemaps/Tutorial/TestMapFitted.json', null, Phaser.Tilemap.TILED_JSON); game.load.image('grass_platform', 'assets/tilemaps/Tutorial/grass_platform.png'); game.load.image('ladder_sprite', 'assets/tilemaps/Tutorial/new_ladder_sprite.png'); game.load.image('ladder_sprite_top', 'assets/tilemaps/Tutorial/new_ladder_sprite.png'); }, create: function(){ // Stop sounds when starting a state game.sound.stopAll(); // start game at bottom of screen game.camera.y = game.world.height; // Add game background // change 'bg1' to whatever is required add_game_bg('bg1') //////////////////////////////////////////// // Add in tilemap // Vaidehi, please generalize this as needed map = game.add.tilemap('stage'); map.addTilesetImage('grass_platform'); map.addTilesetImage('ladder_sprite'); map.addTilesetImage('ladder_sprite_top'); layer1 = map.createLayer('Platforms'); layer2 = map.createLayer('Ladders'); layer1.resizeWorld(); layer2.resizeWorld(); // Make sure to enable arcade for all layers so boss doesn't go wherever it wants game.physics.arcade.enable(layer1); game.physics.arcade.enable(layer2); // set collisions for the tilemaps map.setCollisionBetween(1, 3, true, layer1); map.setCollisionBetween(4, 5, true, layer2); // load in sound guitar1 = game.add.audio('guitar'); // loops guitar music guitar1.play('','',0.5,true,true); /////////////////////////////////////////////// // Add chameleon at x,y createChameleon(500,game.world.height - 400); // make groups make_fruit_groups(); make_enemy_groups(); make_balloon_group(); addMovingPlatforms(); make_healthpack_groups(); // Examples: // placeFruit(700, 2700, "bluefruit") // var snake1 = placeSnake(300, 2000, ["blue"]); // snake1.mytween = game.add.tween(snake1).to({x:[200, 300], y:[2000,2000]}, 4000, Phaser.Easing.Linear.None, true, 0, -1, false); // placeBalloon(100, 3100); // placeMP(150, 2700, 3, 1, 2, 2, 100, 100); // placeHealthpack(900, 2600); // These should be the last thing added so that it is on top of all other sprites (never hidden) createInventory(0, 525); place_hearts(450, 0); add_pause_darkener(); game.input.onDown.add(pause_clicking, self); }, update: function(){ // Collide with layers that are necessary game.physics.arcade.collide(player, layer1); move_camera(1,1); if (player.ballooning) { chameleon_float(); } else { chameleonmove(); // ladder movement if not floating // here, layer 2 is your ladder layer // 4 & 5 are indices of ladder tiles var tile_arr = get_surrounding_tiles(layer2, map); ladder_movement(tile_arr, 4, 5); } birds_group.forEach(moveBird, this); snakes_group.forEach(moveSnake, this); moving_platform_group.forEach(movingPlatformsUpdate, this); update_health(player.health); }, } // tween examples // snake 1 moves from (200, 2000) to (300, 2000) and back, looping infinitely // var snake1 = placeSnake(300, 2000, ["blue"]); // snake1.mytween = game.add.tween(snake1).to({x:[200, 300], y:[2000,2000]}, 4000, Phaser.Easing.Linear.None, true, 0, -1, false); // snake 2 moves from (200, 300) to (500, 600) // var snake2 = placeSnake(300, 2000, ["blue"]); // snake2.mytween = game.add.tween(snake2).from({x:200, y:300}, 4000, Phaser.Easing.Linear.None, true); // Tween waits before starting // var snake1 = placeSnake(300, 2000, ["blue"]); // snake1.mytween = game.add.tween(snake1).to({x:[200, 300], y:[2000,2000]}, 4000, Phaser.Easing.Linear.None, true, 2000, -1, false); // Relative values for moving tween // var snake1 = placeSnake(300, 2000, ["blue"]); // snake1.mytween = game.add.tween(snake1).to({x:'+200'}, 4000, Phaser.Easing.Linear.None, true, 0, -1, false); // You can add a tween to camera //var rumbleOffset = 10; //var properties = {x: game.camera.x - rumbleOffset}; //// we make it a really fast movement //var duration = 100; //// because it will repeat //var repeat = 4; //// we use bounce in-out to soften it a little bit //var ease = Phaser.Easing.Bounce.InOut; //var autoStart = false; //// a little delay because we will run it indefinitely //var delay = 1000; //// we want to go back to the original position //var yoyo = true; // var quake = game.add.tween(game.camera).to(properties, duration, ease, autoStart, delay, 4, yoyo);
MasahiroWard/MVPgamedev
Game/state_boilerplate.js
JavaScript
mit
5,570
define([ 'dojo/_base/declare', 'dijit/_WidgetBase', 'dijit/_TemplatedMixin', 'dijit/_WidgetsInTemplateMixin', 'esri/toolbars/draw', 'esri/tasks/query', 'esri/tasks/GeometryService', 'dojo/_base/lang', 'dojo/on', 'dojo/dom-style', 'dojo/aspect', 'dojo/topic', 'dojo/keys', // template 'dojo/text!./Search/templates/Search.html', //i18n 'dojo/i18n!./Search/nls/Search', //template widgets 'dijit/layout/LayoutContainer', 'dijit/layout/ContentPane', 'dijit/layout/TabContainer', 'dijit/form/Select', 'dijit/form/TextBox', 'dijit/form/NumberTextBox', 'dijit/form/Button', 'dijit/form/CheckBox', // css 'xstyle/css!./Search/css/Search.css', 'xstyle/css!./Search/css/Draw.css' ], function ( declare, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, Draw, Query, GeometryService, lang, on, domStyle, aspect, topic, keys, template, i18n ) { return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], { name: 'Search', baseClass: 'cmvSearchWidget', widgetsInTemplate: true, templateString: template, mapClickMode: null, // i18n i18n: i18n, title: 'Search Results', topicID: 'searchResults', attributesContainerID: 'attributesContainer', shapeLayer: 0, attributeLayer: 0, drawToolbar: null, drawingOptions: { rectangle: true, circle: true, point: true, polyline: true, freehandPolyline: true, polygon: true, freehandPolygon: true, identifiedFeature: true, selectedFeatures: false }, bufferUnits: [ { value: GeometryService.UNIT_FOOT, label: 'Feet', selected: true }, { value: GeometryService.UNIT_STATUTE_MILE, label: 'Miles' }, { value: GeometryService.UNIT_METER, label: 'Meters' }, { value: GeometryService.UNIT_KILOMETER, label: 'Kilometers' }, { value: GeometryService.UNIT_NAUTICAL_MILE, label: 'Nautical Miles' }, { value: GeometryService.UNIT_US_NAUTICAL_MILE, label: 'US Nautical Miles' } ], postCreate: function () { this.inherited(arguments); this.initLayerSelect(); this.selectBufferUnits.set('options', this.bufferUnits); this.drawToolbar = new Draw(this.map); this.enableDrawingButtons(); if (this.map.infoWindow) { on(this.map.infoWindow, 'show', lang.hitch(this, 'enableIdentifyButton')); on(this.map.infoWindow, 'hide', lang.hitch(this, 'disableIdentifyButton')); } this.own(on(this.drawToolbar, 'draw-end', lang.hitch(this, 'endDrawing'))); for (var k = 0; k < 5; k++) { this.own(on(this['inputSearchTerm' + k], 'keyup', lang.hitch(this, 'executeSearchWithReturn'))); } this.addTopics(); }, startup: function () { this.inherited(arguments); var parent = this.getParent(); if (parent) { this.own(on(parent, 'show', lang.hitch(this, function () { this.tabContainer.resize(); }))); } aspect.after(this, 'resize', lang.hitch(this, function () { this.tabContainer.resize(); })); }, addTopics: function () { this.own(topic.subscribe('mapClickMode/currentSet', lang.hitch(this, 'setMapClickMode'))); this.own(topic.subscribe('searchWidget/search', lang.hitch(this, 'executeSearch'))); }, /******************************* * Search Functions *******************************/ executeSearchWithReturn: function (evt) { if (evt.keyCode === keys.ENTER) { this.onSearch(); } }, search: function (geometry, layerIndex) { if (!this.layers) { return; } if (this.layers.length === 0) { return; } var distance, unit, showOnly = false; var layer = this.layers[layerIndex]; var where = layer.expression || ''; var search = layer.attributeSearches[this.searchIndex] || {}; if (geometry) { distance = this.inputBufferDistance.get('value'); if (isNaN(distance)) { topic.publish('growler/growl', { title: 'Search', message: 'Invalid distance', level: 'error', timeout: 3000 }); return; } unit = this.selectBufferUnits.get('value'); showOnly = this.checkBufferOnly.get('checked'); } else { var fields = search.searchFields; var len = fields.length; for (var k = 0; k < len; k++) { var field = fields[k]; var searchTerm = this.getSearchTerm(k, field); if (searchTerm === null) { return; } else if (searchTerm.length > 0 && field.expression) { var attrWhere = field.expression; attrWhere = attrWhere.replace(/\[value\]/g, searchTerm); if (!attrWhere) { break; } if (where !== '') { where += ' AND '; } where += attrWhere; } } } var queryOptions = { idProperty: search.idProperty || layer.idProperty || 'FID', linkField: search.linkField || layer.linkField || null, linkedQuery: lang.clone(search.linkedQuery || layer.linkedQuery || null) }; var queryParameters = lang.clone(search.queryParameters || layer.queryParameters || {}); queryOptions.queryParameters = lang.mixin(queryParameters, { //type: search.type || layer.type || 'spatial', geometry: geometry, where: where, outSpatialReference: search.outSpatialReference || this.map.spatialReference, spatialRelationship: search.spatialRelationship || layer.spatialRelationship || Query.SPATIAL_REL_INTERSECTS }); var bufferParameters = lang.clone(search.bufferParameters || layer.bufferParameters || {}); queryOptions.bufferParameters = lang.mixin(bufferParameters, { distance: distance, unit: unit, showOnly: showOnly }); // publish to an accompanying attributed table topic.publish(this.attributesContainerID + '/addTable', { title: search.title || layer.title || this.title, topicID: search.topicID || layer.topicID || this.topicID, queryOptions: queryOptions, gridOptions: lang.clone(search.gridOptions || layer.gridOptions || {}), featureOptions: lang.clone(search.featureOptions || layer.featureOptions || {}), symbolOptions: lang.clone(search.symbolOptions || layer.symbolOptions || {}), toolbarOptions: lang.clone(search.toolbarOptions || layer.toolbarOptions || {}), infoTemplate: search.infoTemplate || layer.infoTemplate }); }, getSearchTerm: function (idx, field) { var searchTerm = this['inputSearchTerm' + idx].get('value'); if (!searchTerm && field.required) { this['inputSearchTerm' + idx].domNode.focus(); topic.publish('growler/growl', { title: 'Search', message: 'You must provide a search term for ' + field.name + '.', level: 'error', timeout: 3000 }); return null; } if (field.minChars && field.required) { if (searchTerm.length < field.minChars) { topic.publish('growler/growl', { title: 'Search', message: 'Search term for ' + field.name + ' must be at least ' + field.minChars + ' characters.', level: 'error', timeout: 3000 }); return null; } } return searchTerm; }, // a topic subscription to listen for published topics executeSearch: function (options) { if (options.searchTerm) { this.inputSearchTerm0.set('value', options.searchTerm); } if (options.bufferDistance) { this.inputBufferDistance.set('value', options.bufferDistance); if (options.bufferUnits) { this.selectBufferUnits.set('value', options.bufferUnits); } } this.search(options.geometry, options.layerIndex); }, /******************************* * Form/Field Functions *******************************/ initLayerSelect: function () { var attrOptions = [], shapeOptions = []; var len = this.layers.length, option; for (var i = 0; i < len; i++) { option = { value: i, label: this.layers[i].name }; attrOptions.push(lang.clone(option)); if (this.layers[i].queryParameters && this.layers[i].queryParameters.type === 'spatial') { option.value = (shapeOptions.length); shapeOptions.push(option); } } if (attrOptions.length > 0) { this.selectLayerByAttribute.set('options', attrOptions); this.onAttributeLayerChange(this.attributeLayer); } else { this.selectLayerByAttribute.set('disabled', true); } if (shapeOptions.length > 0) { this.selectLayerByShape.set('options', shapeOptions); this.onShapeLayerChange(this.shapeLayer); } else { this.selectLayerByShape.set('disabled', true); } }, onShapeLayerChange: function (newValue) { this.shapeLayer = newValue; }, onAttributeLayerChange: function (newValue) { this.attributeLayer = newValue; this.selectAttributeQuery.set('disabled', true); var layer = this.layers[this.attributeLayer]; if (layer) { this.selectAttributeQuery.set('value', null); this.selectAttributeQuery.set('options', null); var searches = layer.attributeSearches; var options = []; var len = searches.length; for (var i = 0; i < len; i++) { var option = { value: i, label: searches[i].name }; options.push(option); if (i === 0) { options[i].selected = true; } } if (len) { this.selectAttributeQuery.set('options', options); this.selectAttributeQuery.set('disabled', false); this.selectAttributeQuery.set('value', 0); this.onAttributeQueryChange(0); domStyle.set(this.divAttributeQuerySelect, 'display', (len > 1) ? 'block' : 'none'); } } }, onAttributeQueryChange: function (newValue) { this.searchIndex = newValue; var layer = this.layers[this.attributeLayer]; if (layer) { var searches = layer.attributeSearches; if (searches) { var search = searches[newValue]; if (search) { // initialize all the search field inputs var fields = search.searchFields; for (var k = 0; k < 10; k++) { var display = 'block', disabled = false; var formLabel = this['labelSearchTerm' + k]; var formInput = this['inputSearchTerm' + k]; if (formInput) { var field = fields[k]; if (field) { var txt = field.label + ':'; if (field.minChars) { txt += ' (at least ' + field.minChars + ' chars)'; } formLabel.textContent = txt; formInput.set('value', ''); formInput.set('placeHolder', field.placeholder); } else { display = 'none'; disabled = true; } formInput.set('disabled', disabled); domStyle.set(formInput.domNode, 'display', display); domStyle.set(formLabel, 'display', display); } } // put focus on the first input field this.inputSearchTerm0.domNode.focus(); this.btnSearch.set('disabled', false); } } } }, onSearch: function () { this.search(null, this.attributeLayer); }, /******************************* * Drawing Functions *******************************/ enableDrawingButtons: function () { var opts = this.drawingOptions; var disp = (opts.rectangle !== false) ? 'inline-block' : 'none'; domStyle.set(this.searchRectangleButtonDijit.domNode, 'display', disp); disp = (opts.circle !== false) ? 'inline-block' : 'none'; domStyle.set(this.searchCircleButtonDijit.domNode, 'display', disp); disp = (opts.point !== false) ? 'inline-block' : 'none'; domStyle.set(this.searchPointButtonDijit.domNode, 'display', disp); disp = (opts.polyline !== false) ? 'inline-block' : 'none'; domStyle.set(this.searchPolylineButtonDijit.domNode, 'display', disp); disp = (opts.freehandPolyline !== false) ? 'inline-block' : 'none'; domStyle.set(this.searchFreehandPolylineButtonDijit.domNode, 'display', disp); disp = (opts.polygon !== false) ? 'inline-block' : 'none'; domStyle.set(this.searchPolygonButtonDijit.domNode, 'display', disp); disp = (opts.freehandPolygon !== false) ? 'inline-block' : 'none'; domStyle.set(this.searchFreehandPolygonButtonDijit.domNode, 'display', disp); disp = (opts.identifiedFeatures !== false) ? 'inline-block' : 'none'; domStyle.set(this.searchIdentifyButtonDijit.domNode, 'display', disp); disp = (opts.selectedFeatures !== false) ? 'inline-block' : 'none'; domStyle.set(this.searchSelectedButtonDijit.domNode, 'display', disp); }, prepareForDrawing: function (btn) { // is btn checked? var chk = btn.get('checked'); this.cancelDrawing(); if (chk) { // toggle btn to checked state btn.set('checked', true); } return chk; }, drawRectangle: function () { var btn = this.searchRectangleButtonDijit; if (this.prepareForDrawing(btn)) { this.drawToolbar.activate(Draw.EXTENT); } }, drawCircle: function () { var btn = this.searchCircleButtonDijit; if (this.prepareForDrawing(btn)) { this.drawToolbar.activate(Draw.CIRCLE); } }, drawPoint: function () { var btn = this.searchPointButtonDijit; if (this.prepareForDrawing(btn)) { this.drawToolbar.activate(Draw.POINT); } }, drawPolyline: function () { var btn = this.searchPolylineButtonDijit; if (this.prepareForDrawing(btn)) { this.drawToolbar.activate(Draw.POLYLINE); } }, drawFreehandPolyline: function () { var btn = this.searchFreehandPolylineButtonDijit; if (this.prepareForDrawing(btn)) { this.drawToolbar.activate(Draw.FREEHAND_POLYLINE); } }, drawPolygon: function () { var btn = this.searchPolygonButtonDijit; if (this.prepareForDrawing(btn)) { this.drawToolbar.activate(Draw.POLYGON); } }, drawFreehandPolygon: function () { var btn = this.searchFreehandPolygonButtonDijit; if (this.prepareForDrawing(btn)) { this.drawToolbar.activate(Draw.FREEHAND_POLYGON); } }, uncheckDrawingTools: function () { this.searchRectangleButtonDijit.set('checked', false); this.searchCircleButtonDijit.set('checked', false); this.searchPointButtonDijit.set('checked', false); this.searchPolylineButtonDijit.set('checked', false); this.searchFreehandPolylineButtonDijit.set('checked', false); this.searchPolygonButtonDijit.set('checked', false); this.searchFreehandPolygonButtonDijit.set('checked', false); }, endDrawing: function(evt) { var clickMode = this.mapClickMode; this.uncheckDrawingTools(); this.map.enableMapNavigation(); this.drawToolbar.deactivate(); this.connectMapClick(); if (clickMode === 'search') { var geometry = evt.geometry; if (geometry) { this.search(geometry, this.shapeLayer); } } }, cancelDrawing: function () { this.hideInfoWindow(); this.disconnectMapClick(); this.uncheckDrawingTools(); }, onDrawToolbarDrawEnd: function (graphic) { this.map.enableMapNavigation(); this.drawToolbar.deactivate(); this.connectMapClick(); this.search(graphic.geometry, this.shapeLayer); }, /******************************* * Using Identify Functions *******************************/ useIdentifiedFeatures: function () { var popup = this.map.infoWindow; if (popup && popup.isShowing) { var feature = popup.getSelectedFeature(); if (feature) { popup.hide(); this.search(feature.geometry, this.shapeLayer); return; } } topic.publish('growler/growl', { title: 'Search', message: 'You must have identified a feature', level: 'error', timeout: 3000 }); }, enableIdentifyButton: function () { this.searchIdentifyButtonDijit.set('disabled', false); }, disableIdentifyButton: function () { this.searchIdentifyButtonDijit.set('disabled', true); }, /******************************* * Using Selected Functions *******************************/ // not yet implemented - need a selection widget useSelectedFeatures: function () { /* var selected = false; if (selected) { var feature = this.getSelectedFeatures(); if (feature) { this.search(feature.geometry, this.shapeLayer); return; } } */ topic.publish('growler/growl', { title: 'Search', message: 'You must have selected feature(s)', level: 'error', timeout: 3000 }); }, enableSelectedButton: function () { this.searchSelectedButtonDijit.set('disabled', false); }, disableSelectedButton: function () { this.searchSelectedButtonDijit.set('disabled', true); }, /******************************* * Miscellaneous Functions *******************************/ hideInfoWindow: function () { if (this.map && this.map.infoWindow) { this.map.infoWindow.hide(); } }, disconnectMapClick: function () { topic.publish('mapClickMode/setCurrent', 'search'); }, connectMapClick: function () { topic.publish('mapClickMode/setDefault'); }, setMapClickMode: function (mode) { this.mapClickMode = mode; }, onLayoutChange: function (open) { if (!open && this.mapClickMode === 'search') { this.connectMapClick(); this.drawToolbar.deactivate(); this.inherited(arguments); } } }); });
fileunderjeff/cmv-app
viewer/js/widgets/Search.js
JavaScript
mit
22,470
var isInit = false, log, sanitize; /* Merge Objects * Combine two object's attributes giving priority * to the first object's (obj1) attribute values. */ function mergeObjects(obj1, obj2) { for(var key in obj2) { if(obj1[key] === undefined) obj1[key] = obj2[key]; } return obj1; } var lib = { loadById: function loadById(Schema, queryObject, populateFields, populateSelects, populateModels, populateConditions) { return loadById[Schema, queryObject, populateFields, populateSelects, populateModels, populateConditions] || (loadById[Schema, queryObject, populateFields, populateSelects, populateModels, populateConditions] = function(req, res, next) { if(req.params[queryObject]) { populateFields = (populateFields) ? populateFields : ""; populateSelects = (populateSelects) ? populateSelects : ""; populateModels = (populateModels) ? populateModels : ""; populateConditions = (populateConditions) ? populateConditions : ""; Schema.findById(req.params[queryObject]).populate(populateFields, populateSelects, populateModels, populateConditions).exec(function(err, obj) { if(err) { next(err); } else if( ! obj){ log.w("Could not find schema object. Query Object:", debug); log.w("\t" + queryObject); } else { req.queryResult = obj; } return next(); }); } else { return next(); } }); }, /** * * Parameters: * obj - * currentObject - * userId - * next - */ update: function update(obj, currentObject, userId, isUpdated, next) { return update[obj, currentObject, userId, isUpdated, next] || (update[obj, currentObject, userId, isUpdated, next] = function() { var now = Date.now, value = undefined; // Check if any changes were made to the object. // If there were not, then return, we are done here. if( ! isUpdated) { if(next !== undefined) { return next(undefined, true); } return true; } // check for a valid update object. if( ! obj) { var err = new Error('Cannot update the schema object because the first parameter "obj" is not valid.') err.status = 500; // If a callback was supplied, then pass the error on. if(next !== undefined) { return next(err); } // Otherwise just print the error. return log.e(err); } // Update the last updated by attribute with the parameter object's // information or the userId parameter. If neither is present, then // set the value to undefined because we don't know who updated it last. value = sanitize.objectId(obj['lastUpdatedBy']); currentObject['lastUpdatedBy'] = (value) ? value : sanitize.objectId(userId); // Update the last updated date and time with the parameter object's // informaiton or the time this function was called. value = sanitize.objectId(obj['lastUpdated']); currentObject['lastUpdated'] = (value) ? value : now; currentObject.save(function(err, currentObject) { // If the current object was not returned, // and there was no error, then create a generic error. if(! user && ! err) { var err = new Error('There was a problem saving the updated user object.'); err.status = 500; } // If there were any errors, then return them or log them. if(err) { if(next !== undefined) { return next(err); } return log.e(err); } // Upon success, call the next function if we can. if(next !== undefined) { next(undefined, currentObject); } }); }); }, load: function load(Schema, queryObject, opts) { if(!queryObject) { queryObject = {}; } return load[Schema, queryObject, opts] || (load[Schema, queryObject, opts] = function(req, res, next) { //return function(req, res, next) { var sort = ""; var query = mergeObjects(req.query, queryObject); log.d("Query: " + JSON.stringify(query)); if(opts) { sort = (opts["sort"]) ? opts["sort"] : ""; } Schema.find(query).sort(sort).exec(function(err, obj) { if(err) { next(err); } else if( ! obj){ log.w("Could not find schema object. Query Object:", debug); log.w("\t" + query); } else { req.queryResult = obj; } return next(); }); }); } } /* ************************************************** * * ******************** Initialization Method * ************************************************** */ var init = function(config) { if(isInit) { return lib; } else { log = require(config.paths.serverLibFolder + "log")(config); sanitize = require(config.paths.nodeModulesFolder + "sanitize-it"); isInit = true; return lib; } } // Export the library function. exports = module.exports = init;
ssmereka/quickie-js
server/libs/model.js
JavaScript
mit
5,184
var month_names = ['January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; /*** * Base animal class. All animals are descended from this. ***/ Animal = function(type) { this.type = type; this._dob = new Date(); this.dob = function(){ return this._dob.getDay() + '/' + month_names[this._dob.getMonth()] + '/' + this._dob.getYear() } this.change_direction_counter = 510; /*** * Sets the animals name * * If called without a name - generate a funny name ***/ this.set_name = function(name) { this.name = name || 'funny name here'; } /*** * * Phaser parts * ***/ var x = game.world.randomX; var y = game.world.randomY; this.animal = game.add.sprite(x, y, 'chicken'); this.animal.width = 20; this.animal.height = 20; game.physics.enable(this.animal, Phaser.Physics.ARCADE); game.physics.arcade.enableBody(this.animal); group_universe.add(this.animal); } /*** * Custom update method ***/ Animal.prototype.update = function() { if (this.change_direction_counter > 500) { this.animal.body.velocity.x = (Math.round(Math.random()) * 2 - 1) * 10; this.animal.body.velocity.y = (Math.round(Math.random()) * 2 - 1) * 10; this.change_direction_counter = 0; } else { this.change_direction_counter++; } } /*** * Globals ***/ var game; var group_universe; // A group for scaling everything (zooming) var game_world_bounds = {x:0,y:0, width:1200, height:1200}; window.onload = function() { game = new Phaser.Game( window.innerWidth * window.devicePixelRatio, // width (set game to size of browser viewport) window.innerHeight * window.devicePixelRatio, // height (set game to size of browser viewport) /*1200, 1200,*/ /*'100%', '100%',*/ Phaser.AUTO, // WebGL with canvas fallback 'world-canvas', // DOM id of element to contain phaser canvas { preload: preload, create: create, update: update, render: render }); function preload() { game.load.image('planet', 'world.png'); game.load.image('chicken', 'chicken.jpg'); } function create() { group_universe = game.add.group(); game.stage.disableVisibilityChange = true; // Don't pause game if browser window loses focus // Game world is size of browser viewport - set the world to actually be much bigger // (size of animal world - plus a bit extra for some space around it) game.world.setBounds(0,0,1200,1200); game.physics.startSystem(Phaser.Physics.ARCADE); var planet_x_pos = game.world.centerX - (game.cache.getImage('planet').width / 2); var planet_y_pos = game.world.centerY - (game.cache.getImage('planet').height / 2); var planet = game.add.sprite(planet_x_pos, planet_y_pos, 'planet'); //var planet = game.add.sprite(0,0,'planet'); group_universe.add(planet); //group_universe.scale = new Phaser.Point(0.4,0.4) // The 0.4 percentage is of the original scale, not of the last scale the group had //animals = game.add.group(); animals = [] //animals.add(new Animal('chicken')); for (var i=0; i<1000; i++) { animals.push(new Animal('chicken')); } zoom_pan_setup(); } function update() { for (var i = 0; i < animals.length; i++) { animals[i].update(); } } function render() { } }; function dets(){ console.log('game.world.width=',game.world.width); console.log('game.world.scale=',game.world.scale); console.log('game.world.bounds=',game.world.bounds); console.log('game.camera.width=',game.camera.width); console.log('game.camera.scale=',game.camera.scale); console.log('game.camera.xy=',game.camera.x,',',game.camera.y); console.log('game.stage.width=',game.stage.width); console.log('game.stage.scale=',game.stage.scale); console.log('game.stage.getBounds()=',game.stage.getBounds()); }
benopotamus/vegeworld
js/world.js
JavaScript
mit
3,871
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M16.5 6v11.5c0 2.21-1.79 4-4 4s-4-1.79-4-4V5c0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5v10.5c0 .55-.45 1-1 1s-1-.45-1-1V6H10v9.5c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5V5c0-2.21-1.79-4-4-4S7 2.79 7 5v12.5c0 3.04 2.46 5.5 5.5 5.5s5.5-2.46 5.5-5.5V6h-1.5z" /></g> , 'AttachFile');
cherniavskii/material-ui
packages/material-ui-icons/src/AttachFile.js
JavaScript
mit
401
/** * koa服务入口文件 */ const Koa=require('koa') const router=require('koa-router')() const bodyParser=require('koa-bodyparser') const path=require('path') const static=require('koa-static') //创建Koa对象 const app=new Koa() router.get('/', async (ctx, next)=>{ let url=ctx.url let request_query=ctx.request.query let request_querystring=ctx.request.querystring let ctx_query=ctx.query let ctx_querystring=ctx.querystring ctx.response.type='aplication/json' ctx.response.body={ url, request_query, request_querystring, ctx_query, ctx_querystring } }) router.get('/login', async (ctx, next)=>{ let html=` <h1>用户登录页面</h1> <form method="POST" action="/login_do"> <p>UserName</p> <input type="text" name="username" /><br/> <p>Password</p> <input type="password" name="password" /><br/><br/> <button type="submit">submit</button> </form> ` ctx.response.body=html }) router.post('/login_do', async (ctx, next)=>{ //直接利用ctx.request.body获取表单提交数据 let postData=ctx.request.body ctx.response.type='aplication/json' ctx.response.body=postData }) //add koa-bodyparser middleware app.use(bodyParser()) //add router middleware app.use(router.routes()) app.use(router.allowedMethods()) //add static middleware app.use(static(path.join(__dirname, './static'))) //监听端口 app.listen(8080) console.log('koabon server is starting at port 8080')
leeyu0329/koabon
koastatic/app.js
JavaScript
mit
1,449
/** * Just like `relp_basic.js` but this one is for the docker example */ addInputPlugin('relp', { host: '0.0.0.0', port: 5514 }) addOutputPlugin('stdout')
nbrownus/streamstash
examples/relp_container.js
JavaScript
mit
159
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "M6.41 6 5 7.41 9.58 12 5 16.59 6.41 18l6-6z" }, "0"), /*#__PURE__*/_jsx("path", { d: "m13 6-1.41 1.41L16.17 12l-4.58 4.59L13 18l6-6z" }, "1")], 'KeyboardDoubleArrowRight');
oliviertassinari/material-ui
packages/mui-icons-material/lib/esm/KeyboardDoubleArrowRight.js
JavaScript
mit
338
"use strict"; var language = require("eberon/eberon_grammar.js").language; var nodejs = require("nodejs.js"); var options = { "--include": "includeDirs", "--out-dir": "outDir", "--import-dir": "importDir", "--timing": "timing" }; function parseOption(a, result){ for(var o in options){ var optionPrefix = o + "="; if (a.indexOf(optionPrefix) === 0){ result[options[o]] = a.substr(optionPrefix.length); return; } } result.notParsed.push(a); } function parseOptions(argv){ var result = {notParsed: []}; for(var i = 0; i < argv.length; ++i) parseOption(argv[i], result); return result; } function main(){ var args = parseOptions(process.argv.splice(2)); var sources = args.notParsed; if (!sources.length){ console.info("Usage: <oc_nodejs> [options] <input oberon module file(s)>"); console.info("options:\n--include=<search directories separated by ';'>\n--out-dir=<out dir>\n--import-dir=<import dir>"); return -1; } var includeDirs = (args.includeDirs && args.includeDirs.split(";")) || []; var outDir = args.outDir || "."; var errors = ""; var start = args.timing == "true" ? (new Date()).getTime() : undefined; var success = nodejs.compile(sources, language, function(e){ console.error(e); errors += e + "\n"; }, includeDirs, outDir, args.importDir ); if (!success) return -2; if (start){ var stop = (new Date()).getTime(); console.log("elapsed: " + (stop - start) / 1000 + " s" ); } console.info("OK!"); return 0; } // process.exit(main()); // hack to avoid problem with not flushed stdout on exit: https://github.com/joyent/node/issues/1669 var rc = main(); process.stdout.once("drain", function(){process.exit(rc);}); process.stdout.write("");
vladfolts/oberonjs
src/oc_nodejs.js
JavaScript
mit
2,048
// LICENSE : MIT "use strict"; const React = require("react"); const PropTypes = require("prop-types"); import SVGIcon from "../../uikit/SVGIcon/SVGIcon"; import Color from "../../../js/domain/value/Color"; export default class IconPalette extends React.Component { render() { /** * @type {Color} */ const color = this.props.color; const fillColor = { color: color.hexCode, fill: color.hexCode }; return ( <div className="IconPalette"> <SVGIcon name="check" style={fillColor} /> <SVGIcon name="hearts" style={fillColor} /> <SVGIcon name="play" style={fillColor} /> <span className="IconPalette-hexCode">{color.hexCode}</span> </div> ); } } IconPalette.propTypes = { color: PropTypes.instanceOf(Color).isRequired };
almin/almin
examples/svg-feeling/src/component/project/IconPalette/IconPalette.js
JavaScript
mit
905
'use strict'; var chai = require('chai'); var expect = chai.expect; var assert = chai.assert; var chaihttp = require('chai-http'); let port = process.env.PORT || 3000; chai.use(chaihttp); require('../server.js'); // Tests that make sure server can load basic HTML pages describe('Test that server can load basic html pages', function () { //create task to test that server can load a basic web pages it('Should load homepage', function (done) { chai.request('localhost:' + port) .get('/') .end(function (err, res) { expect(err).to.eql(null); expect(res.status).to.eql(200); assert.equal(res.header['content-type'], 'text/html; charset=UTF-8'); done(); }); }); it('Should load about page', function (done) { chai.request('localhost:' + port) .get('/about') .end(function (err, res) { expect(err).to.eql(null); expect(res.status).to.eql(200); assert.equal(res.header['content-type'], 'text/html; charset=UTF-8'); done(); }); }); it('Should load past events page', function (done) { chai.request('localhost:' + port) .get('/past-events') .end(function (err, res) { expect(err).to.eql(null); expect(res.status).to.eql(200); assert.equal(res.header['content-type'], 'text/html; charset=UTF-8'); done(); }); }); it('Should load meet the team page', function (done) { chai.request('localhost:' + port) .get('/meet-the-team') .end(function (err, res) { expect(err).to.eql(null); expect(res.status).to.eql(200); assert.equal(res.header['content-type'], 'text/html; charset=UTF-8'); done(); }); }); it('Should load contact us page', function (done) { chai.request('localhost:' + port) .get('/contactus') .end(function (err, res) { expect(err).to.eql(null); expect(res.status).to.eql(200); assert.equal(res.header['content-type'], 'text/html; charset=UTF-8'); done(); }); }); it('Should load faq page', function (done) { chai.request('localhost:' + port) .get('/faq') .end(function (err, res) { expect(err).to.eql(null); expect(res.status).to.eql(200); assert.equal(res.header['content-type'], 'text/html; charset=UTF-8'); done(); }); }); it('Should load latest news page', function (done) { chai.request('localhost:' + port) .get('/latest-news') .end(function (err, res) { expect(err).to.eql(null); expect(res.status).to.eql(200); assert.equal(res.header['content-type'], 'text/html; charset=UTF-8'); done(); }); }); });
mb4ms/event-site
tests/basic_routes_test.js
JavaScript
mit
2,723
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { PropTypes, Component } from 'react'; import styles from './ShopPage.css'; import withStyles from '../../decorators/withStyles'; import BooksList from '../BooksList'; import http from '../../core/HttpClient'; @withStyles(styles) class ShopPage extends Component { static propTypes = { path: PropTypes.string.isRequired, content: PropTypes.string.isRequired, title: PropTypes.string }; static contextTypes = { onSetTitle: PropTypes.func.isRequired }; state = { books : [] }; loadBooksFromServer(){ http.get('http://henri-potier.xebia.fr/books') .then(data => { this.setState({ books: data }); }) .catch(error => {console.error(error)}); } componentDidMount(){ this.loadBooksFromServer(); } render() { this.context.onSetTitle(this.props.title); return ( <div className="ShopPage"> {this.props.path === '/' ? null : <h1>{this.props.title}</h1>} <BooksList title="Série Hari Potier" books={this.state.books}></BooksList> </div> ); } } export default ShopPage;
charesbast/react
src/components/PageShop/ShopPage.js
JavaScript
mit
1,327
'use strict' function checkStatus(response) { if (response.status >= 200 && response.status < 300) { return response } else { let error = new Error(response.statusText) error.response = response throw error } } module.exports = checkStatus
capejs/capejs
lib/cape/mixins/check_status.js
JavaScript
mit
266
import React from 'react' import LessonNavigator from './LessonNavigator' import PrepositiondPanel from '../dictionary/prepositiond/PrepositiondPanel' function Prepositiond(props) { const style = { border: '1px solid black', margin: '5px' } const q = props.quiz const s:Object = props.strings.get('strings').prepositiond const sm:Object = props.strings.get('strings').misc const quizInsertAdjectivFlag = q.getIn(['prepositiond','insertPrepositiond']) ? <img id='insertPrepositiondCheck' className='checkmark' src='/img/Checked.png' alt='checkmark' width='36' height='36'/> : '' const quizUpdateAdjectivFlag = q.getIn(['prepositiond','updatePrepositiond']) ? <img id='updatePrepositiondCheck' className='checkmark' src='/img/Checked.png' alt='checkmark' width='36' height='36'/> : '' const quizDeleteAdjectivFlag = q.getIn(['prepositiond','deletePrepositiond']) ? <img id='deletePrepositiondCheck' className='checkmark' src='/img/Checked.png' alt='checkmark' width='36' height='36'/> : '' return( <div> <LessonNavigator {...props} /> <div id='help' style={style}> <p>{s.help10}</p> <p>{s.help11}</p> <p>{s.help12}</p> <p>{s.help13}</p> </div> <PrepositiondPanel {...props} /> <div id='quiz' style={style}> <h3>{sm.quiz}</h3> <table> <tbody> <tr> <td><p>{s.quiz1}</p></td> <td>{quizInsertAdjectivFlag}</td> </tr> <tr> <td><p>{s.quiz3}</p></td> <td>{quizUpdateAdjectivFlag}</td> </tr> <tr> <td><p>{s.quiz2}</p></td> <td>{quizDeleteAdjectivFlag}</td> </tr> </tbody> </table> </div> </div> ) } export default Prepositiond
bostontrader/senmaker
src/views/syllabus/Prepositiond.js
JavaScript
mit
2,159
/* ====================================== Custom dashboard telemetry data filter ====================================== */ // This filter is used to change telemetry data // before it is displayed on the dashboard. // For example, you may convert km/h to mph, kilograms to tons, etc. // "data" object is an instance of the Ets2TelemetryData class // defined in dashboard-core.ts (or see JSON response in the server's API). Funbit.Ets.Telemetry.Dashboard.prototype.filter = function (data) { // round truck speed data.truckSpeedRounded = Math.abs(data.truck.speed > 0 ? Math.floor(data.truck.speed) : Math.round(data.truck.speed)); // convert kilometers per hour to miles per hour (just an example) data.truckSpeedMph = data.truck.speed * 0.621371; data.truckSpeedMphRounded = Math.abs(Math.floor(data.truckSpeedMph)); // convert gear to readable format data.gear = data.truck.gear > 0 ? 'D' + data.truck.gear : (data.truck.gear < 0 ? 'R' : 'N'); data.currentFuelPercentage = (data.truck.fuel / data.truck.fuelCapacity) * 100; // scsTruckDamage is the value SCS uses in the route advisor data.scsTruckDamage = getDamagePercentage(data); data.scsTruckDamageRounded = Math.floor(data.scsTruckDamage); data.wearTrailerRounded = Math.floor(data.trailer.wear * 100); data.gameTime12h = getTime(data.game.time, 12, true); data.jobDeadlineTime12h = getTime(data.job.deadlineTime, 12, false); data.trailerMassTons = data.trailer.attached ? ((data.trailer.mass / 1000.0) + ' t') : ''; data.trailerMassKg = data.trailer.attached ? data.trailer.mass + ' kg' : ''; data.jobIncome = getJobIncome(data.job.income); data.game.nextRestStopTimeArray = getHoursMinutesAndSeconds(data.game.nextRestStopTime); data.game.nextRestStopTime = processTimeDifferenceArray(data.game.nextRestStopTimeArray); data.navigation.speedLimitMph = data.navigation.speedLimit * .621371; data.navigation.speedLimitMphRounded = Math.round(data.navigation.speedLimitMph); data.navigation.estimatedDistanceKm = data.navigation.estimatedDistance / 1000; data.navigation.estimatedDistanceMi = data.navigation.estimatedDistanceKm * .621371; data.navigation.estimatedDistanceKmRounded = Math.floor(data.navigation.estimatedDistanceKm); data.navigation.estimatedDistanceMiRounded = Math.floor(data.navigation.estimatedDistanceMi); var originalEstimatedTime = data.navigation.estimatedTime; var timeToDestinationArray = getHoursMinutesAndSeconds(originalEstimatedTime); data.navigation.estimatedTime = addTime(data.game.time, timeToDestinationArray[0], timeToDestinationArray[1], timeToDestinationArray[2]); data.navigation.estimatedTime = getTime(data.navigation.estimatedTime, 24, false); data.navigation.estimatedTime12h = getTime(originalEstimatedTime, 12, false); data.navigation.timeToDestination = processTimeDifferenceArray(timeToDestinationArray); // return changed data to the core for rendering return data; }; Funbit.Ets.Telemetry.Dashboard.prototype.render = function (data) { // // data - same data object as in the filter function // $('#fuelLine').css('width', data.currentFuelPercentage + '%'); $('#damageLine').css('width', data.scsTruckDamage + '%'); $('#truckDamageIcon').css('height', getDamageFillForTruck(data.scsTruckDamage) + '%'); $('#trailerDamageIcon').css('height', getDamageFillForTrailer(data.trailer.wear * 100) + '%'); $('#restLine').css('width', getFatiguePercentage(data.game.nextRestStopTimeArray[0], data.game.nextRestStopTimeArray[1]) + '%'); // Process DOM for connection if (data.game.connected) { $('.has-connection').show(); $('.no-connection').hide(); } else { $('.has-connection').hide(); $('.no-connection').show(); } // Process DOM for job if (data.trailer.attached) { $('.hasJob').show(); $('.noJob').hide(); } else { $('.hasJob').hide(); $('.noJob').show(); } } Funbit.Ets.Telemetry.Dashboard.prototype.initialize = function (skinConfig) { // // skinConfig - a copy of the skin configuration from config.json // // this function is called before everything else, // so you may perform any DOM or resource initializations here // Process Speed Units var distanceUnits = skinConfig.distanceUnits; if (distanceUnits === 'km') { $('.speedUnits').text('km/h'); $('.distanceUnits').text('km'); $('.truckSpeedRoundedKmhMph').addClass('truckSpeedRounded').removeClass('truckSpeedRoundedKmhMph'); $('.speedLimitRoundedKmhMph').addClass('navigation-speedLimit').removeClass('speedLimitRoundedKmhMph'); $('.navigationEstimatedDistanceKmMi').addClass('navigation-estimatedDistanceKmRounded').removeClass('navigationEstimatedDistanceKmMi'); } else if (distanceUnits === 'mi') { $('.speedUnits').text('mph'); $('.distanceUnits').text('mi'); $('.truckSpeedRoundedKmhMph').addClass('truckSpeedMphRounded').removeClass('truckSpeedRoundedKmhMph'); $('.speedLimitRoundedKmhMph').addClass('navigation-speedLimitMphRounded').removeClass('speedLimitRoundedKmhMph'); $('.navigationEstimatedDistanceKmMi').addClass('navigation-estimatedDistanceMiRounded').removeClass('navigationEstimatedDistanceKmMi'); } // Process kg vs tons var weightUnits = skinConfig.weightUnits; if (weightUnits === 'kg') { $('.trailerMassKgOrT').addClass('trailerMassKg').removeClass('trailerMassKgOrT'); } else if (weightUnits === 't') { $('.trailerMassKgOrT').addClass('trailerMassTons').removeClass('trailerMassKgOrT'); } // Process 12 vs 24 hr time var timeFormat = skinConfig.timeFormat; if (timeFormat === '12h') { $('.game-time').addClass('gameTime12h').removeClass('game-time'); $('.job-deadlineTime').addClass('jobDeadlineTime12h').removeClass('job-deadlineTime'); $('.navigation-estimatedTime').addClass('navigation-estimatedTime12h').removeClass('navigation-estimatedTime'); } // Process currency code $('.currencyCode').text(skinConfig.currencyCode); // Process language JSON $.getJSON('skins/mobile-route-advisor/language/'+skinConfig.language, function(json) { $.each(json, function(key, value) { updateLanguage(key, value); }); }); } function getHoursMinutesAndSeconds(time) { var dateTime = new Date(time); var hour = dateTime.getUTCHours(); var minute = dateTime.getUTCMinutes(); var second = dateTime.getUTCSeconds(); return [hour, minute, second]; } function addTime(time, hours, minutes, seconds) { var dateTime = new Date(time); dateTime = dateTime.addHours(hours); dateTime = dateTime.addMinutes(minutes); dateTime = dateTime.addSeconds(seconds); return dateTime; } function getFatiguePercentage(hoursUntilRest, minutesUntilRest) { var FULLY_RESTED_TIME_REMAINING_IN_MILLISECONDS = 11*60*60*1000; // 11 hours * 60 min * 60 sec * 1000 milliseconds if (hoursUntilRest <= 0 && minutesUntilRest <= 0) { return 100; } var hoursInMilliseconds = hoursUntilRest * 60 * 60 * 1000; // # hours * 60 min * 60 sec * 1000 milliseconds var minutesInMilliseconds = minutesUntilRest * 60 * 1000; // # minutes * 60 sec * 1000 milliseconds return 100 - (((hoursInMilliseconds + minutesInMilliseconds) / FULLY_RESTED_TIME_REMAINING_IN_MILLISECONDS) * 100); } function processTimeDifferenceArray(hourMinuteArray) { var hours = hourMinuteArray[0]; var minutes = hourMinuteArray[1]; if (hours <= 0 && minutes <= 0) { minutes = $('.lXMinutes').text().replace('{0}', 0); return minutes; } if (hours == 1) { hours = $('.lXHour').text().replace('{0}', hours); } else if (hours == 0) { hours = ''; } else { hours = $('.lXHours').text().replace('{0}', hours); } if (minutes == 1) { minutes = $('.lXMinute').text().replace('{0}', minutes); } else { minutes = $('.lXMinutes').text().replace('{0}', minutes); } return hours + ' ' + minutes; } function getTime(gameTime, timeUnits, isHeader) { var currentTime = new Date(gameTime); var currentPeriod = timeUnits === 12 ? ' AM' : ''; var currentHours = currentTime.getUTCHours(); var currentMinutes = currentTime.getUTCMinutes(); var formattedMinutes = currentMinutes < 10 ? '0'+currentMinutes : currentMinutes; var currentDay = ''; switch (currentTime.getUTCDay()) { case 0: currentDay = "Sunday"; break; case 1: currentDay = "Monday"; break; case 2: currentDay = "Tuesday"; break; case 3: currentDay = "Wednesday"; break; case 4: currentDay = "Thursday"; break; case 5: currentDay = "Friday"; break; case 6: currentDay = "Saturday"; break; } if (currentHours > 12 && timeUnits === 12) { currentHours -= 12; currentPeriod = ' PM'; } var formattedHours = currentHours < 10 ? '0'+currentHours : currentHours; if (currentDay == 'Wednesday' && isHeader) { $('#headerTime').css('font-size','.9em'); } else { $('#headerTime').css('font-size','1em'); } return currentDay + ' ' + formattedHours + ':' + formattedMinutes + currentPeriod; } function updateLanguage(key, value) { $('.l' + key).text(value); } function getJobIncome(income) { /* Looking at an economy_data.sii file found, the conversion rates are: EUR: 1 CHF: 1.2 CZK: 25 GBP: 0.8 PLN: 4.2 HUF: 293 */ var currencyCode = $('.currencyCode').text(); if (currencyCode == 'EUR') { income = '&euro;&nbsp;' + income; } else if (currencyCode == 'GBP') { income *= 0.8; income = '&pound;&nbsp;' + income; } else if (currencyCode == 'CHF') { income *= 1.2; income += '.&nbsp;-&nbsp;CHF'; } else if (currencyCode == 'CZK') { income *= 25; income += '.&nbsp;-&nbsp;K&#x10D;'; } else if (currencyCode == 'PLN') { income *= 4.2; income += '.&nbsp;-&nbsp;z&#0322;'; } else if (currencyCode == 'HUF') { income *= 293; income += '.&nbsp;-&nbsp;Ft'; } return income; } function getDamagePercentage(data) { // Return the max value of all damage percentages. return Math.max(data.truck.wearEngine, data.truck.wearTransmission, data.truck.wearCabin, data.truck.wearChassis, data.truck.wearWheels) * 100; } function getDamageFillForTruck(damagePercentage) { // damagePercentage: The value returned from getDamagePercentage damagePercentage = Math.floor(damagePercentage); if (damagePercentage < 0.5) { return 80; } if (damagePercentage > 99.4) { return 25; } // This is the closest linear fit found from 3 eyeballed data points. return (475/6) - (.55 * damagePercentage); } function getDamageFillForTrailer(damagePercentage) { // damagePercentage: the same as data.wearTrailer damagePercentage = Math.floor(damagePercentage); if (damagePercentage < .5) { return 65; } if (damagePercentage > 99.4) { return 34; } // This is the closest linear fit found from 3 eyeballed data points. return (389/6) - (0.31 * damagePercentage); } function showTab(tabName) { // Hide all tabs (map, cargo, damage, about) $('#map').hide(); $('#cargo').hide(); $('#damage').hide(); $('#about').hide(); // Remove the "_footerSelected" class from all items. $('#mapFooter').removeClass('_footerSelected'); $('#cargoFooter').removeClass('_footerSelected'); $('#damageFooter').removeClass('_footerSelected'); $('#aboutFooter').removeClass('_footerSelected'); // Show the ID requested $('#' + tabName).show(); $('#' + tabName + 'Footer').addClass('_footerSelected'); } /** Returns the difference between two dates in ISO 8601 format in an [hour, minutes] array */ function getTimeDifference(begin, end) { var beginDate = new Date(begin); var endDate = new Date(end); var MILLISECONDS_IN_MINUTE = 60*1000; var MILLISECONDS_IN_HOUR = MILLISECONDS_IN_MINUTE*60; var MILLISECONDS_IN_DAY = MILLISECONDS_IN_HOUR*24; var hours = Math.floor((endDate - beginDate) % MILLISECONDS_IN_DAY / MILLISECONDS_IN_HOUR) // number of hours var minutes = Math.floor((endDate - beginDate) % MILLISECONDS_IN_DAY % MILLISECONDS_IN_HOUR / MILLISECONDS_IN_MINUTE) // number of minutes return [hours, minutes]; } Date.prototype.addHours = function(h) { this.setTime(this.getTime() + (h*60*60*1000)); return this; } Date.prototype.addMinutes = function(m) { this.setTime(this.getTime() + (m*60*1000)); return this; } Date.prototype.addSeconds = function(s) { this.setTime(this.getTime() + (s*1000)); return this; }
Phil0499/ets2-mobile-route-advisor
dashboard.js
JavaScript
mit
13,360
var util = require("util"); var choreography = require("temboo/core/choreography"); /* DeleteRegionOperation Deletes the specified operation within a region. */ var DeleteRegionOperation = function(session) { /* Create a new instance of the DeleteRegionOperation Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/Google/ComputeEngine/RegionOperations/DeleteRegionOperation" DeleteRegionOperation.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new DeleteRegionOperationResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new DeleteRegionOperationInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the DeleteRegionOperation Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var DeleteRegionOperationInputSet = function() { DeleteRegionOperationInputSet.super_.call(this); /* Set the value of the AccessToken input for this Choreo. ((optional, string) A valid access token retrieved during the OAuth process. This is required unless you provide the ClientID, ClientSecret, and RefreshToken to generate a new access token.) */ this.set_AccessToken = function(value) { this.setInput("AccessToken", value); } /* Set the value of the ClientID input for this Choreo. ((conditional, string) The Client ID provided by Google. Required unless providing a valid AccessToken.) */ this.set_ClientID = function(value) { this.setInput("ClientID", value); } /* Set the value of the ClientSecret input for this Choreo. ((conditional, string) The Client Secret provided by Google. Required unless providing a valid AccessToken.) */ this.set_ClientSecret = function(value) { this.setInput("ClientSecret", value); } /* Set the value of the Fields input for this Choreo. ((optional, string) Comma-seperated list of fields you want to include in the response.) */ this.set_Fields = function(value) { this.setInput("Fields", value); } /* Set the value of the Operation input for this Choreo. ((required, string) The name of the operation to delete.) */ this.set_Operation = function(value) { this.setInput("Operation", value); } /* Set the value of the Project input for this Choreo. ((required, string) The ID of a Google Compute project.) */ this.set_Project = function(value) { this.setInput("Project", value); } /* Set the value of the RefreshToken input for this Choreo. ((conditional, string) An OAuth refresh token used to generate a new access token when the original token is expired. Required unless providing a valid AccessToken.) */ this.set_RefreshToken = function(value) { this.setInput("RefreshToken", value); } /* Set the value of the Region input for this Choreo. ((required, string) The name of the region associated with the request. (e.g. europe-west1)) */ this.set_Region = function(value) { this.setInput("Region", value); } } /* A ResultSet with methods tailored to the values returned by the DeleteRegionOperation Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var DeleteRegionOperationResultSet = function(resultStream) { DeleteRegionOperationResultSet.super_.call(this, resultStream); /* Retrieve the value for the "NewAccessToken" output from this Choreo execution. ((string) Contains a new AccessToken when the RefreshToken is provided.) */ this.get_NewAccessToken = function() { return this.getResult("NewAccessToken"); } /* Retrieve the value for the "ResponseStatusCode" output from this Choreo execution. ((integer) The response status code returned from Google. A 204 is expected for a successful delete operation.) */ this.get_ResponseStatusCode = function() { return this.getResult("ResponseStatusCode"); } /* Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Google.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(DeleteRegionOperation, choreography.Choreography); util.inherits(DeleteRegionOperationInputSet, choreography.InputSet); util.inherits(DeleteRegionOperationResultSet, choreography.ResultSet); exports.DeleteRegionOperation = DeleteRegionOperation; /* GetRegionOperation Retrieves information about the specified operation within a region. */ var GetRegionOperation = function(session) { /* Create a new instance of the GetRegionOperation Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/Google/ComputeEngine/RegionOperations/GetRegionOperation" GetRegionOperation.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new GetRegionOperationResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new GetRegionOperationInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the GetRegionOperation Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var GetRegionOperationInputSet = function() { GetRegionOperationInputSet.super_.call(this); /* Set the value of the AccessToken input for this Choreo. ((optional, string) A valid access token retrieved during the OAuth process. This is required unless you provide the ClientID, ClientSecret, and RefreshToken to generate a new access token.) */ this.set_AccessToken = function(value) { this.setInput("AccessToken", value); } /* Set the value of the ClientID input for this Choreo. ((conditional, string) The Client ID provided by Google. Required unless providing a valid AccessToken.) */ this.set_ClientID = function(value) { this.setInput("ClientID", value); } /* Set the value of the ClientSecret input for this Choreo. ((conditional, string) The Client Secret provided by Google. Required unless providing a valid AccessToken.) */ this.set_ClientSecret = function(value) { this.setInput("ClientSecret", value); } /* Set the value of the Fields input for this Choreo. ((optional, string) Comma-seperated list of fields you want to include in the response.) */ this.set_Fields = function(value) { this.setInput("Fields", value); } /* Set the value of the Operation input for this Choreo. ((required, string) The name of the operation to retrieve.) */ this.set_Operation = function(value) { this.setInput("Operation", value); } /* Set the value of the Project input for this Choreo. ((required, string) The ID of a Google Compute project.) */ this.set_Project = function(value) { this.setInput("Project", value); } /* Set the value of the RefreshToken input for this Choreo. ((conditional, string) An OAuth refresh token used to generate a new access token when the original token is expired. Required unless providing a valid AccessToken.) */ this.set_RefreshToken = function(value) { this.setInput("RefreshToken", value); } /* Set the value of the Region input for this Choreo. ((required, string) The name of the region associated with the request. (e.g. europe-west1)) */ this.set_Region = function(value) { this.setInput("Region", value); } } /* A ResultSet with methods tailored to the values returned by the GetRegionOperation Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var GetRegionOperationResultSet = function(resultStream) { GetRegionOperationResultSet.super_.call(this, resultStream); /* Retrieve the value for the "NewAccessToken" output from this Choreo execution. ((string) Contains a new AccessToken when the RefreshToken is provided.) */ this.get_NewAccessToken = function() { return this.getResult("NewAccessToken"); } /* Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Google.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(GetRegionOperation, choreography.Choreography); util.inherits(GetRegionOperationInputSet, choreography.InputSet); util.inherits(GetRegionOperationResultSet, choreography.ResultSet); exports.GetRegionOperation = GetRegionOperation; /* ListRegionOperations Retrieves a list of operation resources contained within the specified region. */ var ListRegionOperations = function(session) { /* Create a new instance of the ListRegionOperations Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/Google/ComputeEngine/RegionOperations/ListRegionOperations" ListRegionOperations.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new ListRegionOperationsResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new ListRegionOperationsInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the ListRegionOperations Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var ListRegionOperationsInputSet = function() { ListRegionOperationsInputSet.super_.call(this); /* Set the value of the AccessToken input for this Choreo. ((optional, string) A valid access token retrieved during the OAuth process. This is required unless you provide the ClientID, ClientSecret, and RefreshToken to generate a new access token.) */ this.set_AccessToken = function(value) { this.setInput("AccessToken", value); } /* Set the value of the ClientID input for this Choreo. ((conditional, string) The Client ID provided by Google. Required unless providing a valid AccessToken.) */ this.set_ClientID = function(value) { this.setInput("ClientID", value); } /* Set the value of the ClientSecret input for this Choreo. ((conditional, string) The Client Secret provided by Google. Required unless providing a valid AccessToken.) */ this.set_ClientSecret = function(value) { this.setInput("ClientSecret", value); } /* Set the value of the Fields input for this Choreo. ((optional, string) Comma-seperated list of fields you want to include in the response.) */ this.set_Fields = function(value) { this.setInput("Fields", value); } /* Set the value of the Filter input for this Choreo. ((optional, string) A filter expression for narrowing results in the form: {field_name} {comparison_string} {literal_string} (e.g. name eq operation-1234). Comparison strings can be eq (equals) or ne (not equals).) */ this.set_Filter = function(value) { this.setInput("Filter", value); } /* Set the value of the MaxResults input for this Choreo. ((optional, integer) The maximum number of results to return.) */ this.set_MaxResults = function(value) { this.setInput("MaxResults", value); } /* Set the value of the PageToken input for this Choreo. ((optional, string) The "nextPageToken" found in the response which is used to page through results.) */ this.set_PageToken = function(value) { this.setInput("PageToken", value); } /* Set the value of the Project input for this Choreo. ((required, string) The ID of a Google Compute project.) */ this.set_Project = function(value) { this.setInput("Project", value); } /* Set the value of the RefreshToken input for this Choreo. ((conditional, string) An OAuth refresh token used to generate a new access token when the original token is expired. Required unless providing a valid AccessToken.) */ this.set_RefreshToken = function(value) { this.setInput("RefreshToken", value); } /* Set the value of the Region input for this Choreo. ((required, string) The name of the region associated with this request. (e.g. europe-west1)) */ this.set_Region = function(value) { this.setInput("Region", value); } } /* A ResultSet with methods tailored to the values returned by the ListRegionOperations Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var ListRegionOperationsResultSet = function(resultStream) { ListRegionOperationsResultSet.super_.call(this, resultStream); /* Retrieve the value for the "NewAccessToken" output from this Choreo execution. ((string) Contains a new AccessToken when the RefreshToken is provided.) */ this.get_NewAccessToken = function() { return this.getResult("NewAccessToken"); } /* Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Google.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(ListRegionOperations, choreography.Choreography); util.inherits(ListRegionOperationsInputSet, choreography.InputSet); util.inherits(ListRegionOperationsResultSet, choreography.ResultSet); exports.ListRegionOperations = ListRegionOperations; /****************************************************************************** Begin output wrapper classes ******************************************************************************/ /** * Utility function, to retrieve the array-type sub-item specified by the key from the parent (array) specified by the item. * Returns an empty array if key is not present. */ function getSubArrayByKey(item, key) { var val = item[key]; if(val == null) { val = new Array(); } return val; }
nikmeiser/omphaloskepsis
node_modules/temboo/Library/Google/ComputeEngine/RegionOperations.js
JavaScript
mit
16,483