code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
params(path, captures, params = {}) { for (let len = captures.length, i = 0; i < len; i++) { if (this.paramNames[i]) { const c = captures[i]; if (c && c.length > 0) params[this.paramNames[i].name] = c ? safeDecodeURIComponent(c) : c; } } return params; }
Returns map of URL parameters for given `path` and `paramNames`. @param {String} path @param {Array.<String>} captures @param {Object=} params @returns {Object} @private
params
javascript
koajs/router
lib/layer.js
https://github.com/koajs/router/blob/master/lib/layer.js
MIT
captures(path) { return this.opts.ignoreCaptures ? [] : path.match(this.regexp).slice(1); }
Returns array of regexp url path captures. @param {String} path @returns {Array.<String>} @private
captures
javascript
koajs/router
lib/layer.js
https://github.com/koajs/router/blob/master/lib/layer.js
MIT
url(params, options) { let args = params; const url = this.path.replace(/\(\.\*\)/g, ''); if (typeof params !== 'object') { args = Array.prototype.slice.call(arguments); if (typeof args[args.length - 1] === 'object') { options = args[args.length - 1]; args = args.slice(0, -1); } } const toPath = compile(url, { encode: encodeURIComponent, ...options }); let replaced; const tokens = parse(url); let replace = {}; if (Array.isArray(args)) { for (let len = tokens.length, i = 0, j = 0; i < len; i++) { if (tokens[i].name) replace[tokens[i].name] = args[j++]; } } else if (tokens.some((token) => token.name)) { replace = params; } else if (!options) { options = params; } replaced = toPath(replace); if (options && options.query) { replaced = parseUrl(replaced); if (typeof options.query === 'string') { replaced.search = options.query; } else { replaced.search = undefined; replaced.query = options.query; } return formatUrl(replaced); } return replaced; }
Generate URL for route using given `params`. @example ```javascript const route = new Layer('/users/:id', ['GET'], fn); route.url({ id: 123 }); // => "/users/123" ``` @param {Object} params url parameters @returns {String} @private
url
javascript
koajs/router
lib/layer.js
https://github.com/koajs/router/blob/master/lib/layer.js
MIT
param(param, fn) { const { stack } = this; const params = this.paramNames; const middleware = function (ctx, next) { return fn.call(this, ctx.params[param], ctx, next); }; middleware.param = param; const names = params.map(function (p) { return p.name; }); const x = names.indexOf(param); if (x > -1) { // iterate through the stack, to figure out where to place the handler fn stack.some((fn, i) => { // param handlers are always first, so when we find an fn w/o a param property, stop here // if the param handler at this part of the stack comes after the one we are adding, stop here if (!fn.param || names.indexOf(fn.param) > x) { // inject this param handler right before the current item stack.splice(i, 0, middleware); return true; // then break the loop } }); } return this; }
Run validations on route named parameters. @example ```javascript router .param('user', function (id, ctx, next) { ctx.user = users[id]; if (!ctx.user) return ctx.status = 404; next(); }) .get('/users/:user', function (ctx, next) { ctx.body = ctx.user; }); ``` @param {String} param @param {Function} middleware @returns {Layer} @private
param
javascript
koajs/router
lib/layer.js
https://github.com/koajs/router/blob/master/lib/layer.js
MIT
middleware = function (ctx, next) { return fn.call(this, ctx.params[param], ctx, next); }
Run validations on route named parameters. @example ```javascript router .param('user', function (id, ctx, next) { ctx.user = users[id]; if (!ctx.user) return ctx.status = 404; next(); }) .get('/users/:user', function (ctx, next) { ctx.body = ctx.user; }); ``` @param {String} param @param {Function} middleware @returns {Layer} @private
middleware
javascript
koajs/router
lib/layer.js
https://github.com/koajs/router/blob/master/lib/layer.js
MIT
middleware = function (ctx, next) { return fn.call(this, ctx.params[param], ctx, next); }
Run validations on route named parameters. @example ```javascript router .param('user', function (id, ctx, next) { ctx.user = users[id]; if (!ctx.user) return ctx.status = 404; next(); }) .get('/users/:user', function (ctx, next) { ctx.body = ctx.user; }); ``` @param {String} param @param {Function} middleware @returns {Layer} @private
middleware
javascript
koajs/router
lib/layer.js
https://github.com/koajs/router/blob/master/lib/layer.js
MIT
setPrefix(prefix) { if (this.path) { this.path = this.path !== '/' || this.opts.strict === true ? `${prefix}${this.path}` : prefix; this.paramNames = []; this.regexp = pathToRegexp(this.path, this.paramNames, this.opts); } return this; }
Prefix route path. @param {String} prefix @returns {Layer} @private
setPrefix
javascript
koajs/router
lib/layer.js
https://github.com/koajs/router/blob/master/lib/layer.js
MIT
function safeDecodeURIComponent(text) { try { // TODO: take a look on `safeDecodeURIComponent` if we use it only with route params let's remove the `replace` method otherwise make it flexible. // @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent#decoding_query_parameters_from_a_url return decodeURIComponent(text.replace(/\+/g, ' ')); } catch { return text; } }
Safe decodeURIComponent, won't throw any error. If `decodeURIComponent` error happen, just return the original value. @param {String} text @returns {String} URL decode original string. @private
safeDecodeURIComponent
javascript
koajs/router
lib/layer.js
https://github.com/koajs/router/blob/master/lib/layer.js
MIT
constructor(opts = {}) { if (!(this instanceof Router)) return new Router(opts); // eslint-disable-line no-constructor-return this.opts = opts; this.methods = this.opts.methods || [ 'HEAD', 'OPTIONS', 'GET', 'PUT', 'PATCH', 'POST', 'DELETE' ]; this.exclusive = Boolean(this.opts.exclusive); this.params = {}; this.stack = []; this.host = this.opts.host; }
Create a new router. @example Basic usage: ```javascript const Koa = require('koa'); const Router = require('@koa/router'); const app = new Koa(); const router = new Router(); router.get('/', (ctx, next) => { // ctx.router available }); app .use(router.routes()) .use(router.allowedMethods()); ``` @alias module:koa-router @param {Object=} opts @param {Boolean=false} opts.exclusive only run last matched route's controller when there are multiple matches @param {String=} opts.prefix prefix router paths @param {String|RegExp=} opts.host host for router match @constructor
constructor
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
static url(path, ...args) { return Layer.prototype.url.apply({ path }, args); }
Generate URL from url pattern and given `params`. @example ```javascript const url = Router.url('/users/:id', {id: 1}); // => "/users/1" ``` @param {String} path url pattern @param {Object} params url parameters @returns {String}
url
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
use(...middleware) { const router = this; let path; // support array of paths if (Array.isArray(middleware[0]) && typeof middleware[0][0] === 'string') { const arrPaths = middleware[0]; for (const p of arrPaths) { router.use.apply(router, [p, ...middleware.slice(1)]); } return this; } const hasPath = typeof middleware[0] === 'string'; if (hasPath) path = middleware.shift(); for (const m of middleware) { if (m.router) { const cloneRouter = Object.assign( Object.create(Router.prototype), m.router, { stack: [...m.router.stack] } ); for (let j = 0; j < cloneRouter.stack.length; j++) { const nestedLayer = cloneRouter.stack[j]; const cloneLayer = Object.assign( Object.create(Layer.prototype), nestedLayer ); if (path) cloneLayer.setPrefix(path); if (router.opts.prefix) cloneLayer.setPrefix(router.opts.prefix); router.stack.push(cloneLayer); cloneRouter.stack[j] = cloneLayer; } if (router.params) { const routerParams = Object.keys(router.params); for (const key of routerParams) { cloneRouter.param(key, router.params[key]); } } } else { const keys = []; pathToRegexp(router.opts.prefix || '', keys); const routerPrefixHasParam = Boolean( router.opts.prefix && keys.length > 0 ); router.register(path || '([^/]*)', [], m, { end: false, ignoreCaptures: !hasPath && !routerPrefixHasParam }); } } return this; }
Use given middleware. Middleware run in the order they are defined by `.use()`. They are invoked sequentially, requests start at the first middleware and work their way "down" the middleware stack. @example ```javascript // session middleware will run before authorize router .use(session()) .use(authorize()); // use middleware only with given path router.use('/users', userAuth()); // or with an array of paths router.use(['/users', '/admin'], userAuth()); app.use(router.routes()); ``` @param {String=} path @param {Function} middleware @param {Function=} ... @returns {Router}
use
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
prefix(prefix) { prefix = prefix.replace(/\/$/, ''); this.opts.prefix = prefix; for (let i = 0; i < this.stack.length; i++) { const route = this.stack[i]; route.setPrefix(prefix); } return this; }
Set the path prefix for a Router instance that was already initialized. @example ```javascript router.prefix('/things/:thing_id') ``` @param {String} prefix @returns {Router}
prefix
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
middleware() { const router = this; const dispatch = (ctx, next) => { debug('%s %s', ctx.method, ctx.path); const hostMatched = router.matchHost(ctx.host); if (!hostMatched) { return next(); } const path = router.opts.routerPath || ctx.newRouterPath || ctx.path || ctx.routerPath; const matched = router.match(path, ctx.method); if (ctx.matched) { ctx.matched.push.apply(ctx.matched, matched.path); } else { ctx.matched = matched.path; } ctx.router = router; if (!matched.route) return next(); const matchedLayers = matched.pathAndMethod; const mostSpecificLayer = matchedLayers[matchedLayers.length - 1]; ctx._matchedRoute = mostSpecificLayer.path; if (mostSpecificLayer.name) { ctx._matchedRouteName = mostSpecificLayer.name; } const layerChain = ( router.exclusive ? [mostSpecificLayer] : matchedLayers ).reduce((memo, layer) => { memo.push((ctx, next) => { ctx.captures = layer.captures(path, ctx.captures); ctx.request.params = layer.params(path, ctx.captures, ctx.params); ctx.params = ctx.request.params; ctx.routerPath = layer.path; ctx.routerName = layer.name; ctx._matchedRoute = layer.path; if (layer.name) { ctx._matchedRouteName = layer.name; } return next(); }); return [...memo, ...layer.stack]; }, []); return compose(layerChain)(ctx, next); }; dispatch.router = this; return dispatch; }
Returns router middleware which dispatches a route matching the request. @returns {Function}
middleware
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
dispatch = (ctx, next) => { debug('%s %s', ctx.method, ctx.path); const hostMatched = router.matchHost(ctx.host); if (!hostMatched) { return next(); } const path = router.opts.routerPath || ctx.newRouterPath || ctx.path || ctx.routerPath; const matched = router.match(path, ctx.method); if (ctx.matched) { ctx.matched.push.apply(ctx.matched, matched.path); } else { ctx.matched = matched.path; } ctx.router = router; if (!matched.route) return next(); const matchedLayers = matched.pathAndMethod; const mostSpecificLayer = matchedLayers[matchedLayers.length - 1]; ctx._matchedRoute = mostSpecificLayer.path; if (mostSpecificLayer.name) { ctx._matchedRouteName = mostSpecificLayer.name; } const layerChain = ( router.exclusive ? [mostSpecificLayer] : matchedLayers ).reduce((memo, layer) => { memo.push((ctx, next) => { ctx.captures = layer.captures(path, ctx.captures); ctx.request.params = layer.params(path, ctx.captures, ctx.params); ctx.params = ctx.request.params; ctx.routerPath = layer.path; ctx.routerName = layer.name; ctx._matchedRoute = layer.path; if (layer.name) { ctx._matchedRouteName = layer.name; } return next(); }); return [...memo, ...layer.stack]; }, []); return compose(layerChain)(ctx, next); }
Returns router middleware which dispatches a route matching the request. @returns {Function}
dispatch
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
dispatch = (ctx, next) => { debug('%s %s', ctx.method, ctx.path); const hostMatched = router.matchHost(ctx.host); if (!hostMatched) { return next(); } const path = router.opts.routerPath || ctx.newRouterPath || ctx.path || ctx.routerPath; const matched = router.match(path, ctx.method); if (ctx.matched) { ctx.matched.push.apply(ctx.matched, matched.path); } else { ctx.matched = matched.path; } ctx.router = router; if (!matched.route) return next(); const matchedLayers = matched.pathAndMethod; const mostSpecificLayer = matchedLayers[matchedLayers.length - 1]; ctx._matchedRoute = mostSpecificLayer.path; if (mostSpecificLayer.name) { ctx._matchedRouteName = mostSpecificLayer.name; } const layerChain = ( router.exclusive ? [mostSpecificLayer] : matchedLayers ).reduce((memo, layer) => { memo.push((ctx, next) => { ctx.captures = layer.captures(path, ctx.captures); ctx.request.params = layer.params(path, ctx.captures, ctx.params); ctx.params = ctx.request.params; ctx.routerPath = layer.path; ctx.routerName = layer.name; ctx._matchedRoute = layer.path; if (layer.name) { ctx._matchedRouteName = layer.name; } return next(); }); return [...memo, ...layer.stack]; }, []); return compose(layerChain)(ctx, next); }
Returns router middleware which dispatches a route matching the request. @returns {Function}
dispatch
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
routes() { return this.middleware(); }
Returns router middleware which dispatches a route matching the request. @returns {Function}
routes
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
allowedMethods(options = {}) { const implemented = this.methods; return (ctx, next) => { return next().then(() => { const allowed = {}; if (ctx.matched && (!ctx.status || ctx.status === 404)) { for (let i = 0; i < ctx.matched.length; i++) { const route = ctx.matched[i]; for (let j = 0; j < route.methods.length; j++) { const method = route.methods[j]; allowed[method] = method; } } const allowedArr = Object.keys(allowed); if (!implemented.includes(ctx.method)) { if (options.throw) { const notImplementedThrowable = typeof options.notImplemented === 'function' ? options.notImplemented() // set whatever the user returns from their function : new HttpError.NotImplemented(); throw notImplementedThrowable; } else { ctx.status = 501; ctx.set('Allow', allowedArr.join(', ')); } } else if (allowedArr.length > 0) { if (ctx.method === 'OPTIONS') { ctx.status = 200; ctx.body = ''; ctx.set('Allow', allowedArr.join(', ')); } else if (!allowed[ctx.method]) { if (options.throw) { const notAllowedThrowable = typeof options.methodNotAllowed === 'function' ? options.methodNotAllowed() // set whatever the user returns from their function : new HttpError.MethodNotAllowed(); throw notAllowedThrowable; } else { ctx.status = 405; ctx.set('Allow', allowedArr.join(', ')); } } } } }); }; }
Returns separate middleware for responding to `OPTIONS` requests with an `Allow` header containing the allowed methods, as well as responding with `405 Method Not Allowed` and `501 Not Implemented` as appropriate. @example ```javascript const Koa = require('koa'); const Router = require('@koa/router'); const app = new Koa(); const router = new Router(); app.use(router.routes()); app.use(router.allowedMethods()); ``` **Example with [Boom](https://github.com/hapijs/boom)** ```javascript const Koa = require('koa'); const Router = require('@koa/router'); const Boom = require('boom'); const app = new Koa(); const router = new Router(); app.use(router.routes()); app.use(router.allowedMethods({ throw: true, notImplemented: () => new Boom.notImplemented(), methodNotAllowed: () => new Boom.methodNotAllowed() })); ``` @param {Object=} options @param {Boolean=} options.throw throw error instead of setting status and header @param {Function=} options.notImplemented throw the returned value in place of the default NotImplemented error @param {Function=} options.methodNotAllowed throw the returned value in place of the default MethodNotAllowed error @returns {Function}
allowedMethods
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
all(name, path, middleware) { if (typeof path === 'string') { middleware = Array.prototype.slice.call(arguments, 2); } else { middleware = Array.prototype.slice.call(arguments, 1); path = name; name = null; } // Sanity check to ensure we have a viable path candidate (eg: string|regex|non-empty array) if ( typeof path !== 'string' && !(path instanceof RegExp) && (!Array.isArray(path) || path.length === 0) ) throw new Error('You have to provide a path when adding an all handler'); this.register(path, methods, middleware, { name }); return this; }
Register route with all methods. @param {String} name Optional. @param {String} path @param {Function=} middleware You may also pass multiple middleware. @param {Function} callback @returns {Router}
all
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
redirect(source, destination, code) { // lookup source route by name if (typeof source === 'symbol' || source[0] !== '/') { source = this.url(source); if (source instanceof Error) throw source; } // lookup destination route by name if ( typeof destination === 'symbol' || (destination[0] !== '/' && !destination.includes('://')) ) { destination = this.url(destination); if (destination instanceof Error) throw destination; } return this.all(source, (ctx) => { ctx.redirect(destination); ctx.status = code || 301; }); }
Redirect `source` to `destination` URL with optional 30x status `code`. Both `source` and `destination` can be route names. ```javascript router.redirect('/login', 'sign-in'); ``` This is equivalent to: ```javascript router.all('/login', ctx => { ctx.redirect('/sign-in'); ctx.status = 301; }); ``` @param {String} source URL or route name. @param {String} destination URL or route name. @param {Number=} code HTTP status code (default: 301). @returns {Router}
redirect
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
register(path, methods, middleware, opts = {}) { const router = this; const { stack } = this; // support array of paths if (Array.isArray(path)) { for (const curPath of path) { router.register.call(router, curPath, methods, middleware, opts); } return this; } // create route const route = new Layer(path, methods, middleware, { end: opts.end === false ? opts.end : true, name: opts.name, sensitive: opts.sensitive || this.opts.sensitive || false, strict: opts.strict || this.opts.strict || false, prefix: opts.prefix || this.opts.prefix || '', ignoreCaptures: opts.ignoreCaptures }); if (this.opts.prefix) { route.setPrefix(this.opts.prefix); } // add parameter middleware for (let i = 0; i < Object.keys(this.params).length; i++) { const param = Object.keys(this.params)[i]; route.param(param, this.params[param]); } stack.push(route); debug('defined route %s %s', route.methods, route.path); return route; }
Create and register a route. @param {String} path Path string. @param {Array.<String>} methods Array of HTTP verbs. @param {Function} middleware Multiple middleware also accepted. @returns {Layer} @private
register
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
route(name) { const routes = this.stack; for (let len = routes.length, i = 0; i < len; i++) { if (routes[i].name && routes[i].name === name) return routes[i]; } return false; }
Lookup route with given `name`. @param {String} name @returns {Layer|false}
route
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
match(path, method) { const layers = this.stack; let layer; const matched = { path: [], pathAndMethod: [], route: false }; for (let len = layers.length, i = 0; i < len; i++) { layer = layers[i]; debug('test %s %s', layer.path, layer.regexp); // eslint-disable-next-line unicorn/prefer-regexp-test if (layer.match(path)) { matched.path.push(layer); if (layer.methods.length === 0 || layer.methods.includes(method)) { matched.pathAndMethod.push(layer); if (layer.methods.length > 0) matched.route = true; } } } return matched; }
Match given `path` and return corresponding routes. @param {String} path @param {String} method @returns {Object.<path, pathAndMethod>} returns layers that matched path and path and method. @private
match
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
matchHost(input) { const { host } = this; if (!host) { return true; } if (!input) { return false; } if (typeof host === 'string') { return input === host; } if (typeof host === 'object' && host instanceof RegExp) { return host.test(input); } }
Match given `input` to allowed host @param {String} input @returns {boolean}
matchHost
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
param(param, middleware) { this.params[param] = middleware; for (let i = 0; i < this.stack.length; i++) { const route = this.stack[i]; route.param(param, middleware); } return this; }
Run middleware for named route parameters. Useful for auto-loading or validation. @example ```javascript router .param('user', (id, ctx, next) => { ctx.user = users[id]; if (!ctx.user) return ctx.status = 404; return next(); }) .get('/users/:user', ctx => { ctx.body = ctx.user; }) .get('/users/:user/friends', ctx => { return ctx.user.getFriends().then(function(friends) { ctx.body = friends; }); }) // /users/3 => {"id": 3, "name": "Alex"} // /users/3/friends => [{"id": 4, "name": "TJ"}] ``` @param {String} param @param {Function} middleware @returns {Router}
param
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
function loadData(locations, response, callback) { if (locations.length === 0) callback(null, response); else $.get(locations.shift()) .fail(function(e) { callback(e, null); }) .done(function (data) { if (response.length > 0) response += '\n\n'; response += data; loadData(locations, response, callback); }); }
File fetcher function. Fetches a given `url` via AJAX. See [Runner#run()] for a description of fetcher functions.
loadData
javascript
localForage/localForage
docs/scripts/flatdoc.js
https://github.com/localForage/localForage/blob/master/docs/scripts/flatdoc.js
Apache-2.0
function mkdir_p(level) { cache.length = level + 1; var obj = cache[level]; if (!obj) { var parent = (level > 1) ? mkdir_p(level-1) : root; obj = { items: [], level: level }; cache = cache.concat([obj, obj]); parent.items.push(obj); } return obj; }
Returns menu data for a given HTML. menu = Flatdoc.transformer.getMenu($content); menu == { level: 0, items: [{ section: "Getting started", level: 1, items: [...]}, ...]}
mkdir_p
javascript
localForage/localForage
docs/scripts/flatdoc.js
https://github.com/localForage/localForage/blob/master/docs/scripts/flatdoc.js
Apache-2.0
function getTextNodesIn(el) { var exclude = 'iframe,pre,code'; return $(el).find(':not('+exclude+')').andSelf().contents().filter(function() { return this.nodeType == 3 && $(this).closest(exclude).length === 0; }); }
Fetches a given element from the DOM. Returns a jQuery object. @api private
getTextNodesIn
javascript
localForage/localForage
docs/scripts/flatdoc.js
https://github.com/localForage/localForage/blob/master/docs/scripts/flatdoc.js
Apache-2.0
function quotify(a) { a = a.replace(/(^|[\-\u2014\s(\["])'/g, "$1\u2018"); // opening singles a = a.replace(/'/g, "\u2019"); // closing singles & apostrophes a = a.replace(/(^|[\-\u2014\/\[(\u2018\s])"/g, "$1\u201c"); // opening doubles a = a.replace(/"/g, "\u201d"); // closing doubles a = a.replace(/\.\.\./g, "\u2026"); // ellipses a = a.replace(/--/g, "\u2014"); // em-dashes return a; }
Fetches a given element from the DOM. Returns a jQuery object. @api private
quotify
javascript
localForage/localForage
docs/scripts/flatdoc.js
https://github.com/localForage/localForage/blob/master/docs/scripts/flatdoc.js
Apache-2.0
function each(ary, func) { if (ary) { var i; for (i = 0; i < ary.length; i += 1) { if (ary[i] && func(ary[i], i, ary)) { break; } } } }
Helper function for iterating over an array. If the func returns a true value, it will break out of the loop.
each
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function eachReverse(ary, func) { if (ary) { var i; for (i = ary.length - 1; i > -1; i -= 1) { if (ary[i] && func(ary[i], i, ary)) { break; } } } }
Helper function for iterating over an array backwards. If the func returns a true value, it will break out of the loop.
eachReverse
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function hasProp(obj, prop) { return hasOwn.call(obj, prop); }
Helper function for iterating over an array backwards. If the func returns a true value, it will break out of the loop.
hasProp
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function getOwn(obj, prop) { return hasProp(obj, prop) && obj[prop]; }
Helper function for iterating over an array backwards. If the func returns a true value, it will break out of the loop.
getOwn
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function eachProp(obj, func) { var prop; for (prop in obj) { if (hasProp(obj, prop)) { if (func(obj[prop], prop)) { break; } } } }
Cycles over properties in an object and calls a function for each property value. If the function returns a truthy value, then the iteration is stopped.
eachProp
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function mixin(target, source, force, deepStringMixin) { if (source) { eachProp(source, function (value, prop) { if (force || !hasProp(target, prop)) { if (deepStringMixin && typeof value !== 'string') { if (!target[prop]) { target[prop] = {}; } mixin(target[prop], value, force, deepStringMixin); } else { target[prop] = value; } } }); } return target; }
Simple function to mix in properties from source into target, but only if target does not already have a property of the same name.
mixin
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function bind(obj, fn) { return function () { return fn.apply(obj, arguments); }; }
Simple function to mix in properties from source into target, but only if target does not already have a property of the same name.
bind
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function scripts() { return document.getElementsByTagName('script'); }
Simple function to mix in properties from source into target, but only if target does not already have a property of the same name.
scripts
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function getGlobal(value) { if (!value) { return value; } var g = global; each(value.split('.'), function (part) { g = g[part]; }); return g; }
Simple function to mix in properties from source into target, but only if target does not already have a property of the same name.
getGlobal
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function makeError(id, msg, err, requireModules) { var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); e.requireType = id; e.requireModules = requireModules; if (err) { e.originalError = err; } return e; }
Constructs an error with a pointer to an URL with more information. @param {String} id the error ID that maps to an ID on a web page. @param {String} message human readable error. @param {Error} [err] the original error, if there is one. @returns {Error}
makeError
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function newContext(contextName) { var inCheckLoaded, Module, context, handlers, checkLoadedTimeoutId, config = { //Defaults. Do not set a default for map //config to speed up normalize(), which //will run faster if there is no default. waitSeconds: 7, baseUrl: './', paths: {}, pkgs: {}, shim: {}, config: {} }, registry = {}, //registry of just enabled modules, to speed //cycle breaking code when lots of modules //are registered, but not activated. enabledRegistry = {}, undefEvents = {}, defQueue = [], defined = {}, urlFetched = {}, requireCounter = 1, unnormalizedCounter = 1; /** * Trims the . and .. from an array of path segments. * It will keep a leading path segment if a .. will become * the first path segment, to help with module name lookups, * which act like paths, but can be remapped. But the end result, * all paths that use this function should look normalized. * NOTE: this method MODIFIES the input array. * @param {Array} ary the array of path segments. */ function trimDots(ary) { var i, part; for (i = 0; ary[i]; i += 1) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } } /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @param {Boolean} applyMap apply the map config to the value. Should * only be done if this normalization is for a dependency ID. * @returns {String} normalized name */ function normalize(name, baseName, applyMap) { var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment, foundMap, foundI, foundStarMap, starI, baseParts = baseName && baseName.split('/'), normalizedBaseParts = baseParts, map = config.map, starMap = map && map['*']; //Adjust any relative paths. if (name && name.charAt(0) === '.') { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { if (getOwn(config.pkgs, baseName)) { //If the baseName is a package name, then just treat it as one //name to concat the name with. normalizedBaseParts = baseParts = [baseName]; } else { //Convert baseName to array, and lop off the last part, //so that . matches that 'directory' and not name of the baseName's //module. For instance, baseName of 'one/two/three', maps to //'one/two/three.js', but we want the directory, 'one/two' for //this normalization. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); } name = normalizedBaseParts.concat(name.split('/')); trimDots(name); //Some use of packages may use a . path to reference the //'main' module name, so normalize for that. pkgConfig = getOwn(config.pkgs, (pkgName = name[0])); name = name.join('/'); if (pkgConfig && name === pkgName + '/' + pkgConfig.main) { name = pkgName; } } else if (name.indexOf('./') === 0) { // No baseName, so this is ID is resolved relative // to baseUrl, pull off the leading dot. name = name.substring(2); } } //Apply map config if available. if (applyMap && map && (baseParts || starMap)) { nameParts = name.split('/'); for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join('/'); if (baseParts) { //Find the longest baseName segment match in the config. //So, do joins on the biggest to smallest lengths of baseParts. for (j = baseParts.length; j > 0; j -= 1) { mapValue = getOwn(map, baseParts.slice(0, j).join('/')); //baseName segment has config, find if it has one for //this name. if (mapValue) { mapValue = getOwn(mapValue, nameSegment); if (mapValue) { //Match, update name to the new value. foundMap = mapValue; foundI = i; break; } } } } if (foundMap) { break; } //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { foundStarMap = getOwn(starMap, nameSegment); starI = i; } } if (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } return name; } function removeScript(name) { if (isBrowser) { each(scripts(), function (scriptNode) { if (scriptNode.getAttribute('data-requiremodule') === name && scriptNode.getAttribute('data-requirecontext') === context.contextName) { scriptNode.parentNode.removeChild(scriptNode); return true; } }); } } function hasPathFallback(id) { var pathConfig = getOwn(config.paths, id); if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { removeScript(id); //Pop off the first array value, since it failed, and //retry pathConfig.shift(); context.require.undef(id); context.require([id]); return true; } } //Turns a plugin!resource to [plugin, resource] //with the plugin being undefined if the name //did not have a plugin prefix. function splitPrefix(name) { var prefix, index = name ? name.indexOf('!') : -1; if (index > -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } return [prefix, name]; } /** * Creates a module mapping that includes plugin prefix, module * name, and path. If parentModuleMap is provided it will * also normalize the name via require.normalize() * * @param {String} name the module name * @param {String} [parentModuleMap] parent module map * for the module name, used to resolve relative names. * @param {Boolean} isNormalized: is the ID already normalized. * This is true if this call is done for a define() module ID. * @param {Boolean} applyMap: apply the map config to the ID. * Should only be true if this map is for a dependency. * * @returns {Object} */ function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { var url, pluginModule, suffix, nameParts, prefix = null, parentName = parentModuleMap ? parentModuleMap.name : null, originalName = name, isDefine = true, normalizedName = ''; //If no name, then it means it is a require call, generate an //internal name. if (!name) { isDefine = false; name = '_@r' + (requireCounter += 1); } nameParts = splitPrefix(name); prefix = nameParts[0]; name = nameParts[1]; if (prefix) { prefix = normalize(prefix, parentName, applyMap); pluginModule = getOwn(defined, prefix); } //Account for relative paths if there is a base name. if (name) { if (prefix) { if (pluginModule && pluginModule.normalize) { //Plugin is loaded, use its normalize method. normalizedName = pluginModule.normalize(name, function (name) { return normalize(name, parentName, applyMap); }); } else { normalizedName = normalize(name, parentName, applyMap); } } else { //A regular module. normalizedName = normalize(name, parentName, applyMap); //Normalized name may be a plugin ID due to map config //application in normalize. The map config values must //already be normalized, so do not need to redo that part. nameParts = splitPrefix(normalizedName); prefix = nameParts[0]; normalizedName = nameParts[1]; isNormalized = true; url = context.nameToUrl(normalizedName); } } //If the id is a plugin id that cannot be determined if it needs //normalization, stamp it with a unique ID so two matching relative //ids that may conflict can be separate. suffix = prefix && !pluginModule && !isNormalized ? '_unnormalized' + (unnormalizedCounter += 1) : ''; return { prefix: prefix, name: normalizedName, parentMap: parentModuleMap, unnormalized: !!suffix, url: url, originalName: originalName, isDefine: isDefine, id: (prefix ? prefix + '!' + normalizedName : normalizedName) + suffix }; } function getModule(depMap) { var id = depMap.id, mod = getOwn(registry, id); if (!mod) { mod = registry[id] = new context.Module(depMap); } return mod; } function on(depMap, name, fn) { var id = depMap.id, mod = getOwn(registry, id); if (hasProp(defined, id) && (!mod || mod.defineEmitComplete)) { if (name === 'defined') { fn(defined[id]); } } else { getModule(depMap).on(name, fn); } } function onError(err, errback) { var ids = err.requireModules, notified = false; if (errback) { errback(err); } else { each(ids, function (id) { var mod = getOwn(registry, id); if (mod) { //Set error on module, so it skips timeout checks. mod.error = err; if (mod.events.error) { notified = true; mod.emit('error', err); } } }); if (!notified) { req.onError(err); } } } /** * Internal method to transfer globalQueue items to this context's * defQueue. */ function takeGlobalQueue() { //Push all the globalDefQueue items into the context's defQueue if (globalDefQueue.length) { //Array splice in the values since the context code has a //local var ref to defQueue, so cannot just reassign the one //on context. apsp.apply(defQueue, [defQueue.length - 1, 0].concat(globalDefQueue)); globalDefQueue = []; } } handlers = { 'require': function (mod) { if (mod.require) { return mod.require; } else { return (mod.require = context.makeRequire(mod.map)); } }, 'exports': function (mod) { mod.usingExports = true; if (mod.map.isDefine) { if (mod.exports) { return mod.exports; } else { return (mod.exports = defined[mod.map.id] = {}); } } }, 'module': function (mod) { if (mod.module) { return mod.module; } else { return (mod.module = { id: mod.map.id, uri: mod.map.url, config: function () { return (config.config && getOwn(config.config, mod.map.id)) || {}; }, exports: defined[mod.map.id] }); } } }; function cleanRegistry(id) { //Clean up machinery used for waiting modules. delete registry[id]; delete enabledRegistry[id]; } function breakCycle(mod, traced, processed) { var id = mod.map.id; if (mod.error) { mod.emit('error', mod.error); } else { traced[id] = true; each(mod.depMaps, function (depMap, i) { var depId = depMap.id, dep = getOwn(registry, depId); //Only force things that have not completed //being defined, so still in the registry, //and only if it has not been matched up //in the module already. if (dep && !mod.depMatched[i] && !processed[depId]) { if (getOwn(traced, depId)) { mod.defineDep(i, defined[depId]); mod.check(); //pass false? } else { breakCycle(dep, traced, processed); } } }); processed[id] = true; } } function checkLoaded() { var map, modId, err, usingPathFallback, waitInterval = config.waitSeconds * 1000, //It is possible to disable the wait interval by using waitSeconds of 0. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), noLoads = [], reqCalls = [], stillLoading = false, needCycleCheck = true; //Do not bother if this call was a result of a cycle break. if (inCheckLoaded) { return; } inCheckLoaded = true; //Figure out the state of all the modules. eachProp(enabledRegistry, function (mod) { map = mod.map; modId = map.id; //Skip things that are not enabled or in error state. if (!mod.enabled) { return; } if (!map.isDefine) { reqCalls.push(mod); } if (!mod.error) { //If the module should be executed, and it has not //been inited and time is up, remember it. if (!mod.inited && expired) { if (hasPathFallback(modId)) { usingPathFallback = true; stillLoading = true; } else { noLoads.push(modId); removeScript(modId); } } else if (!mod.inited && mod.fetched && map.isDefine) { stillLoading = true; if (!map.prefix) { //No reason to keep looking for unfinished //loading. If the only stillLoading is a //plugin resource though, keep going, //because it may be that a plugin resource //is waiting on a non-plugin cycle. return (needCycleCheck = false); } } } }); if (expired && noLoads.length) { //If wait time expired, throw error of unloaded modules. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); err.contextName = context.contextName; return onError(err); } //Not expired, check for a cycle. if (needCycleCheck) { each(reqCalls, function (mod) { breakCycle(mod, {}, {}); }); } //If still waiting on loads, and the waiting load is something //other than a plugin resource, or there are still outstanding //scripts, then just try back later. if ((!expired || usingPathFallback) && stillLoading) { //Something is still waiting to load. Wait for it, but only //if a timeout is not already in effect. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { checkLoadedTimeoutId = setTimeout(function () { checkLoadedTimeoutId = 0; checkLoaded(); }, 50); } } inCheckLoaded = false; } Module = function (map) { this.events = getOwn(undefEvents, map.id) || {}; this.map = map; this.shim = getOwn(config.shim, map.id); this.depExports = []; this.depMaps = []; this.depMatched = []; this.pluginMaps = {}; this.depCount = 0; /* this.exports this.factory this.depMaps = [], this.enabled, this.fetched */ }; Module.prototype = { init: function (depMaps, factory, errback, options) { options = options || {}; //Do not do more inits if already done. Can happen if there //are multiple define calls for the same module. That is not //a normal, common case, but it is also not unexpected. if (this.inited) { return; } this.factory = factory; if (errback) { //Register for errors on this module. this.on('error', errback); } else if (this.events.error) { //If no errback already, but there are error listeners //on this module, set up an errback to pass to the deps. errback = bind(this, function (err) { this.emit('error', err); }); } //Do a copy of the dependency array, so that //source inputs are not modified. For example //"shim" deps are passed in here directly, and //doing a direct modification of the depMaps array //would affect that config. this.depMaps = depMaps && depMaps.slice(0); this.errback = errback; //Indicate this module has be initialized this.inited = true; this.ignore = options.ignore; //Could have option to init this module in enabled mode, //or could have been previously marked as enabled. However, //the dependencies are not known until init is called. So //if enabled previously, now trigger dependencies as enabled. if (options.enabled || this.enabled) { //Enable this module and dependencies. //Will call this.check() this.enable(); } else { this.check(); } }, defineDep: function (i, depExports) { //Because of cycles, defined callback for a given //export can be called more than once. if (!this.depMatched[i]) { this.depMatched[i] = true; this.depCount -= 1; this.depExports[i] = depExports; } }, fetch: function () { if (this.fetched) { return; } this.fetched = true; context.startTime = (new Date()).getTime(); var map = this.map; //If the manager is for a plugin managed resource, //ask the plugin to load it now. if (this.shim) { context.makeRequire(this.map, { enableBuildCallback: true })(this.shim.deps || [], bind(this, function () { return map.prefix ? this.callPlugin() : this.load(); })); } else { //Regular dependency. return map.prefix ? this.callPlugin() : this.load(); } }, load: function () { var url = this.map.url; //Regular dependency. if (!urlFetched[url]) { urlFetched[url] = true; context.load(this.map.id, url); } }, /** * Checks if the module is ready to define itself, and if so, * define it. */ check: function () { if (!this.enabled || this.enabling) { return; } var err, cjsModule, id = this.map.id, depExports = this.depExports, exports = this.exports, factory = this.factory; if (!this.inited) { this.fetch(); } else if (this.error) { this.emit('error', this.error); } else if (!this.defining) { //The factory could trigger another require call //that would result in checking this module to //define itself again. If already in the process //of doing that, skip this work. this.defining = true; if (this.depCount < 1 && !this.defined) { if (isFunction(factory)) { //If there is an error listener, favor passing //to that instead of throwing an error. if (this.events.error) { try { exports = context.execCb(id, factory, depExports, exports); } catch (e) { err = e; } } else { exports = context.execCb(id, factory, depExports, exports); } if (this.map.isDefine) { //If setting exports via 'module' is in play, //favor that over return value and exports. After that, //favor a non-undefined return value over exports use. cjsModule = this.module; if (cjsModule && cjsModule.exports !== undefined && //Make sure it is not already the exports value cjsModule.exports !== this.exports) { exports = cjsModule.exports; } else if (exports === undefined && this.usingExports) { //exports already set the defined value. exports = this.exports; } } if (err) { err.requireMap = this.map; err.requireModules = [this.map.id]; err.requireType = 'define'; return onError((this.error = err)); } } else { //Just a literal value exports = factory; } this.exports = exports; if (this.map.isDefine && !this.ignore) { defined[id] = exports; if (req.onResourceLoad) { req.onResourceLoad(context, this.map, this.depMaps); } } //Clean up cleanRegistry(id); this.defined = true; } //Finished the define stage. Allow calling check again //to allow define notifications below in the case of a //cycle. this.defining = false; if (this.defined && !this.defineEmitted) { this.defineEmitted = true; this.emit('defined', this.exports); this.defineEmitComplete = true; } } }, callPlugin: function () { var map = this.map, id = map.id, //Map already normalized the prefix. pluginMap = makeModuleMap(map.prefix); //Mark this as a dependency for this plugin, so it //can be traced for cycles. this.depMaps.push(pluginMap); on(pluginMap, 'defined', bind(this, function (plugin) { var load, normalizedMap, normalizedMod, name = this.map.name, parentName = this.map.parentMap ? this.map.parentMap.name : null, localRequire = context.makeRequire(map.parentMap, { enableBuildCallback: true }); //If current map is not normalized, wait for that //normalized name to load instead of continuing. if (this.map.unnormalized) { //Normalize the ID if the plugin allows it. if (plugin.normalize) { name = plugin.normalize(name, function (name) { return normalize(name, parentName, true); }) || ''; } //prefix and name should already be normalized, no need //for applying map config again either. normalizedMap = makeModuleMap(map.prefix + '!' + name, this.map.parentMap); on(normalizedMap, 'defined', bind(this, function (value) { this.init([], function () { return value; }, null, { enabled: true, ignore: true }); })); normalizedMod = getOwn(registry, normalizedMap.id); if (normalizedMod) { //Mark this as a dependency for this plugin, so it //can be traced for cycles. this.depMaps.push(normalizedMap); if (this.events.error) { normalizedMod.on('error', bind(this, function (err) { this.emit('error', err); })); } normalizedMod.enable(); } return; } load = bind(this, function (value) { this.init([], function () { return value; }, null, { enabled: true }); }); load.error = bind(this, function (err) { this.inited = true; this.error = err; err.requireModules = [id]; //Remove temp unnormalized modules for this module, //since they will never be resolved otherwise now. eachProp(registry, function (mod) { if (mod.map.id.indexOf(id + '_unnormalized') === 0) { cleanRegistry(mod.map.id); } }); onError(err); }); //Allow plugins to load other code without having to know the //context or how to 'complete' the load. load.fromText = bind(this, function (text, textAlt) { /*jslint evil: true */ var moduleName = map.name, moduleMap = makeModuleMap(moduleName), hasInteractive = useInteractive; //As of 2.1.0, support just passing the text, to reinforce //fromText only being called once per resource. Still //support old style of passing moduleName but discard //that moduleName in favor of the internal ref. if (textAlt) { text = textAlt; } //Turn off interactive script matching for IE for any define //calls in the text, then turn it back on at the end. if (hasInteractive) { useInteractive = false; } //Prime the system by creating a module instance for //it. getModule(moduleMap); //Transfer any config to this other module. if (hasProp(config.config, id)) { config.config[moduleName] = config.config[id]; } try { req.exec(text); } catch (e) { return onError(makeError('fromtexteval', 'fromText eval for ' + id + ' failed: ' + e, e, [id])); } if (hasInteractive) { useInteractive = true; } //Mark this as a dependency for the plugin //resource this.depMaps.push(moduleMap); //Support anonymous modules. context.completeLoad(moduleName); //Bind the value of that module to the value for this //resource ID. localRequire([moduleName], load); }); //Use parentName here since the plugin's name is not reliable, //could be some weird string with no path that actually wants to //reference the parentName's path. plugin.load(map.name, localRequire, load, config); })); context.enable(pluginMap, this); this.pluginMaps[pluginMap.id] = pluginMap; }, enable: function () { enabledRegistry[this.map.id] = this; this.enabled = true; //Set flag mentioning that the module is enabling, //so that immediate calls to the defined callbacks //for dependencies do not trigger inadvertent load //with the depCount still being zero. this.enabling = true; //Enable each dependency each(this.depMaps, bind(this, function (depMap, i) { var id, mod, handler; if (typeof depMap === 'string') { //Dependency needs to be converted to a depMap //and wired up to this module. depMap = makeModuleMap(depMap, (this.map.isDefine ? this.map : this.map.parentMap), false, !this.skipMap); this.depMaps[i] = depMap; handler = getOwn(handlers, depMap.id); if (handler) { this.depExports[i] = handler(this); return; } this.depCount += 1; on(depMap, 'defined', bind(this, function (depExports) { this.defineDep(i, depExports); this.check(); })); if (this.errback) { on(depMap, 'error', this.errback); } } id = depMap.id; mod = registry[id]; //Skip special modules like 'require', 'exports', 'module' //Also, don't call enable if it is already enabled, //important in circular dependency cases. if (!hasProp(handlers, id) && mod && !mod.enabled) { context.enable(depMap, this); } })); //Enable each plugin that is used in //a dependency eachProp(this.pluginMaps, bind(this, function (pluginMap) { var mod = getOwn(registry, pluginMap.id); if (mod && !mod.enabled) { context.enable(pluginMap, this); } })); this.enabling = false; this.check(); }, on: function (name, cb) { var cbs = this.events[name]; if (!cbs) { cbs = this.events[name] = []; } cbs.push(cb); }, emit: function (name, evt) { each(this.events[name], function (cb) { cb(evt); }); if (name === 'error') { //Now that the error handler was triggered, remove //the listeners, since this broken Module instance //can stay around for a while in the registry. delete this.events[name]; } } }; function callGetModule(args) { //Skip modules already defined. if (!hasProp(defined, args[0])) { getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); } } function removeListener(node, func, name, ieName) { //Favor detachEvent because of IE9 //issue, see attachEvent/addEventListener comment elsewhere //in this file. if (node.detachEvent && !isOpera) { //Probably IE. If not it will throw an error, which will be //useful to know. if (ieName) { node.detachEvent(ieName, func); } } else { node.removeEventListener(name, func, false); } } /** * Given an event from a script node, get the requirejs info from it, * and then removes the event listeners on the node. * @param {Event} evt * @returns {Object} */ function getScriptData(evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. var node = evt.currentTarget || evt.srcElement; //Remove the listeners once here. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); removeListener(node, context.onScriptError, 'error'); return { node: node, id: node && node.getAttribute('data-requiremodule') }; } function intakeDefines() { var args; //Any defined modules in the global queue, intake them now. takeGlobalQueue(); //Make sure any remaining defQueue items get properly processed. while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1])); } else { //args are id, deps, factory. Should be normalized by the //define() function. callGetModule(args); } } } context = { config: config, contextName: contextName, registry: registry, defined: defined, urlFetched: urlFetched, defQueue: defQueue, Module: Module, makeModuleMap: makeModuleMap, nextTick: req.nextTick, onError: onError, /** * Set a configuration for the context. * @param {Object} cfg config object to integrate. */ configure: function (cfg) { //Make sure the baseUrl ends in a slash. if (cfg.baseUrl) { if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { cfg.baseUrl += '/'; } } //Save off the paths and packages since they require special processing, //they are additive. var pkgs = config.pkgs, shim = config.shim, objs = { paths: true, config: true, map: true }; eachProp(cfg, function (value, prop) { if (objs[prop]) { if (prop === 'map') { if (!config.map) { config.map = {}; } mixin(config[prop], value, true, true); } else { mixin(config[prop], value, true); } } else { config[prop] = value; } }); //Merge shim if (cfg.shim) { eachProp(cfg.shim, function (value, id) { //Normalize the structure if (isArray(value)) { value = { deps: value }; } if ((value.exports || value.init) && !value.exportsFn) { value.exportsFn = context.makeShimExports(value); } shim[id] = value; }); config.shim = shim; } //Adjust packages if necessary. if (cfg.packages) { each(cfg.packages, function (pkgObj) { var location; pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj; location = pkgObj.location; //Create a brand new object on pkgs, since currentPackages can //be passed in again, and config.pkgs is the internal transformed //state for all package configs. pkgs[pkgObj.name] = { name: pkgObj.name, location: location || pkgObj.name, //Remove leading dot in main, so main paths are normalized, //and remove any trailing .js, since different package //envs have different conventions: some use a module name, //some use a file name. main: (pkgObj.main || 'main') .replace(currDirRegExp, '') .replace(jsSuffixRegExp, '') }; }); //Done with modifications, assing packages back to context config config.pkgs = pkgs; } //If there are any "waiting to execute" modules in the registry, //update the maps for them, since their info, like URLs to load, //may have changed. eachProp(registry, function (mod, id) { //If module already has init called, since it is too //late to modify them, and ignore unnormalized ones //since they are transient. if (!mod.inited && !mod.map.unnormalized) { mod.map = makeModuleMap(id); } }); //If a deps array or a config callback is specified, then call //require with those args. This is useful when require is defined as a //config object before require.js is loaded. if (cfg.deps || cfg.callback) { context.require(cfg.deps || [], cfg.callback); } }, makeShimExports: function (value) { function fn() { var ret; if (value.init) { ret = value.init.apply(global, arguments); } return ret || (value.exports && getGlobal(value.exports)); } return fn; }, makeRequire: function (relMap, options) { options = options || {}; function localRequire(deps, callback, errback) { var id, map, requireMod; if (options.enableBuildCallback && callback && isFunction(callback)) { callback.__requireJsBuild = true; } if (typeof deps === 'string') { if (isFunction(callback)) { //Invalid call return onError(makeError('requireargs', 'Invalid require call'), errback); } //If require|exports|module are requested, get the //value for them from the special handlers. Caveat: //this only works while module is being defined. if (relMap && hasProp(handlers, deps)) { return handlers[deps](registry[relMap.id]); } //Synchronous access to one module. If require.get is //available (as in the Node adapter), prefer that. if (req.get) { return req.get(context, deps, relMap, localRequire); } //Normalize module name, if it contains . or .. map = makeModuleMap(deps, relMap, false, true); id = map.id; if (!hasProp(defined, id)) { return onError(makeError('notloaded', 'Module name "' + id + '" has not been loaded yet for context: ' + contextName + (relMap ? '' : '. Use require([])'))); } return defined[id]; } //Grab defines waiting in the global queue. intakeDefines(); //Mark all the dependencies as needing to be loaded. context.nextTick(function () { //Some defines could have been added since the //require call, collect them. intakeDefines(); requireMod = getModule(makeModuleMap(null, relMap)); //Store if map config should be applied to this require //call for dependencies. requireMod.skipMap = options.skipMap; requireMod.init(deps, callback, errback, { enabled: true }); checkLoaded(); }); return localRequire; } mixin(localRequire, { isBrowser: isBrowser, /** * Converts a module name + .extension into an URL path. * *Requires* the use of a module name. It does not support using * plain URLs like nameToUrl. */ toUrl: function (moduleNamePlusExt) { var ext, index = moduleNamePlusExt.lastIndexOf('.'), segment = moduleNamePlusExt.split('/')[0], isRelative = segment === '.' || segment === '..'; //Have a file extension alias, and it is not the //dots from a relative path. if (index !== -1 && (!isRelative || index > 1)) { ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); moduleNamePlusExt = moduleNamePlusExt.substring(0, index); } return context.nameToUrl(normalize(moduleNamePlusExt, relMap && relMap.id, true), ext, true); }, defined: function (id) { return hasProp(defined, makeModuleMap(id, relMap, false, true).id); }, specified: function (id) { id = makeModuleMap(id, relMap, false, true).id; return hasProp(defined, id) || hasProp(registry, id); } }); //Only allow undef on top level require calls if (!relMap) { localRequire.undef = function (id) { //Bind any waiting define() calls to this context, //fix for #408 takeGlobalQueue(); var map = makeModuleMap(id, relMap, true), mod = getOwn(registry, id); delete defined[id]; delete urlFetched[map.url]; delete undefEvents[id]; if (mod) { //Hold on to listeners in case the //module will be attempted to be reloaded //using a different config. if (mod.events.defined) { undefEvents[id] = mod.events; } cleanRegistry(id); } }; } return localRequire; }, /** * Called to enable a module if it is still in the registry * awaiting enablement. A second arg, parent, the parent module, * is passed in for context, when this method is overriden by * the optimizer. Not shown here to keep code compact. */ enable: function (depMap) { var mod = getOwn(registry, depMap.id); if (mod) { getModule(depMap).enable(); } }, /** * Internal method used by environment adapters to complete a load event. * A load event could be a script load or just a load pass from a synchronous * load call. * @param {String} moduleName the name of the module to potentially complete. */ completeLoad: function (moduleName) { var found, args, mod, shim = getOwn(config.shim, moduleName) || {}, shExports = shim.exports; takeGlobalQueue(); while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { args[0] = moduleName; //If already found an anonymous module and bound it //to this name, then this is some other anon module //waiting for its completeLoad to fire. if (found) { break; } found = true; } else if (args[0] === moduleName) { //Found matching define call for this script! found = true; } callGetModule(args); } //Do this after the cycle of callGetModule in case the result //of those calls/init calls changes the registry. mod = getOwn(registry, moduleName); if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { if (hasPathFallback(moduleName)) { return; } else { return onError(makeError('nodefine', 'No define call for ' + moduleName, null, [moduleName])); } } else { //A script that does not call define(), so just simulate //the call for it. callGetModule([moduleName, (shim.deps || []), shim.exportsFn]); } } checkLoaded(); }, /** * Converts a module name to a file path. Supports cases where * moduleName may actually be just an URL. * Note that it **does not** call normalize on the moduleName, * it is assumed to have already been normalized. This is an * internal API, not a public one. Use toUrl for the public API. */ nameToUrl: function (moduleName, ext, skipExt) { var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url, parentPath; //If a colon is in the URL, it indicates a protocol is used and it is just //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) //or ends with .js, then assume the user meant to use an url and not a module id. //The slash is important for protocol-less URLs as well as full paths. if (req.jsExtRegExp.test(moduleName)) { //Just a plain path, not module name lookup, so just return it. //Add extension if it is included. This is a bit wonky, only non-.js things pass //an extension, this method probably needs to be reworked. url = moduleName + (ext || ''); } else { //A module that needs to be converted to a path. paths = config.paths; pkgs = config.pkgs; syms = moduleName.split('/'); //For each module name segment, see if there is a path //registered for it. Start with most specific name //and work up from it. for (i = syms.length; i > 0; i -= 1) { parentModule = syms.slice(0, i).join('/'); pkg = getOwn(pkgs, parentModule); parentPath = getOwn(paths, parentModule); if (parentPath) { //If an array, it means there are a few choices, //Choose the one that is desired if (isArray(parentPath)) { parentPath = parentPath[0]; } syms.splice(0, i, parentPath); break; } else if (pkg) { //If module name is just the package name, then looking //for the main module. if (moduleName === pkg.name) { pkgPath = pkg.location + '/' + pkg.main; } else { pkgPath = pkg.location; } syms.splice(0, i, pkgPath); break; } } //Join the path parts together, then figure out if baseUrl is needed. url = syms.join('/'); url += (ext || (/\?/.test(url) || skipExt ? '' : '.js')); url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; } return config.urlArgs ? url + ((url.indexOf('?') === -1 ? '?' : '&') + config.urlArgs) : url; }, //Delegates to req.load. Broken out as a separate function to //allow overriding in the optimizer. load: function (id, url) { req.load(context, id, url); }, /** * Executes a module callack function. Broken out as a separate function * solely to allow the build system to sequence the files in the built * layer in the right sequence. * * @private */ execCb: function (name, callback, args, exports) { return callback.apply(exports, args); }, /** * callback for script loads, used to check status of loading. * * @param {Event} evt the event from the browser for the script * that was loaded. */ onScriptLoad: function (evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. if (evt.type === 'load' || (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) { //Reset interactive script so a script node is not held onto for //to long. interactiveScript = null; //Pull out the name of the module and the context. var data = getScriptData(evt); context.completeLoad(data.id); } }, /** * Callback for script errors. */ onScriptError: function (evt) { var data = getScriptData(evt); if (!hasPathFallback(data.id)) { return onError(makeError('scripterror', 'Script error', evt, [data.id])); } } }; context.require = context.makeRequire(); return context; }
Constructs an error with a pointer to an URL with more information. @param {String} id the error ID that maps to an ID on a web page. @param {String} message human readable error. @param {Error} [err] the original error, if there is one. @returns {Error}
newContext
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function trimDots(ary) { var i, part; for (i = 0; ary[i]; i += 1) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } }
Trims the . and .. from an array of path segments. It will keep a leading path segment if a .. will become the first path segment, to help with module name lookups, which act like paths, but can be remapped. But the end result, all paths that use this function should look normalized. NOTE: this method MODIFIES the input array. @param {Array} ary the array of path segments.
trimDots
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function normalize(name, baseName, applyMap) { var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment, foundMap, foundI, foundStarMap, starI, baseParts = baseName && baseName.split('/'), normalizedBaseParts = baseParts, map = config.map, starMap = map && map['*']; //Adjust any relative paths. if (name && name.charAt(0) === '.') { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { if (getOwn(config.pkgs, baseName)) { //If the baseName is a package name, then just treat it as one //name to concat the name with. normalizedBaseParts = baseParts = [baseName]; } else { //Convert baseName to array, and lop off the last part, //so that . matches that 'directory' and not name of the baseName's //module. For instance, baseName of 'one/two/three', maps to //'one/two/three.js', but we want the directory, 'one/two' for //this normalization. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); } name = normalizedBaseParts.concat(name.split('/')); trimDots(name); //Some use of packages may use a . path to reference the //'main' module name, so normalize for that. pkgConfig = getOwn(config.pkgs, (pkgName = name[0])); name = name.join('/'); if (pkgConfig && name === pkgName + '/' + pkgConfig.main) { name = pkgName; } } else if (name.indexOf('./') === 0) { // No baseName, so this is ID is resolved relative // to baseUrl, pull off the leading dot. name = name.substring(2); } } //Apply map config if available. if (applyMap && map && (baseParts || starMap)) { nameParts = name.split('/'); for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join('/'); if (baseParts) { //Find the longest baseName segment match in the config. //So, do joins on the biggest to smallest lengths of baseParts. for (j = baseParts.length; j > 0; j -= 1) { mapValue = getOwn(map, baseParts.slice(0, j).join('/')); //baseName segment has config, find if it has one for //this name. if (mapValue) { mapValue = getOwn(mapValue, nameSegment); if (mapValue) { //Match, update name to the new value. foundMap = mapValue; foundI = i; break; } } } } if (foundMap) { break; } //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { foundStarMap = getOwn(starMap, nameSegment); starI = i; } } if (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } return name; }
Given a relative module name, like ./something, normalize it to a real name that can be mapped to a path. @param {String} name the relative name @param {String} baseName a real name that the name arg is relative to. @param {Boolean} applyMap apply the map config to the value. Should only be done if this normalization is for a dependency ID. @returns {String} normalized name
normalize
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function removeScript(name) { if (isBrowser) { each(scripts(), function (scriptNode) { if (scriptNode.getAttribute('data-requiremodule') === name && scriptNode.getAttribute('data-requirecontext') === context.contextName) { scriptNode.parentNode.removeChild(scriptNode); return true; } }); } }
Given a relative module name, like ./something, normalize it to a real name that can be mapped to a path. @param {String} name the relative name @param {String} baseName a real name that the name arg is relative to. @param {Boolean} applyMap apply the map config to the value. Should only be done if this normalization is for a dependency ID. @returns {String} normalized name
removeScript
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function hasPathFallback(id) { var pathConfig = getOwn(config.paths, id); if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { removeScript(id); //Pop off the first array value, since it failed, and //retry pathConfig.shift(); context.require.undef(id); context.require([id]); return true; } }
Given a relative module name, like ./something, normalize it to a real name that can be mapped to a path. @param {String} name the relative name @param {String} baseName a real name that the name arg is relative to. @param {Boolean} applyMap apply the map config to the value. Should only be done if this normalization is for a dependency ID. @returns {String} normalized name
hasPathFallback
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function splitPrefix(name) { var prefix, index = name ? name.indexOf('!') : -1; if (index > -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } return [prefix, name]; }
Given a relative module name, like ./something, normalize it to a real name that can be mapped to a path. @param {String} name the relative name @param {String} baseName a real name that the name arg is relative to. @param {Boolean} applyMap apply the map config to the value. Should only be done if this normalization is for a dependency ID. @returns {String} normalized name
splitPrefix
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { var url, pluginModule, suffix, nameParts, prefix = null, parentName = parentModuleMap ? parentModuleMap.name : null, originalName = name, isDefine = true, normalizedName = ''; //If no name, then it means it is a require call, generate an //internal name. if (!name) { isDefine = false; name = '_@r' + (requireCounter += 1); } nameParts = splitPrefix(name); prefix = nameParts[0]; name = nameParts[1]; if (prefix) { prefix = normalize(prefix, parentName, applyMap); pluginModule = getOwn(defined, prefix); } //Account for relative paths if there is a base name. if (name) { if (prefix) { if (pluginModule && pluginModule.normalize) { //Plugin is loaded, use its normalize method. normalizedName = pluginModule.normalize(name, function (name) { return normalize(name, parentName, applyMap); }); } else { normalizedName = normalize(name, parentName, applyMap); } } else { //A regular module. normalizedName = normalize(name, parentName, applyMap); //Normalized name may be a plugin ID due to map config //application in normalize. The map config values must //already be normalized, so do not need to redo that part. nameParts = splitPrefix(normalizedName); prefix = nameParts[0]; normalizedName = nameParts[1]; isNormalized = true; url = context.nameToUrl(normalizedName); } } //If the id is a plugin id that cannot be determined if it needs //normalization, stamp it with a unique ID so two matching relative //ids that may conflict can be separate. suffix = prefix && !pluginModule && !isNormalized ? '_unnormalized' + (unnormalizedCounter += 1) : ''; return { prefix: prefix, name: normalizedName, parentMap: parentModuleMap, unnormalized: !!suffix, url: url, originalName: originalName, isDefine: isDefine, id: (prefix ? prefix + '!' + normalizedName : normalizedName) + suffix }; }
Creates a module mapping that includes plugin prefix, module name, and path. If parentModuleMap is provided it will also normalize the name via require.normalize() @param {String} name the module name @param {String} [parentModuleMap] parent module map for the module name, used to resolve relative names. @param {Boolean} isNormalized: is the ID already normalized. This is true if this call is done for a define() module ID. @param {Boolean} applyMap: apply the map config to the ID. Should only be true if this map is for a dependency. @returns {Object}
makeModuleMap
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function getModule(depMap) { var id = depMap.id, mod = getOwn(registry, id); if (!mod) { mod = registry[id] = new context.Module(depMap); } return mod; }
Creates a module mapping that includes plugin prefix, module name, and path. If parentModuleMap is provided it will also normalize the name via require.normalize() @param {String} name the module name @param {String} [parentModuleMap] parent module map for the module name, used to resolve relative names. @param {Boolean} isNormalized: is the ID already normalized. This is true if this call is done for a define() module ID. @param {Boolean} applyMap: apply the map config to the ID. Should only be true if this map is for a dependency. @returns {Object}
getModule
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function on(depMap, name, fn) { var id = depMap.id, mod = getOwn(registry, id); if (hasProp(defined, id) && (!mod || mod.defineEmitComplete)) { if (name === 'defined') { fn(defined[id]); } } else { getModule(depMap).on(name, fn); } }
Creates a module mapping that includes plugin prefix, module name, and path. If parentModuleMap is provided it will also normalize the name via require.normalize() @param {String} name the module name @param {String} [parentModuleMap] parent module map for the module name, used to resolve relative names. @param {Boolean} isNormalized: is the ID already normalized. This is true if this call is done for a define() module ID. @param {Boolean} applyMap: apply the map config to the ID. Should only be true if this map is for a dependency. @returns {Object}
on
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function onError(err, errback) { var ids = err.requireModules, notified = false; if (errback) { errback(err); } else { each(ids, function (id) { var mod = getOwn(registry, id); if (mod) { //Set error on module, so it skips timeout checks. mod.error = err; if (mod.events.error) { notified = true; mod.emit('error', err); } } }); if (!notified) { req.onError(err); } } }
Creates a module mapping that includes plugin prefix, module name, and path. If parentModuleMap is provided it will also normalize the name via require.normalize() @param {String} name the module name @param {String} [parentModuleMap] parent module map for the module name, used to resolve relative names. @param {Boolean} isNormalized: is the ID already normalized. This is true if this call is done for a define() module ID. @param {Boolean} applyMap: apply the map config to the ID. Should only be true if this map is for a dependency. @returns {Object}
onError
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function takeGlobalQueue() { //Push all the globalDefQueue items into the context's defQueue if (globalDefQueue.length) { //Array splice in the values since the context code has a //local var ref to defQueue, so cannot just reassign the one //on context. apsp.apply(defQueue, [defQueue.length - 1, 0].concat(globalDefQueue)); globalDefQueue = []; } }
Internal method to transfer globalQueue items to this context's defQueue.
takeGlobalQueue
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function cleanRegistry(id) { //Clean up machinery used for waiting modules. delete registry[id]; delete enabledRegistry[id]; }
Internal method to transfer globalQueue items to this context's defQueue.
cleanRegistry
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function breakCycle(mod, traced, processed) { var id = mod.map.id; if (mod.error) { mod.emit('error', mod.error); } else { traced[id] = true; each(mod.depMaps, function (depMap, i) { var depId = depMap.id, dep = getOwn(registry, depId); //Only force things that have not completed //being defined, so still in the registry, //and only if it has not been matched up //in the module already. if (dep && !mod.depMatched[i] && !processed[depId]) { if (getOwn(traced, depId)) { mod.defineDep(i, defined[depId]); mod.check(); //pass false? } else { breakCycle(dep, traced, processed); } } }); processed[id] = true; } }
Internal method to transfer globalQueue items to this context's defQueue.
breakCycle
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function checkLoaded() { var map, modId, err, usingPathFallback, waitInterval = config.waitSeconds * 1000, //It is possible to disable the wait interval by using waitSeconds of 0. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), noLoads = [], reqCalls = [], stillLoading = false, needCycleCheck = true; //Do not bother if this call was a result of a cycle break. if (inCheckLoaded) { return; } inCheckLoaded = true; //Figure out the state of all the modules. eachProp(enabledRegistry, function (mod) { map = mod.map; modId = map.id; //Skip things that are not enabled or in error state. if (!mod.enabled) { return; } if (!map.isDefine) { reqCalls.push(mod); } if (!mod.error) { //If the module should be executed, and it has not //been inited and time is up, remember it. if (!mod.inited && expired) { if (hasPathFallback(modId)) { usingPathFallback = true; stillLoading = true; } else { noLoads.push(modId); removeScript(modId); } } else if (!mod.inited && mod.fetched && map.isDefine) { stillLoading = true; if (!map.prefix) { //No reason to keep looking for unfinished //loading. If the only stillLoading is a //plugin resource though, keep going, //because it may be that a plugin resource //is waiting on a non-plugin cycle. return (needCycleCheck = false); } } } }); if (expired && noLoads.length) { //If wait time expired, throw error of unloaded modules. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); err.contextName = context.contextName; return onError(err); } //Not expired, check for a cycle. if (needCycleCheck) { each(reqCalls, function (mod) { breakCycle(mod, {}, {}); }); } //If still waiting on loads, and the waiting load is something //other than a plugin resource, or there are still outstanding //scripts, then just try back later. if ((!expired || usingPathFallback) && stillLoading) { //Something is still waiting to load. Wait for it, but only //if a timeout is not already in effect. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { checkLoadedTimeoutId = setTimeout(function () { checkLoadedTimeoutId = 0; checkLoaded(); }, 50); } } inCheckLoaded = false; }
Internal method to transfer globalQueue items to this context's defQueue.
checkLoaded
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function callGetModule(args) { //Skip modules already defined. if (!hasProp(defined, args[0])) { getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); } }
Checks if the module is ready to define itself, and if so, define it.
callGetModule
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function removeListener(node, func, name, ieName) { //Favor detachEvent because of IE9 //issue, see attachEvent/addEventListener comment elsewhere //in this file. if (node.detachEvent && !isOpera) { //Probably IE. If not it will throw an error, which will be //useful to know. if (ieName) { node.detachEvent(ieName, func); } } else { node.removeEventListener(name, func, false); } }
Checks if the module is ready to define itself, and if so, define it.
removeListener
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function getScriptData(evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. var node = evt.currentTarget || evt.srcElement; //Remove the listeners once here. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); removeListener(node, context.onScriptError, 'error'); return { node: node, id: node && node.getAttribute('data-requiremodule') }; }
Given an event from a script node, get the requirejs info from it, and then removes the event listeners on the node. @param {Event} evt @returns {Object}
getScriptData
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function intakeDefines() { var args; //Any defined modules in the global queue, intake them now. takeGlobalQueue(); //Make sure any remaining defQueue items get properly processed. while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1])); } else { //args are id, deps, factory. Should be normalized by the //define() function. callGetModule(args); } } }
Given an event from a script node, get the requirejs info from it, and then removes the event listeners on the node. @param {Event} evt @returns {Object}
intakeDefines
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function fn() { var ret; if (value.init) { ret = value.init.apply(global, arguments); } return ret || (value.exports && getGlobal(value.exports)); }
Set a configuration for the context. @param {Object} cfg config object to integrate.
fn
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function localRequire(deps, callback, errback) { var id, map, requireMod; if (options.enableBuildCallback && callback && isFunction(callback)) { callback.__requireJsBuild = true; } if (typeof deps === 'string') { if (isFunction(callback)) { //Invalid call return onError(makeError('requireargs', 'Invalid require call'), errback); } //If require|exports|module are requested, get the //value for them from the special handlers. Caveat: //this only works while module is being defined. if (relMap && hasProp(handlers, deps)) { return handlers[deps](registry[relMap.id]); } //Synchronous access to one module. If require.get is //available (as in the Node adapter), prefer that. if (req.get) { return req.get(context, deps, relMap, localRequire); } //Normalize module name, if it contains . or .. map = makeModuleMap(deps, relMap, false, true); id = map.id; if (!hasProp(defined, id)) { return onError(makeError('notloaded', 'Module name "' + id + '" has not been loaded yet for context: ' + contextName + (relMap ? '' : '. Use require([])'))); } return defined[id]; } //Grab defines waiting in the global queue. intakeDefines(); //Mark all the dependencies as needing to be loaded. context.nextTick(function () { //Some defines could have been added since the //require call, collect them. intakeDefines(); requireMod = getModule(makeModuleMap(null, relMap)); //Store if map config should be applied to this require //call for dependencies. requireMod.skipMap = options.skipMap; requireMod.init(deps, callback, errback, { enabled: true }); checkLoaded(); }); return localRequire; }
Set a configuration for the context. @param {Object} cfg config object to integrate.
localRequire
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function getInteractiveScript() { if (interactiveScript && interactiveScript.readyState === 'interactive') { return interactiveScript; } eachReverse(scripts(), function (script) { if (script.readyState === 'interactive') { return (interactiveScript = script); } }); return interactiveScript; }
Does the request to load a module for the browser case. Make this a separate function to allow other environments to override it. @param {Object} context the require context to find state. @param {String} moduleName the name of the module. @param {Object} url the URL to the module.
getInteractiveScript
javascript
localForage/localForage
examples/require.js
https://github.com/localForage/localForage/blob/master/examples/require.js
Apache-2.0
function _init(stream) { stream.setMaxListeners(0); return stream; }
/*.js') .pipe(babel({ presets: ['es2015'], ignore: 'src/ui/vendor/*' })) .pipe(gulp.dest(appConfig.buildPath)); }); /* ------------------------------------------------ Sym Links ------------------------------------------------
_init
javascript
officert/mongotron
gulpfile.js
https://github.com/officert/mongotron/blob/master/gulpfile.js
MIT
function unlink(symlink, next) { fs.lstat(symlink, (lerr, lstat) => { if (lerr || !lstat.isSymbolicLink()) { return next(); } fs.unlink(symlink, () => { return next(); }); }); }
/*.js') .pipe(babel({ presets: ['es2015'], ignore: 'src/ui/vendor/*' })) .pipe(gulp.dest(appConfig.buildPath)); }); /* ------------------------------------------------ Sym Links ------------------------------------------------
unlink
javascript
officert/mongotron
gulpfile.js
https://github.com/officert/mongotron/blob/master/gulpfile.js
MIT
constructor(database, options) { if (!(database instanceof MongoDb)) console.error('Collection ctor - database is not an instance of MongoDb'); options = options || {}; var _this = this; _this.id = options.id; _this.name = options.name; _this.connection = options.connection; _this.database = options.database; _this.serverName = options.serverName; _this.databaseName = options.databaseName; _this._dbCollection = database.collection(_this.name); }
@param {Object} database - MongoDb object @param {Object} options @param {String} options.name - name of the collection @param {String} options.serverName - name of the server @param {String} options.databaseName - name of the database
constructor
javascript
officert/mongotron
src/lib/entities/collection.js
https://github.com/officert/mongotron/blob/master/src/lib/entities/collection.js
MIT
find(query, options) { options = options || {}; let cursor = this._dbCollection.find(query, options); if (options.skip) cursor.skip(Number(options.skip)); cursor.limit(options.limit ? Number(options.limit) : DEFAULT_PAGE_SIZE); return new MongotronCursor(cursor); }
@param {Object} [query] - mongo query @param {Object} [options] - mongo query options
find
javascript
officert/mongotron
src/lib/entities/collection.js
https://github.com/officert/mongotron/blob/master/src/lib/entities/collection.js
MIT
count(query, options) { query = query || {}; options = options || {}; return this._dbCollection.count(query, options); }
@param {Object} query - mongo query @param {Object} [options] - mongo query options
count
javascript
officert/mongotron
src/lib/entities/collection.js
https://github.com/officert/mongotron/blob/master/src/lib/entities/collection.js
MIT
deleteMany(query, options) { return new Promise((resolve, reject) => { query = query || {}; options = options || {}; this._dbCollection.deleteMany(query, options, (err, result) => { if (err) return reject(err); return resolve(result); }); }); }
@param {Object} query - mongo query @param {Object} [options] - mongo query options
deleteMany
javascript
officert/mongotron
src/lib/entities/collection.js
https://github.com/officert/mongotron/blob/master/src/lib/entities/collection.js
MIT
distinct(field, query) { if (!field) return Promise.reject(new errors.InvalidArugmentError('field is required')); query = query || {}; return Promise.fromCallback(callback => { this._dbCollection.distinct(field, query, callback); }); }
@param {String} field - mongo field, including dot-notated fields @param {Object} [query] - mongo query
distinct
javascript
officert/mongotron
src/lib/entities/collection.js
https://github.com/officert/mongotron/blob/master/src/lib/entities/collection.js
MIT
aggregate(pipeline, options) { if (!_.isArray(pipeline)) return Promise.reject('pipeline must be an array'); options = options || {}; let stream = options.stream; delete options.stream; //always return as a cursor options.cursor = {}; let cursor = this._dbCollection.aggregate(pipeline, options); if (options.skip) cursor.skip(Number(options.skip)); cursor.limit(options.limit ? Number(options.limit) : DEFAULT_PAGE_SIZE); if (stream === true) { cursor.stream(); } return new MongotronCursor(cursor); }
@param {Object} [pipeline] - mongo pipeline @param {Object} [options] - mongo pipeline options
aggregate
javascript
officert/mongotron
src/lib/entities/collection.js
https://github.com/officert/mongotron/blob/master/src/lib/entities/collection.js
MIT
updateMany(query, updates, options) { return new Promise((resolve, reject) => { if (!query) return reject(new errors.InvalidArugmentError('query is required')); if (!updates) return reject(new errors.InvalidArugmentError('updates is required')); options = options || {}; this._dbCollection.updateMany(query, updates, (err, result) => { if (err) return reject(err); return resolve(result); }); }); }
@param {Object} query - mongo query @param {Object} updates - updates to apply @param {Object} [options] - mongo query options
updateMany
javascript
officert/mongotron
src/lib/entities/collection.js
https://github.com/officert/mongotron/blob/master/src/lib/entities/collection.js
MIT
updateById(objectId, updates, options) { return new Promise((resolve, reject) => { if (!objectId) return reject(new errors.InvalidArugmentError('objectId is required')); if (!updates) return reject(new errors.InvalidArugmentError('updates is required')); options = options || {}; this._dbCollection.updateOne({ _id: objectId }, updates, (err, result) => { if (err) return reject(err); return resolve(result); }); }); }
@param {Object} Mongo ObjectId @param {Object} updates - updates to apply @param {Object} [options] - mongo query options
updateById
javascript
officert/mongotron
src/lib/entities/collection.js
https://github.com/officert/mongotron/blob/master/src/lib/entities/collection.js
MIT
updateOne(query, updates, options) { return new Promise((resolve, reject) => { if (!query) return reject(new errors.InvalidArugmentError('query is required')); if (!updates) return reject(new errors.InvalidArugmentError('updates is required')); options = options || {}; this._dbCollection.updateOne(query, updates, (err, result) => { if (err) return reject(err); return resolve(result); }); }); }
@param {Object} query - mongo query @param {Object} updates - updates to apply @param {Object} [options] - mongo query options
updateOne
javascript
officert/mongotron
src/lib/entities/collection.js
https://github.com/officert/mongotron/blob/master/src/lib/entities/collection.js
MIT
constructor(options) { options = options || {}; var _this = this; _this.id = options.id; _this.name = options.name; _this.host = options.host; _this.port = options.port; _this.replicaSet = options.replicaSet; _this.databases = []; if (options.databaseName && !mongoUtils.isLocalHost(options.host)) { let newDb = { id: uuid.v4(), name: options.databaseName, host: options.host, port: options.port, auth: options.auth }; if (options.auth && (options.auth.username || options.auth.password)) { newDb.auth = {}; newDb.auth.username = options.auth.username; newDb.auth.password = options.auth.password; } _this.addDatabase(newDb); } }
@param {Object} options @param {String} options.name @param {String} [options.host] @param {String} [options.port] @param {Object} [options.replicaSet] @param {String} [options.replicaSet.name] @param {Array<Object>} [options.replicaSet.servers]
constructor
javascript
officert/mongotron
src/lib/entities/connection.js
https://github.com/officert/mongotron/blob/master/src/lib/entities/connection.js
MIT
get connectionString() { if (!this._connectionString) { this._connectionString = _getConnectionString(this); } return this._connectionString; }
@param {Object} options @param {String} options.name @param {String} [options.host] @param {String} [options.port] @param {Object} [options.replicaSet] @param {String} [options.replicaSet.name] @param {Array<Object>} [options.replicaSet.servers]
connectionString
javascript
officert/mongotron
src/lib/entities/connection.js
https://github.com/officert/mongotron/blob/master/src/lib/entities/connection.js
MIT
addDatabase(options) { options = options || {}; let existingDatabase = _.findWhere(this.databases, { name: options.name }); if (existingDatabase) return; let database = new Database({ id: options.id, name: options.name, host: options.host, port: options.port, auth: options.auth, connection: this }); this.databases.push(database); return database; }
Add a new database to the connection @param {Object} options @param {String} options.name
addDatabase
javascript
officert/mongotron
src/lib/entities/connection.js
https://github.com/officert/mongotron/blob/master/src/lib/entities/connection.js
MIT
createDatabase(options) { options = options || {}; return new Promise((resolve, reject) => { if (!options) return reject(new Error('options is required')); if (!options.name) return reject(new Error('options.name is required')); let client = new MongoClient(); client.connect(this.connectionString, (err, database) => { if (err) return reject(err); database.db(options.name); let newDatabase = this.addDatabase({ name: options.name, host: this.host, port: this.port, auth: this.auth }); return resolve(newDatabase); }); }); }
Create a new database @param {Object} options @param {String} options.name @return Promise
createDatabase
javascript
officert/mongotron
src/lib/entities/connection.js
https://github.com/officert/mongotron/blob/master/src/lib/entities/connection.js
MIT
function _getDbsForLocalhostConnection(connection, next) { if (!connection) return next(new Error('connection is required')); if (!next) return next(new Error('next is required')); if (!mongoUtils.isLocalHost(connection.host)) return next(new Error('cannot get local dbs for non localhost connection')); var localDb = new MongoDb('local', new MongoServer(connection.host, connection.port)); localDb.open(function(err, db) { if (err) return next(new errors.ConnectionError(util.format('An error occured when trying to connect to %s', connection.host))); // Use the admin database for the operation var adminDb = db.admin(); // List all the available databases adminDb.listDatabases((err, result) => { if (err) return next(new errors.DatabaseError(err)); db.close(); _.each(result.databases, (db) => { connection.addDatabase({ name: db.name, host: connection.host, port: connection.port }); }); return next(null); }); }); }
@function _getDbsForLocalhostConnection @param {Function} next - callback function @private
_getDbsForLocalhostConnection
javascript
officert/mongotron
src/lib/entities/connection.js
https://github.com/officert/mongotron/blob/master/src/lib/entities/connection.js
MIT
constructor(options) { options = options || {}; this.id = options.id; this.name = options.name; //TODO: validate name doesn't contain spaces this.host = options.host; this.port = options.port; this.auth = options.auth; this.connection = options.connection; this.collections = []; if (mongoUtils.isLocalHost(this.host)) { this._dbConnection = new MongoDb(this.name, new MongoServer(this.host, this.port)); } else { this._dbConnection = null; //this is set by the parent connection once we've connect to it } }
@param {Object} options @param {String} options.name - name of the database @param {String} options.host - host of the database, defaults to localhost @param {String} options.port - port of the database, defaults to 27017 @param {Object} options.auth - database auth info @param {String} options.auth.username - database auth username @param {String} options.auth.password - database auth password
constructor
javascript
officert/mongotron
src/lib/entities/database.js
https://github.com/officert/mongotron/blob/master/src/lib/entities/database.js
MIT
findById(id) { let _this = this; return new Promise((resolve, reject) => { if (!id) return reject(new errors.InvalidArugmentError('id is required')); return _this.list() .then((connections) => { return findConnectionById(id, connections); }) .then(resolve) .catch(reject); }); }
Find a connection by id @param {string} id - Id of the connection to find
findById
javascript
officert/mongotron
src/lib/modules/connection/repository.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js
MIT
create(options) { let _this = this; return new Promise((resolve, reject) => { if (!options) return reject(new errors.InternalServiceError('options is required')); let connections; let newConnection; options.id = uuid.v4(); //assign a "unique" id return _this.list() .then((_connections) => { connections = _connections; return createConnection(options, _connections); }) .then((_connection) => { newConnection = _connection; connections.push(newConnection); return convertConnectionInstancesIntoConfig(connections); }) .then(writeConfigFile) .then(() => { return new Promise((resolve1) => { return resolve1(newConnection); }); }) .then(resolve) .catch(reject); }); }
Create a new connection @param {object} options @param {string} options.name - Connection name @param {string} options.host - Connection host @param {string} options.port - Connection port @param {string} [options.databaseName] - Database name @param {object} [options.replicaSet] - Replica set config @param {string} options.replicaSet.name - Replica set name @param {array<object>} options.replicaSet.servers - Replica set servers @param {object} [options.auth]
create
javascript
officert/mongotron
src/lib/modules/connection/repository.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js
MIT
update(id, updatedConnection) { let _this = this; let connections; return new Promise((resolve, reject) => { if (!id) return reject(new errors.InvalidArugmentError('id is required')); if (!updatedConnection) return reject(new errors.InvalidArugmentError('updatedConnection is required')); return _this.list() .then((_connections) => { connections = _connections; return findConnectionById(id, connections); }) .then((connection) => { return updateConnection(connection, updatedConnection, connections); }) .then(convertConnectionInstancesIntoConfig) .then(writeConfigFile) .then(() => { return resolve(updatedConnection); }) .catch(reject); }); }
Update a connection by id @param {string} id - id of the connection to update @param {object} updates - hash of updates to apply to the connection @param {string} [updates.name] - connection name @param {string} [updates.host] - Connection host @param {string} [updates.port ]- Connection port @param {string} [updates.databaseName] - Database name @param {object} [updates.replicaSet] - Replica set config @param {string} [updates.replicaSet.name] - Replica set name @param {array<object>} [updates.replicaSet.servers] - Replica set servers @param {object} [updates.auth]
update
javascript
officert/mongotron
src/lib/modules/connection/repository.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js
MIT
delete(id) { var _this = this; return new Promise((resolve, reject) => { if (!id) return reject(new errors.InvalidArugmentError('id is required')); return _this.list() .then((connections) => { return findConnectionById(id, connections) .then(function(connection) { return removeConnection(connection, connections); }); }) .then(convertConnectionInstancesIntoConfig) .then(writeConfigFile) .then(() => { return resolve(null); }) .catch(reject); }); }
Delete a connection by id @param {string} id - id of the connection to delete
delete
javascript
officert/mongotron
src/lib/modules/connection/repository.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js
MIT
existsByName(name) { var _this = this; return _this.list() .then((connections) => { return new Promise((resolve) => { var existingConnection = _.findWhere(connections, { name: name }); return resolve(existingConnection ? true : false); }); }); }
Check if a connection exists by name @param {String} name
existsByName
javascript
officert/mongotron
src/lib/modules/connection/repository.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js
MIT
function readConfigFile() { return fileUtils.readJsonFile(DB_CONNECTIONS); }
Check if a connection exists by name @param {String} name
readConfigFile
javascript
officert/mongotron
src/lib/modules/connection/repository.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js
MIT
function writeConfigFile(data) { return fileUtils.writeJsonFile(DB_CONNECTIONS, data); }
Check if a connection exists by name @param {String} name
writeConfigFile
javascript
officert/mongotron
src/lib/modules/connection/repository.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js
MIT
function getConnectionInstances() { return readConfigFile() .then((connectionConfigs) => { return new Promise((resolve) => { return resolve(connectionConfigs && connectionConfigs.length ? connectionConfigs.map(generateConnectionInstanceFromConfig) : []); }); }); }
Check if a connection exists by name @param {String} name
getConnectionInstances
javascript
officert/mongotron
src/lib/modules/connection/repository.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js
MIT
function generateConnectionInstanceFromConfig(connectionConfig) { var newConn = new Connection({ id: connectionConfig.id || uuid.v4(), name: connectionConfig.name, host: connectionConfig.host, port: connectionConfig.port, replicaSet: connectionConfig.replicaSet }); _.each(connectionConfig.databases, (databaseConfig) => { newConn.addDatabase({ id: databaseConfig.id || uuid.v4(), name: databaseConfig.name, host: connectionConfig.host, port: connectionConfig.port, auth: databaseConfig.auth }); }); return newConn; }
Check if a connection exists by name @param {String} name
generateConnectionInstanceFromConfig
javascript
officert/mongotron
src/lib/modules/connection/repository.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js
MIT
function convertConnectionInstancesIntoConfig(connections) { return new Promise((resolve) => { let configs = connections.map(convertConnectionInstanceIntoConfig); return resolve(configs); }); }
Check if a connection exists by name @param {String} name
convertConnectionInstancesIntoConfig
javascript
officert/mongotron
src/lib/modules/connection/repository.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js
MIT
function convertConnectionInstanceIntoConfig(connection) { //unique id's are added to the entities to emulate //storing them in a real database that would assign unique ids //the app relies on the various entities to have unique ids so //until I change to storing these in something that assigns ids //we have to manually add them let config = { id: connection.id || uuid.v4(), name: connection.name, host: connection.host, port: connection.port, replicaSet: connection.replicaSet, databases: connection.databases ? connection.databases.map((database) => { var db = { id: database.id || uuid.v4(), name: database.name }; if (database.auth) { db.auth = { username: database.auth.username, password: database.auth.password }; } return db; }) : [] }; return config; }
Check if a connection exists by name @param {String} name
convertConnectionInstanceIntoConfig
javascript
officert/mongotron
src/lib/modules/connection/repository.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js
MIT
function findConnectionById(connectionId, connections) { return new Promise((resolve, reject) => { var foundConnection = _.findWhere(connections, { id: connectionId }); if (foundConnection) { return resolve(foundConnection); } else { return reject(new errors.ObjectNotFoundError('Connection not found')); } }); }
Check if a connection exists by name @param {String} name
findConnectionById
javascript
officert/mongotron
src/lib/modules/connection/repository.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js
MIT
function createConnection(options) { return new Promise((resolve) => { var newConn = new Connection(options); return resolve(newConn); }); }
Check if a connection exists by name @param {String} name
createConnection
javascript
officert/mongotron
src/lib/modules/connection/repository.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js
MIT
function removeConnection(connection, connections) { return new Promise((resolve) => { var index = connections.indexOf(connection); connections.splice(index, 1); return resolve(connections); }); }
Check if a connection exists by name @param {String} name
removeConnection
javascript
officert/mongotron
src/lib/modules/connection/repository.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js
MIT
function updateConnection(originalConnection, updatedConnection, connections) { return new Promise((resolve) => { // connection = _.extend(connection, options); let index = connections.indexOf(originalConnection); connections.splice(index, 1, updatedConnection); return resolve(connections); }); }
Check if a connection exists by name @param {String} name
updateConnection
javascript
officert/mongotron
src/lib/modules/connection/repository.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js
MIT
findById(id) { return connectionRepository.findById(id); }
Find a connection by id @param {string} id - Id of the connection to find
findById
javascript
officert/mongotron
src/lib/modules/connection/service.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/service.js
MIT
create(options) { //map it to a new object so nothing unexpected can be passed in and saved let newConnection = { name: options.name, host: options.host, port: options.port, databaseName: options.databaseName, replicaSet: options.replicaSet, auth: options.auth }; return new Promise((resolve, reject) => { connectionValidator.validateCreate(newConnection) .then(() => { //TODO: move into validator so update runs it too return connectionRepository.existsByName(newConnection.name); }) .then((exists) => { return new Promise((resolve, reject) => { if (exists) return reject(new errors.InvalidArugmentError('Sorry, connection names must be unique')); return resolve(null); }); }) .then(() => { return connectionRepository.create(newConnection); }) .then(resolve) .catch(reject); }); }
Create a new connection @param {object} options @param {string} options.name - Connection name @param {string} options.host - Connection host @param {string} options.port - Connection port @param {string} [options.databaseName] - Database name @param {object} [options.replicaSet] - Replica set config @param {string} options.replicaSet.name - Replica set name @param {array<object>} options.replicaSet.servers - Replica set servers @param {object} [options.auth]
create
javascript
officert/mongotron
src/lib/modules/connection/service.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/service.js
MIT
update(id, updates) { let _this = this; return new Promise((resolve, reject) => { if (!id) return reject(new errors.InvalidArugmentError('id is required')); if (!updates) return reject(new errors.InvalidArugmentError('updates is required')); _this.findById(id) .then((connection) => { return _applyConnectionUpdatesPreValidation(connection, updates); }) .then(connectionValidator.validateUpdate) .then((connection) => { return _applyConnectionUpdatesPostValidation(connection, updates); }) .then((connection) => { connectionRepository.update(id, connection) .then(resolve) .catch(reject); }) .catch(reject); }); }
Update a connection by id @param {string} id - id of the connection to update @param {object} updates - hash of updates to apply to the connection @param {string} [updates.name] - connection name @param {string} [updates.host] - Connection host @param {string} [updates.port ]- Connection port @param {string} [updates.databaseName] - Database name @param {object} [updates.replicaSet] - Replica set config @param {string} [updates.replicaSet.name] - Replica set name @param {array<object>} [updates.replicaSet.servers] - Replica set servers @param {object} [updates.auth]
update
javascript
officert/mongotron
src/lib/modules/connection/service.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/service.js
MIT
delete(id) { return connectionRepository.delete(id); }
Delete a connection by id @param {string} id - id of the connection to delete
delete
javascript
officert/mongotron
src/lib/modules/connection/service.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/service.js
MIT
function _applyConnectionUpdatesPreValidation(connection, updates) { return new Promise((resolve) => { if ('name' in updates) connection.name = updates.name; if ('host' in updates) { connection.host = updates.host; delete connection.replicaSet; if (mongoUtils.isLocalHost(updates.host)) { delete connection.databases; } } if ('port' in updates) connection.port = updates.port; if ('databaseName' in updates) connection.databaseName = updates.databaseName; if ('auth' in updates) { if (!updates.auth) delete connection.auth; //null or undefined so remove it else if (connection.auth) { if ('username' in updates.auth) connection.auth.username = updates.auth.username; if ('password' in updates.auth) connection.auth.password = updates.auth.password; } else { connection.auth = updates.auth; } } if ('replicaSet' in updates) { if (!updates.replicaSet) delete connection.replicaSet; //null or undefined so remove it else if (connection.replicaSet) { delete connection.host; delete connection.port; if ('name' in updates.replicaSet) connection.replicaSet.name = updates.replicaSet.name; if ('servers' in updates.replicaSet) connection.replicaSet.servers = updates.replicaSet.servers; } else { connection.replicaSet = updates.replicaSet; } } if (!mongoUtils.isLocalHost(connection.host)) { let db = connection.databases && connection.databases.length ? connection.databases[0] : null; if (!db) logger.warn('connection service - _applyConnectionUpdates() - connection has no database'); else { if (!connection.databaseName) connection.databaseName = db.name; let auth = db.auth; if (connection.auth) { connection.auth.username = connection.auth.username || (auth ? auth.username : null); connection.auth.password = connection.auth.password || (auth ? auth.password : null); } } } return resolve(connection); }); }
Validate updates to a connection @param {Connection} connection - connection instance @param {object} updates - hash of updates to apply to validate @private
_applyConnectionUpdatesPreValidation
javascript
officert/mongotron
src/lib/modules/connection/service.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/service.js
MIT
function _applyConnectionUpdatesPostValidation(connection, updates) { return new Promise((resolve) => { let db = connection.databases && connection.databases.length ? connection.databases[0] : null; if (db) { if ('auth' in updates) { if (!updates.auth) { delete db.auth; } else { db.auth = db.auth || {}; db.auth.username = (updates.auth ? updates.auth.username : null) || db.auth.username; db.auth.password = (updates.auth ? updates.auth.password : null) || db.auth.password; } } if ('databaseName' in updates) { db.name = updates.databaseName; } if ('host' in updates) db.host = updates.host; if ('port' in updates) db.port = updates.port; } else { if ('host' in updates && !mongoUtils.isLocalHost(updates.host)) { connection.addDatabase({ host: updates.host, port: updates.port }); } } return resolve(connection); }); }
Validate updates to a connection @param {Connection} connection - connection instance @param {object} updates - hash of updates to apply to validate @private
_applyConnectionUpdatesPostValidation
javascript
officert/mongotron
src/lib/modules/connection/service.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/service.js
MIT
validateCreate(data) { return new Promise((resolve, reject) => { _baseValidate(data) .then(resolve) .catch(reject); }); }
Validate a connection for creating @param {object} data
validateCreate
javascript
officert/mongotron
src/lib/modules/connection/validator.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/validator.js
MIT
validateUpdate(data) { return new Promise((resolve, reject) => { _baseValidate(data) .then(resolve) .catch(reject); }); }
Validate a connection for updating @param {object} data
validateUpdate
javascript
officert/mongotron
src/lib/modules/connection/validator.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/validator.js
MIT
function _baseValidate(data) { return new Promise((resolve, reject) => { if (!data.name) return reject(new errors.InvalidArugmentError('connection.name is required')); if (data.replicaSet) { if (!data.replicaSet.name) return reject(new errors.InvalidArugmentError('data.replicaSet.name is required')); if (!data.replicaSet.servers || !data.replicaSet.servers.length) return reject(new errors.InvalidArugmentError('data.replicaSet.servers is required')); for (let i = 0; i < data.replicaSet.servers.length; i++) { let set = data.replicaSet.servers[i]; if (!set.host) return reject(new errors.InvalidArugmentError(`data.replicaSet.servers[${i}].host is required`)); if (!set.port) return reject(new errors.InvalidArugmentError(`data.replicaSet.servers[${i}].port is required`)); if (set.port < 0 || set.port > 65535) return reject(new errors.InvalidArugmentError(`data.replicaSet.servers[${i}].port number must be between 0 and 65535.`)); } } else { if (!data.host) return reject(new errors.InvalidArugmentError('data.host is required')); if (!data.port) return reject(new errors.InvalidArugmentError('data.port is required')); if (data.port && (data.port < 0 || data.port > 65535)) return reject(new errors.InvalidArugmentError('Port number must be between 0 and 65535.')); } if (data.auth) { if (!data.auth.username) return reject(new errors.InvalidArugmentError('auth.username is required')); if (!data.auth.password) return reject(new errors.InvalidArugmentError('auth.password is required')); } if (!mongoUtils.isLocalHost(data.host)) { if (!data.databaseName) return reject(new errors.InvalidArugmentError('database is required when connecting to a remote server.')); } return resolve(data); }); }
Validate a connection for updating @param {object} data
_baseValidate
javascript
officert/mongotron
src/lib/modules/connection/validator.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/validator.js
MIT