UNPKG

cache-storage

Version:

[ABANDONED] Advanced cache storage for node js

1,522 lines (1,340 loc) 414 kB
/** Generated by SimQ **/ /** modules **/ // Generated by CoffeeScript 1.6.3 (function() { var SUPPORTED, arrayIndexOf, cache, creating, modules, require, resolve, stats; if (!this.require) { SUPPORTED = ['js', 'json', 'ts', 'coffee', 'eco']; modules = {}; stats = {}; cache = {}; creating = []; require = function(name, parent) { var fullName, m; if (parent == null) { parent = null; } fullName = resolve(name, parent); if (fullName === null) { throw new Error('Module ' + name + ' was not found.'); } if (typeof cache[fullName] === 'undefined') { m = { exports: {}, id: fullName, filename: fullName, loaded: false, parent: null, children: null }; if (arrayIndexOf(creating, fullName) === -1) { creating.push(fullName); modules[fullName].apply(window, [m.exports, m]); creating.splice(arrayIndexOf(creating, fullName)); cache[fullName] = m; } m.loaded = true; } else { m = cache[fullName]; } if (typeof stats[fullName] === 'undefined') { stats[fullName] = { atime: null, mtime: null, ctime: null }; } stats[fullName].atime = new Date; return m.exports; }; resolve = function(name, parent) { var ext, num, part, parts, prev, result, _i, _j, _k, _len, _len1, _len2; if (parent == null) { parent = null; } if (parent !== null && name[0] === '.') { num = parent.lastIndexOf('/'); if (num !== -1) { parent = parent.substr(0, num); } name = parent + '/' + name; parts = name.split('/'); result = []; prev = null; for (_i = 0, _len = parts.length; _i < _len; _i++) { part = parts[_i]; if (part === '.' || part === '') { continue; } else if (part === '..' && prev) { result.pop(); } else { result.push(part); } prev = part; } name = result.join('/'); if (parent[0] === '/') { name = '/' + name; } } if (typeof modules[name] !== 'undefined') { return name; } for (_j = 0, _len1 = SUPPORTED.length; _j < _len1; _j++) { ext = SUPPORTED[_j]; if (typeof modules[name + '.' + ext] !== 'undefined') { return name + '.' + ext; } } for (_k = 0, _len2 = SUPPORTED.length; _k < _len2; _k++) { ext = SUPPORTED[_k]; if (typeof modules[name + '/index.' + ext] !== 'undefined') { return name + '/index.' + ext; } } return null; }; arrayIndexOf = function(array, search) { var element, i, _i, _len; if (typeof Array.prototype.indexOf !== 'undefined') { return array.indexOf(search); } if (array.length === 0) { return -1; } for (i = _i = 0, _len = array.length; _i < _len; i = ++_i) { element = array[i]; if (element === search) { return i; } } return -1; }; this.require = function(name, parent) { if (parent == null) { parent = null; } return require(name, parent); }; this.require.simq = true; this.require.version = 1; this.require.resolve = function(name, parent) { if (parent == null) { parent = null; } return resolve(name, parent); }; this.require.define = function(bundleOrName, obj) { var m, name, _results; if (obj == null) { obj = null; } if (typeof bundleOrName === 'string') { return modules[bundleOrName] = obj; } else { _results = []; for (name in bundleOrName) { m = bundleOrName[name]; _results.push(modules[name] = m); } return _results; } }; this.require.release = function() { var name, _results; _results = []; for (name in cache) { _results.push(delete cache[name]); } return _results; }; this.require.getStats = function(name, parent) { var fullName; if (parent == null) { parent = null; } fullName = resolve(name, parent); if (fullName === null) { throw new Error('Module ' + name + ' was not found.'); } if (typeof stats[fullName] === 'undefined') { stats[fullName] = { atime: null, mtime: null, ctime: null }; } return stats[fullName]; }; this.require.__setStats = function(bundle) { var data, name, _results; _results = []; for (name in bundle) { data = bundle[name]; _results.push(stats[name] = { atime: new Date(data.atime), mtime: new Date(data.mtime), ctime: new Date(data.ctime) }); } return _results; }; this.require.cache = cache; } return this.require.define; }).call(this)({ '/lib/Storage/Sync/BrowserLocalStorage.js': function(exports, module) { /** node globals **/ var require = function(name) {return window.require(name, '/lib/Storage/Sync/BrowserLocalStorage.js');}; require.resolve = function(name, parent) {if (parent === null) {parent = '/lib/Storage/Sync/BrowserLocalStorage.js';} return window.require.resolve(name, parent);}; require.define = function(bundle) {window.require.define(bundle);}; require.cache = window.require.cache; var __filename = '/lib/Storage/Sync/BrowserLocalStorage.js'; var __dirname = '/lib/Storage/Sync'; var process = {cwd: function() {return '/';}, argv: ['node', '/lib/Storage/Sync/BrowserLocalStorage.js'], env: {}}; /** code **/ // Generated by CoffeeScript 1.6.3 (function() { var BrowserLocalStorage, Cache, Storage, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; Storage = require('./Storage'); Cache = require('../../Cache'); BrowserLocalStorage = (function(_super) { __extends(BrowserLocalStorage, _super); BrowserLocalStorage.TEST_VALUE = '__--cache-storage--__'; BrowserLocalStorage.prototype.allData = null; BrowserLocalStorage.prototype.data = null; BrowserLocalStorage.prototype.meta = null; function BrowserLocalStorage() { if (!BrowserLocalStorage.isSupported()) { throw new Error('Cache storage: Local storage is not supported'); } } BrowserLocalStorage.isSupported = function() { var e; try { localStorage.setItem(BrowserLocalStorage.TEST_VALUE, BrowserLocalStorage.TEST_VALUE); localStorage.getItem(BrowserLocalStorage.TEST_VALUE); return true; } catch (_error) { e = _error; return false; } }; BrowserLocalStorage.prototype.getName = function() { return '__' + this.cache.namespace; }; BrowserLocalStorage.prototype.loadData = function() { var data; if (this.allData === null) { data = localStorage.getItem(this.getName()); if (data === null) { this.allData = { data: {}, meta: {} }; } else { this.allData = JSON.parse(data); } } return this.allData; }; BrowserLocalStorage.prototype.getData = function() { if (this.data === null) { this.data = this.loadData().data; } return this.data; }; BrowserLocalStorage.prototype.getMeta = function() { if (this.meta === null) { this.meta = this.loadData().meta; } return this.meta; }; BrowserLocalStorage.prototype.writeData = function(data, meta) { this.data = data; this.meta = meta; return localStorage.setItem(this.getName(), JSON.stringify({ data: this.data, meta: this.meta })); }; return BrowserLocalStorage; })(Storage); module.exports = BrowserLocalStorage; }).call(this); }, '/lib/Storage/Sync/Storage.js': function(exports, module) { /** node globals **/ var require = function(name) {return window.require(name, '/lib/Storage/Sync/Storage.js');}; require.resolve = function(name, parent) {if (parent === null) {parent = '/lib/Storage/Sync/Storage.js';} return window.require.resolve(name, parent);}; require.define = function(bundle) {window.require.define(bundle);}; require.cache = window.require.cache; var __filename = '/lib/Storage/Sync/Storage.js'; var __dirname = '/lib/Storage/Sync'; var process = {cwd: function() {return '/';}, argv: ['node', '/lib/Storage/Sync/Storage.js'], env: {}}; /** code **/ // Generated by CoffeeScript 1.6.3 (function() { var BaseStorage, Cache, Storage, isWindow, moment, path, _ref, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; isWindow = typeof window === 'undefined' ? false : true; if (!isWindow) { path = require('path'); } BaseStorage = require('../Storage'); moment = require('moment'); Cache = require('../../Cache'); Storage = (function(_super) { __extends(Storage, _super); function Storage() { _ref = Storage.__super__.constructor.apply(this, arguments); return _ref; } Storage.prototype.async = false; Storage.prototype.read = function(key) { var data; data = this.getData(); if (typeof data[key] === 'undefined') { return null; } else { if (this.verify(this.findMeta(key))) { return data[key]; } else { this.remove(key); return null; } } }; Storage.prototype.write = function(key, data, dependencies) { var all, meta; if (dependencies == null) { dependencies = {}; } all = this.getData(); all[key] = data; meta = this.getMeta(); meta[key] = dependencies; return this.writeData(all, meta); }; Storage.prototype.remove = function(key) { var data, meta; data = this.getData(); meta = this.getMeta(); if (typeof data[key] !== 'undefined') { delete data[key]; delete meta[key]; } return this.writeData(data, meta); }; Storage.prototype.removeAll = function() { return this.writeData({}, {}); }; Storage.prototype.clean = function(conditions) { var key, tag, type, typeFn, _i, _j, _k, _len, _len1, _len2, _ref1, _ref2, _ref3, _results; typeFn = Object.prototype.toString; type = typeFn.call(conditions); if (conditions === Cache.ALL) { return this.removeAll(); } else if (type === '[object Object]') { if (typeof conditions[Cache.TAGS] !== 'undefined') { if (typeFn(conditions[Cache.TAGS]) === '[object String]') { conditions[Cache.TAGS] = [conditions[Cache.TAGS]]; } _ref1 = conditions[Cache.TAGS]; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { tag = _ref1[_i]; _ref2 = this.findKeysByTag(tag); for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { key = _ref2[_j]; this.remove(key); } } } if (typeof conditions[Cache.PRIORITY] !== 'undefined') { _ref3 = this.findKeysByPriority(conditions[Cache.PRIORITY]); _results = []; for (_k = 0, _len2 = _ref3.length; _k < _len2; _k++) { key = _ref3[_k]; _results.push(this.remove(key)); } return _results; } } }; Storage.prototype.findMeta = function(key) { var meta; meta = this.getMeta(); if (typeof meta[key] !== 'undefined') { return meta[key]; } else { return null; } }; Storage.prototype.findKeysByTag = function(tag) { var key, meta, metas, result; metas = this.getMeta(); result = []; for (key in metas) { meta = metas[key]; if (typeof meta[Cache.TAGS] !== 'undefined' && meta[Cache.TAGS].indexOf(tag) !== -1) { result.push(key); } } return result; }; Storage.prototype.findKeysByPriority = function(priority) { var key, meta, metas, result; metas = this.getMeta(); result = []; for (key in metas) { meta = metas[key]; if (typeof meta[Cache.PRIORITY] !== 'undefined' && meta[Cache.PRIORITY] <= priority) { result.push(key); } } return result; }; Storage.prototype.verify = function(meta) { var file, item, mtime, time, typefn, _i, _len, _ref1, _ref2, _ref3; typefn = Object.prototype.toString; if (typefn.call(meta) === '[object Object]') { if (typeof meta[Cache.EXPIRE] !== 'undefined') { if (moment().valueOf() >= meta[Cache.EXPIRE]) { return false; } } if (typeof meta[Cache.ITEMS] !== 'undefined') { _ref1 = meta[Cache.ITEMS]; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { item = _ref1[_i]; item = this.findMeta(item); if ((item === null) || (item !== null && this.verify(item) === false)) { return false; } } } if (typeof meta[Cache.FILES] !== 'undefined') { this.checkFilesSupport(); if (isWindow) { _ref2 = meta[Cache.FILES]; for (file in _ref2) { time = _ref2[file]; mtime = window.require.getStats(file).mtime; if (mtime === null) { throw new Error('File stats are disabled in your simq configuration. Can not get stats for ' + file + '.'); } if (window.require.getStats(file).mtime.getTime() !== time) { return false; } } } else { _ref3 = meta[Cache.FILES]; for (file in _ref3) { time = _ref3[file]; if ((new Date(Cache.getFs().statSync(file).mtime)).getTime() !== time) { return false; } } } } } return true; }; Storage.prototype.parseDependencies = function(dependencies) { var file, files, item, mtime, result, time, typefn, _i, _j, _k, _len, _len1, _len2, _ref1, _ref2, _ref3; typefn = Object.prototype.toString; result = {}; if (typefn.call(dependencies) === '[object Object]') { if (typeof dependencies[Cache.PRIORITY] !== 'undefined') { result[Cache.PRIORITY] = dependencies[Cache.PRIORITY]; } if (typeof dependencies[Cache.TAGS] !== 'undefined') { result[Cache.TAGS] = dependencies[Cache.TAGS]; } if (typeof dependencies[Cache.ITEMS] !== 'undefined') { result[Cache.ITEMS] = []; _ref1 = dependencies[Cache.ITEMS]; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { item = _ref1[_i]; result[Cache.ITEMS].push(this.cache.generateKey(item)); } } if (typeof dependencies[Cache.EXPIRE] !== 'undefined') { switch (typefn.call(dependencies[Cache.EXPIRE])) { case '[object String]': time = moment(dependencies[Cache.EXPIRE], Cache.TIME_FORMAT); break; case '[object Object]': time = moment().add(dependencies[Cache.EXPIRE]); break; default: throw new Error('Expire format is not valid'); } result[Cache.EXPIRE] = time.valueOf(); } if (typeof dependencies[Cache.FILES] !== 'undefined') { this.checkFilesSupport(); files = {}; if (isWindow) { _ref2 = dependencies[Cache.FILES]; for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { file = _ref2[_j]; mtime = window.require.getStats(file).mtime; if (mtime === null) { throw new Error('File stats are disabled in your simq configuration. Can not get stats for ' + file + '.'); } file = window.require.resolve(file); files[file] = mtime.getTime(); } } else { _ref3 = dependencies[Cache.FILES]; for (_k = 0, _len2 = _ref3.length; _k < _len2; _k++) { file = _ref3[_k]; file = path.resolve(file); files[file] = (new Date(Cache.getFs().statSync(file).mtime)).getTime(); } } result[Cache.FILES] = files; } } return result; }; return Storage; })(BaseStorage); module.exports = Storage; }).call(this); }, '/lib/Storage/Storage.js': function(exports, module) { /** node globals **/ var require = function(name) {return window.require(name, '/lib/Storage/Storage.js');}; require.resolve = function(name, parent) {if (parent === null) {parent = '/lib/Storage/Storage.js';} return window.require.resolve(name, parent);}; require.define = function(bundle) {window.require.define(bundle);}; require.cache = window.require.cache; var __filename = '/lib/Storage/Storage.js'; var __dirname = '/lib/Storage'; var process = {cwd: function() {return '/';}, argv: ['node', '/lib/Storage/Storage.js'], env: {}}; /** code **/ // Generated by CoffeeScript 1.6.3 (function() { var Storage; Storage = (function() { Storage.prototype.async = false; Storage.prototype.cache = null; function Storage() { if (!(this instanceof Storage)) { if (typeof this.read === 'undefined' || typeof this.write === 'undefined' || typeof this.remove === 'undefined' || typeof this.removeAll === 'undefined' || typeof this.getMeta === 'undefined') { throw new Error('Cache storage: you have to implement methods read, write, remove, removeAll and getMeta.'); } } } Storage.prototype.checkFilesSupport = function() { var isWindow, version; isWindow = typeof window === 'undefined' ? false : true; if (isWindow && window.require.simq !== true) { throw new Error('Files meta information can be used in browser only with simq.'); } if (isWindow) { version = window.require.version; if (typeof version === 'undefined' || parseInt(version.replace(/\./g, '')) < 510) { throw new Error('File method information is supported only with simq@5.1.0 and later.'); } } }; return Storage; })(); module.exports = Storage; }).call(this); }, 'moment/moment.js': function(exports, module) { /** node globals **/ var require = function(name) {return window.require(name, 'moment/moment.js');}; require.resolve = function(name, parent) {if (parent === null) {parent = 'moment/moment.js';} return window.require.resolve(name, parent);}; require.define = function(bundle) {window.require.define(bundle);}; require.cache = window.require.cache; var __filename = 'moment/moment.js'; var __dirname = 'moment'; var process = {cwd: function() {return '/';}, argv: ['node', 'moment/moment.js'], env: {}}; /** code **/ //! moment.js //! version : 2.5.0 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com (function (undefined) { /************************************ Constants ************************************/ var moment, VERSION = "2.5.0", global = this, round = Math.round, i, YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, // internal storage for language config files languages = {}, // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'), // ASP.NET json date format regex aspNetJsonRegex = /^\/?Date\((\-?\d+)/i, aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/, // format tokens formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g, // parsing token regexes parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99 parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999 parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999 parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999 parseTokenDigits = /\d+/, // nonzero number of digits parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z parseTokenT = /T/i, // T (ISO separator) parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 //strict parsing regexes parseTokenOneDigit = /\d/, // 0 - 9 parseTokenTwoDigits = /\d\d/, // 00 - 99 parseTokenThreeDigits = /\d{3}/, // 000 - 999 parseTokenFourDigits = /\d{4}/, // 0000 - 9999 parseTokenSixDigits = /[+\-]?\d{6}/, // -999,999 - 999,999 // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) isoRegex = /^\s*\d{4}-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/, isoFormat = 'YYYY-MM-DDTHH:mm:ssZ', isoDates = [ 'YYYY-MM-DD', 'GGGG-[W]WW', 'GGGG-[W]WW-E', 'YYYY-DDD' ], // iso time formats and regexes isoTimes = [ ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/], ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], ['HH:mm', /(T| )\d\d:\d\d/], ['HH', /(T| )\d\d/] ], // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"] parseTimezoneChunker = /([\+\-]|\d\d)/gi, // getter and setter names proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'), unitMillisecondFactors = { 'Milliseconds' : 1, 'Seconds' : 1e3, 'Minutes' : 6e4, 'Hours' : 36e5, 'Days' : 864e5, 'Months' : 2592e6, 'Years' : 31536e6 }, unitAliases = { ms : 'millisecond', s : 'second', m : 'minute', h : 'hour', d : 'day', D : 'date', w : 'week', W : 'isoWeek', M : 'month', y : 'year', DDD : 'dayOfYear', e : 'weekday', E : 'isoWeekday', gg: 'weekYear', GG: 'isoWeekYear' }, camelFunctions = { dayofyear : 'dayOfYear', isoweekday : 'isoWeekday', isoweek : 'isoWeek', weekyear : 'weekYear', isoweekyear : 'isoWeekYear' }, // format function strings formatFunctions = {}, // tokens to ordinalize and pad ordinalizeTokens = 'DDD w W M D d'.split(' '), paddedTokens = 'M D H h m s w W'.split(' '), formatTokenFunctions = { M : function () { return this.month() + 1; }, MMM : function (format) { return this.lang().monthsShort(this, format); }, MMMM : function (format) { return this.lang().months(this, format); }, D : function () { return this.date(); }, DDD : function () { return this.dayOfYear(); }, d : function () { return this.day(); }, dd : function (format) { return this.lang().weekdaysMin(this, format); }, ddd : function (format) { return this.lang().weekdaysShort(this, format); }, dddd : function (format) { return this.lang().weekdays(this, format); }, w : function () { return this.week(); }, W : function () { return this.isoWeek(); }, YY : function () { return leftZeroFill(this.year() % 100, 2); }, YYYY : function () { return leftZeroFill(this.year(), 4); }, YYYYY : function () { return leftZeroFill(this.year(), 5); }, YYYYYY : function () { var y = this.year(), sign = y >= 0 ? '+' : '-'; return sign + leftZeroFill(Math.abs(y), 6); }, gg : function () { return leftZeroFill(this.weekYear() % 100, 2); }, gggg : function () { return this.weekYear(); }, ggggg : function () { return leftZeroFill(this.weekYear(), 5); }, GG : function () { return leftZeroFill(this.isoWeekYear() % 100, 2); }, GGGG : function () { return this.isoWeekYear(); }, GGGGG : function () { return leftZeroFill(this.isoWeekYear(), 5); }, e : function () { return this.weekday(); }, E : function () { return this.isoWeekday(); }, a : function () { return this.lang().meridiem(this.hours(), this.minutes(), true); }, A : function () { return this.lang().meridiem(this.hours(), this.minutes(), false); }, H : function () { return this.hours(); }, h : function () { return this.hours() % 12 || 12; }, m : function () { return this.minutes(); }, s : function () { return this.seconds(); }, S : function () { return toInt(this.milliseconds() / 100); }, SS : function () { return leftZeroFill(toInt(this.milliseconds() / 10), 2); }, SSS : function () { return leftZeroFill(this.milliseconds(), 3); }, SSSS : function () { return leftZeroFill(this.milliseconds(), 3); }, Z : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2); }, ZZ : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2); }, z : function () { return this.zoneAbbr(); }, zz : function () { return this.zoneName(); }, X : function () { return this.unix(); }, Q : function () { return this.quarter(); } }, lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin']; function padToken(func, count) { return function (a) { return leftZeroFill(func.call(this, a), count); }; } function ordinalizeToken(func, period) { return function (a) { return this.lang().ordinal(func.call(this, a), period); }; } while (ordinalizeTokens.length) { i = ordinalizeTokens.pop(); formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i); } while (paddedTokens.length) { i = paddedTokens.pop(); formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2); } formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3); /************************************ Constructors ************************************/ function Language() { } // Moment prototype object function Moment(config) { checkOverflow(config); extend(this, config); } // Duration Constructor function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 36e5; // 1000 * 60 * 60 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + years * 12; this._data = {}; this._bubble(); } /************************************ Helpers ************************************/ function extend(a, b) { for (var i in b) { if (b.hasOwnProperty(i)) { a[i] = b[i]; } } if (b.hasOwnProperty("toString")) { a.toString = b.toString; } if (b.hasOwnProperty("valueOf")) { a.valueOf = b.valueOf; } return a; } function absRound(number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } // left zero fill a number // see http://jsperf.com/left-zero-filling for performance comparison function leftZeroFill(number, targetLength, forceSign) { var output = Math.abs(number) + '', sign = number >= 0; while (output.length < targetLength) { output = '0' + output; } return (sign ? (forceSign ? '+' : '') : '-') + output; } // helper function for _.addTime and _.subtractTime function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) { var milliseconds = duration._milliseconds, days = duration._days, months = duration._months, minutes, hours; if (milliseconds) { mom._d.setTime(+mom._d + milliseconds * isAdding); } // store the minutes and hours so we can restore them if (days || months) { minutes = mom.minute(); hours = mom.hour(); } if (days) { mom.date(mom.date() + days * isAdding); } if (months) { mom.month(mom.month() + months * isAdding); } if (milliseconds && !ignoreUpdateOffset) { moment.updateOffset(mom); } // restore the minutes and hours after possibly changing dst if (days || months) { mom.minute(minutes); mom.hour(hours); } } // check if is an array function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]'; } function isDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function normalizeUnits(units) { if (units) { var lowered = units.toLowerCase().replace(/(.)s$/, '$1'); units = unitAliases[units] || camelFunctions[lowered] || lowered; } return units; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (inputObject.hasOwnProperty(prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } function makeList(field) { var count, setter; if (field.indexOf('week') === 0) { count = 7; setter = 'day'; } else if (field.indexOf('month') === 0) { count = 12; setter = 'month'; } else { return; } moment[field] = function (format, index) { var i, getter, method = moment.fn._lang[field], results = []; if (typeof format === 'number') { index = format; format = undefined; } getter = function (i) { var m = moment().utc().set(setter, i); return method.call(moment.fn._lang, m, format || ''); }; if (index != null) { return getter(index); } else { for (i = 0; i < count; i++) { results.push(getter(i)); } return results; } }; } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { if (coercedNumber >= 0) { value = Math.floor(coercedNumber); } else { value = Math.ceil(coercedNumber); } } return value; } function daysInMonth(year, month) { return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function checkOverflow(m) { var overflow; if (m._a && m._pf.overflow === -2) { overflow = m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH : m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE : m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR : m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE : m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND : m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND : -1; if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } m._pf.overflow = overflow; } } function initializeParsingFlags(config) { config._pf = { empty : false, unusedTokens : [], unusedInput : [], overflow : -2, charsLeftOver : 0, nullInput : false, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso: false }; } function isValid(m) { if (m._isValid == null) { m._isValid = !isNaN(m._d.getTime()) && m._pf.overflow < 0 && !m._pf.empty && !m._pf.invalidMonth && !m._pf.nullInput && !m._pf.invalidFormat && !m._pf.userInvalidated; if (m._strict) { m._isValid = m._isValid && m._pf.charsLeftOver === 0 && m._pf.unusedTokens.length === 0; } } return m._isValid; } function normalizeLanguage(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // Return a moment from input, that is local/utc/zone equivalent to model. function makeAs(input, model) { return model._isUTC ? moment(input).zone(model._offset || 0) : moment(input).local(); } /************************************ Languages ************************************/ extend(Language.prototype, { set : function (config) { var prop, i; for (i in config) { prop = config[i]; if (typeof prop === 'function') { this[i] = prop; } else { this['_' + i] = prop; } } }, _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), months : function (m) { return this._months[m.month()]; }, _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), monthsShort : function (m) { return this._monthsShort[m.month()]; }, monthsParse : function (monthName) { var i, mom, regex; if (!this._monthsParse) { this._monthsParse = []; } for (i = 0; i < 12; i++) { // make the regex if we don't have it already if (!this._monthsParse[i]) { mom = moment.utc([2000, i]); regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._monthsParse[i].test(monthName)) { return i; } } }, _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdays : function (m) { return this._weekdays[m.day()]; }, _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysShort : function (m) { return this._weekdaysShort[m.day()]; }, _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), weekdaysMin : function (m) { return this._weekdaysMin[m.day()]; }, weekdaysParse : function (weekdayName) { var i, mom, regex; if (!this._weekdaysParse) { this._weekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already if (!this._weekdaysParse[i]) { mom = moment([2000, 1]).day(i); regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._weekdaysParse[i].test(weekdayName)) { return i; } } }, _longDateFormat : { LT : "h:mm A", L : "MM/DD/YYYY", LL : "MMMM D YYYY", LLL : "MMMM D YYYY LT", LLLL : "dddd, MMMM D YYYY LT" }, longDateFormat : function (key) { var output = this._longDateFormat[key]; if (!output && this._longDateFormat[key.toUpperCase()]) { output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); this._longDateFormat[key] = output; } return output; }, isPM : function (input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); }, _meridiemParse : /[ap]\.?m?\.?/i, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } }, _calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendar[key]; return typeof output === 'function' ? output.apply(mom) : output; }, _relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, relativeTime : function (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (typeof output === 'function') ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); }, pastFuture : function (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); }, ordinal : function (number) { return this._ordinal.replace("%d", number); }, _ordinal : "%d", preparse : function (string) { return string; }, postformat : function (string) { return string; }, week : function (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; }, _week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. }, _invalidDate: 'Invalid date', invalidDate: function () { return this._invalidDate; } }); // Loads a language definition into the `languages` cache. The function // takes a key and optionally values. If not in the browser and no values // are provided, it will load the language file module. As a convenience, // this function also returns the language values. function loadLang(key, values) { values.abbr = key; if (!languages[key]) { languages[key] = new Language(); } languages[key].set(values); return languages[key]; } // Remove a language from the `languages` cache. Mostly useful in tests. function unloadLang(key) { delete languages[key]; } // Determines which language definition to use and returns it. // // With no parameters, it will return the global language. If you // pass in a language key, such as 'en', it will return the // definition for 'en', so long as 'en' has already been loaded using // moment.lang. function getLangDefinition(key) { var i = 0, j, lang, next, split, get = function (k) { if (!languages[k] && hasModule) { try { require('./lang/' + k); } catch (e) { } } return languages[k]; }; if (!key) { return moment.fn._lang; } if (!isArray(key)) { //short-circuit everything else lang = get(key); if (lang) { return lang; } key = [key]; } //pick the language from the array //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root while (i < key.length) { split = normalizeLanguage(key[i]).split('-'); j = split.length; next = normalizeLanguage(key[i + 1]); next = next ? next.split('-') : null; while (j > 0) { lang = get(split.slice(0, j).join('-')); if (lang) { return lang; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return moment.fn._lang; } /************************************ Formatting ************************************/ function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ""); } return input.replace(/\\/g, ""); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = ""; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.lang().invalidDate(); } format = expandFormat(format, m.lang()); if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } function ex