Construct Confluence.

@constructor
@this {Confluence}
@param {Object} config
@param {string} config.username
@param {string} config.password
@param {string} config.baseUrl
@param {number} config.version - Optional
332250
function Confluence(config) {
    if (!(this instanceof Confluence)) return new Confluence(config);

    if (!config) {
        throw new Error("Confluence module expects a config object.");
    }
    else if (!config.username || ! config.password) {
        throw new Error("Confluence module expects a config object with both a username and password.");
    }
    else if (!config.baseUrl) {
        throw new Error("Confluence module expects a config object with a baseUrl.");
    }

    this.config = config;

    this.config.apiPath = '/rest/api';
    this.config.extension = ''; // no extension by default

    if (this.config.version && this.config.version === 4) {
        this.config.apiPath = '/rest/prototype/latest';
        this.config.extension = '.json';
    }
}
1006157
function DiscogsOAuth(auth){
	this.config = util.merge({}, defaultConfig);
	this.auth = {method: 'oauth', level: 0};
	if(auth && (typeof auth === 'object') && (auth.method === 'oauth')){
		util.merge(this.auth, auth);
	}
}
122181
function initApp (config) {
    // init each module in the order loaded
    _.each(config.moduleNames, moduleName => {
        var module = config.modules[moduleName]
        // load modules and controllers for module, setup routes
        initModule(config, module)
        // merge module routes to global routes
        _.merge(config.routes, module.routes)
    })
    // initialize merged routes from all modules
    var router = initRoutes(config, config.routes)
    // bind router to app base
    config.express.use('/', router)
}
1164396
function setting(options) {
  var conf = {};

  if (options === null || typeof options !== 'object') {
    options = {};
  }

  for (var key in defaultSetting) {
    conf[key] = options[key] === undefined ? defaultSetting[key] : options[key];
  }

  conf.format = defaultFormat(['json', 'xml'].indexOf(conf.format.toLowerCase()));

  var prefix = conf.prefix;
  if ((typeof prefix === 'string' || util.isRegExp(prefix)) && !options.prefixPattern) {
    conf.prefixPattern = util.isRegExp(prefix) ? prefix : new RegExp(prefix);
  }

  if (conf.authenticate) {
    conf.deny = options.deny;
    conf.authenticatePattern = options.authenticatePattern || conf.prefixPattern;

    if (conf.authenticate.constructor.name !== 'GeneratorFunction') {
      console.error('authenticate should be a GeneratorFunction');
      conf.authenticate = false;
    }
    if (conf.deny.constructor.name !== 'GeneratorFunction') {
      console.error('deny should be a GeneratorFunction');
    }
  }

  return conf;
}
95007
function nodeGo(config) {
        // Create the node
        RED.nodes.createNode(this, config)

        /** @since 2019-02-02 - the current instance name (url) */
        var uibInstance = config.url // for logging

        log.verbose(`[${uibInstance}] ================ instance registered ================`)

        /** A copy of 'this' object in case we need it in context of callbacks of other functions. @constant {Object} node */
        const node = this

        log.verbose(`[${uibInstance}] = Keys: this, config =`, {'this': Object.keys(node), 'config': Object.keys(config)})

        //#region --- Create local copies of the node configuration (as defined in the .html file)
        // NB: node.id and node.type are also available
        node.name          = config.name || ''
        node.topic         = config.topic || ''
        // TODO: Needs validation as a suitable URL path
        node.url           = config.url  || 'uibuilder'
        node.fwdInMessages = config.fwdInMessages        // @since 2017-09-20 changed to remove default, || with boolean doesn't work properly
        node.allowScripts  = config.allowScripts
        node.allowStyles   = config.allowStyles
        node.debugFE       = config.debugFE
        node.copyIndex     = config.copyIndex
        node.filename      = config.filename
        node.format        = config.format
        node.template      = config.template
        //#endregion ----

        log.verbose(`[${uibInstance}] Node instance settings`, {'name': node.name, 'topic': node.topic, 'url': node.url, 'fwdIn': node.fwdInMessages, 'allowScripts': node.allowScripts, 'allowStyles': node.allowStyles, 'debugFE': node.debugFE })

        // Keep a log of the active instances @since 2019-02-02
        instances[node.id] = node.url
        log.verbose(`[${uibInstance}] Node Instances Registered`, instances)

        /** Name of the fs path used to hold custom files & folders for THIS INSTANCE of uibuilder
         *   Files in this folder are also served to URL but take preference
         *   over those in the nodes folders (which act as defaults) @type {string}
         */
        node.customFolder = path.join(uib_rootPath, node.url)

        /** User supplied vendor packages
         * & only if using dev folders (delete ~/.node-red/uibuilder/<url>/dist/index.html)
         * JK @since 2017-08-17 fix for non-existent properties and use getProps()
         * JK @since 2018-01-06 use uib_globalSettings instead of RED.settings.uibuilder. At least an empty array is returned.
         * @type {Array}
         */
        node.userVendorPackages = uiblib.getProps(RED,config,'userVendorPackages',null) || uiblib.getProps(RED,uib_globalSettings,'userVendorPackages',[])

        log.verbose(`[${uibInstance}] Node package details`, { 'usrVendorPkgs': node.userVendorPackages, 'customAppFldr': uib_rootPath, 'customFldr': node.customFolder } )

        //#region ---- Socket.IO instance configuration ----
        /** How many Socket clients connected to this instance? @type {integer} */
        node.ioClientsCount = 0
        /** How many msg's received since last reset or redeploy? @type {integer} */
        node.rcvMsgCount = 0
        /** The channel names for Socket.IO @type {Object} */
        node.ioChannels = {control: 'uiBuilderControl', client: 'uiBuilderClient', server: 'uiBuilder'}
        /** Make sure each node instance uses a separate Socket.IO namespace - WARNING: This HAS to match the one derived in uibuilderfe.js
         * @since v1.0.10, changed namespace creation to correct a missing / if httpNodeRoot had been changed from the default. @type {string} */
        node.ioNamespace = tilib.urlJoin(httpNodeRoot, node.url)
        //#endregion ---- ----

        log.verbose(`[${uibInstance}] Socket.io details`, { 'ClientCount': node.ioClientsCount, 'rcvdMsgCount': node.rcvMsgCount, 'Channels': node.ioChannels, 'Namespace': node.ioNamespace } )

        // Keep track of the number of times each instance is deployed.
        // The initial deployment = 1
        if ( deployments.hasOwnProperty(node.id) ) deployments[node.id]++
        else deployments[node.id] = 1
        log.verbose(`[${uibInstance}] Number of Deployments`, deployments[node.id] )

        // We need an http server to serve the page. @since 2019-02-04 removed httpAdmin - we only want to use httpNode for web pages
        const app = RED.httpNode // || RED.httpAdmin

        /** Provide the ability to have a ExpressJS middleware hook.
         * This can be used for custom authentication/authorisation or anything else.
         * The function must be defined in settings.js
         * @since v1.0.3 2017-12-15
         */
        var httpMiddleware = function(req,res,next) { next() }
        if ( uib_globalSettings.hasOwnProperty('middleware') ) {
            /** Is a uibuilder specific function available? */
            if ( typeof uib_globalSettings.middleware === 'function' ) {
                log.verbose(`[${uibInstance}] Using uibuilder specific middleware from settings.js`)
                httpMiddleware = uib_globalSettings.middleware
            }
        } else {
            /** If not, see if the Node-RED one is available and use that instead.
             * Use httNodeMiddleware function which is defined in settings.js
             * as for the http in/out nodes - normally used for authentication
             */
            if ( typeof RED.settings.httpNodeMiddleware === 'function' ) {
                log.verbose(`[${uibInstance}] Using Node-RED middleware from settings.js`)
                httpMiddleware = RED.settings.httpNodeMiddleware
            }
        }

        /** This ExpressJS middleware runs when the uibuilder page loads
         * @see https://expressjs.com/en/guide/using-middleware.html */
        function localMiddleware (req, res, next) {
            // Tell the client what Socket.IO namespace to use,
            // trim the leading slash because the cookie will turn it into a %2F
            res.setHeader('uibuilder-namespace', node.ioNamespace)
            res.cookie('uibuilder-namespace', tilib.trimSlashes(node.ioNamespace), {path: node.url, sameSite: true})
            next()
        }

        //#region ----- Create local folder structure ----- //
        var customStatic = function(req,res,next) { next() } // Dummy ExpressJS middleware, replaced by local static folder if needed
        var customFoldersOK = true
        // TODO: May be better as async calls - probably not, but a promisified version would be OK?
        // Make sure the global custom folder exists first
        try {
            fs.mkdirSync(uib_rootPath) // try to create
            fs.accessSync( uib_rootPath, fs.constants.W_OK ) // try to access
        } catch (e) {
            if ( e.code !== 'EEXIST' ) { // ignore folder exists error
                log.error(`[${uibInstance}] Custom folder ERROR, path: ${uib_rootPath}`, e.message)
                customFoldersOK = false
            }
        }
        // make sure the folder for this node instance exists
        try {
            fs.mkdirSync(node.customFolder)
            fs.accessSync(node.customFolder, fs.constants.W_OK)
        } catch (e) {
            if ( e.code !== 'EEXIST' ) {
                log.error(`[${uibInstance}] Local custom folder ERROR`, e.message)
                customFoldersOK = false
            }
        }
        // Then make sure the DIST & SRC folders for this node instance exist
        try {
            fs.mkdirSync( path.join(node.customFolder, 'dist') )
            fs.mkdirSync( path.join(node.customFolder, 'src') )
        } catch (e) {
            if ( e.code !== 'EEXIST' ) {
                log.error(`[${uibInstance}] Local custom dist or src folder ERROR`, e.message)
                customFoldersOK = false
            }
        }

        // We've checked that the custom folder is there and has the correct structure
        if ( customFoldersOK === true ) {
            // local custom folders are there ...
            log.debug(`[${uibInstance}] Using local front-end folders in`, node.customFolder)

            /** Now copy files from the master template folder (instead of master src) @since 2017-10-01
             *  Note: We don't copy the master dist folder
             *  Don't copy if copy turned off in admin ui 
             * TODO: always copy index.html */
            if ( node.copyIndex ) {
                const cpyOpts = {'overwrite':false, 'preserveTimestamps':true}
                fs.copy( path.join( masterTemplateFolder, templateToUse ), path.join(node.customFolder, 'src'), cpyOpts, function(err){
                    if(err){
                        log.error(`[${uibInstance}] Error copying template files from ${path.join( __dirname, 'templates')} to ${path.join(node.customFolder, 'src')}`, err)
                    } else {
                        log.debug(`[${uibInstance}] Copied template files to local src (not overwriting)`, node.customFolder )
                    }
                })
            }
        } else {
            // Local custom folders are not right!
            log.error(`[${uibInstance}] Wanted to use local front-end folders in ${node.customFolder} but could not`)
        }

        //#region Add static path for local custom files
        // TODO: need a build capability for dist - nb probably keep vendor and private code separate
        try {
            // Check if local dist folder contains an index.html & if NR can read it - fall through to catch if not
            fs.accessSync( path.join(node.customFolder, 'dist', 'index.html'), fs.constants.R_OK )
            // If the ./dist/index.html exists use the dist folder...
            log.debug(`[${uibInstance}] Using local dist folder`)
            customStatic = serveStatic( path.join(node.customFolder, 'dist') )
            // NOTE: You are expected to have included vendor packages in
            //       a build process so we are not loading them here
        } catch (e) {
            // dist not being used or not accessible, use src
            log.debug(`[${uibInstance}] Dist folder not in use or not accessible. Using local src folder`, e.message )
            customStatic = serveStatic( path.join(node.customFolder, 'src') )
            // Include vendor resource source paths if needed
            node.userVendorPackages.forEach(function (packageName) {
                // @since 2017-09-19 Using get-installed-path to find where a module is actually installed
                // @since 2017-09-19 AND try require.resolve() as backup (NB this may return unusable path for linked modules)
                var installPath = ''
                try { //@since 2017-09-21 force cwd to be NR's UserDir - Colin Law
                    installPath = getInstalledPathSync(packageName, {local:true, cwd: userDir})
                } catch (e1) {
                    // if getInstalledPath fails, try nodejs internal resolve
                    try {
                        // @since 2017-11-11 v1.0.2 resolve returns the root script not the path
                        installPath = path.dirname( require.resolve(packageName) )
                    } catch (e2) {
                        log.error(`[${uibInstance}] Failed to add user vendor path - no install found for ${packageName}.  Try doing "npm install ${packageName} --save" from ${userDir}`, e2.message );
                        RED.log.warn(`uibuilder:${uibInstance}: Failed to add user vendor path - no install found for ${packageName}.  Try doing "npm install ${packageName} --save" from ${userDir}`)
                    }
                }
                if (installPath !== '') {
                    let vendorPath = tilib.urlJoin(node.url, 'vendor', packageName)
                    log.info(`[${uibInstance}] Adding user vendor path`, {
                        'url': vendorPath, 'path': installPath
                    })
                    app.use( vendorPath, serveStatic(installPath) )
                    vendorPaths[packageName] = {'url': vendorPath, 'path': installPath}
                }
            }) // -- end of forEach vendor package -- //
        }
        //#endregion -- Added static path for local custom files -- //
        //#endregion ------ End of Create custom folder structure ------- //

        /** Create a new, additional static http path to enable
         * loading of central static resources for uibuilder */
        var masterStatic = function(req,res,next) { next() }
        //Object.defineProperty(f, 'name', {value: myName, writable: false})
        try {
            // Will we use "compiled" version of module front-end code?
            fs.accessSync( path.join(__dirname, 'dist', 'index.html'), fs.constants.R_OK )
            log.debug(`[${uibInstance}] Using master production build folder`)
            // If the ./dist/index.html exists use the dist folder...
            masterStatic = serveStatic( path.join( __dirname, 'dist' ) )
        } catch (e) {
            // ... otherwise, use dev resources at ./src/
            log.debug(`[${uibInstance}] Using master src folder and master vendor packages` )
            log.debug('        Reason for not using master dist folder: ', e.message )
            masterStatic = serveStatic( path.join( __dirname, 'src' ) )
            // Include vendor resource source paths if needed
            vendorPackages.forEach(function (packageName) {
                // @since 2017-09-19 Using get-installed-path to find where a module is actually installed
                // @since 2017-09-19 AND try require.resolve() as backup (NB this may return unusable path for linked modules)
                var installPath = ''
                try { //@since 2017-09-21 force cwd to be NR's UserDir - Colin Law
                    installPath = getInstalledPathSync(packageName, {local:true, cwd: userDir})
                } catch (e1) {
                    // if getInstalledPath fails, try nodejs internal resolve
                    try {
                        // @since 2017-11-11 v1.0.2 resolve returns the root script not the path
                        installPath = path.dirname( require.resolve(packageName) )
                    } catch (e2) {
                        log.error(`[${uibInstance}] Failed to add master vendor path - no install found for ${packageName}. Should have been installed by this module`)
                        RED.log.warn(`uibuilder:${uibInstance}: Failed to add master vendor path - no install found for ${packageName}. Should have been installed by this module`)
                    }
                }
                if (installPath !== '') {
                    log.info(`[${uibInstance}] Adding master vendor path`, {
                        'url':  tilib.urlJoin(node.url, 'vendor', packageName), 'path': installPath
                    } )
                    app.use( tilib.urlJoin(node.url, 'vendor', packageName), serveStatic(installPath) )
                }
            })
        }

        app.use( tilib.urlJoin(node.url), httpMiddleware, localMiddleware, customStatic, masterStatic )

        const fullPath = tilib.urlJoin( httpNodeRoot, node.url ) // same as node.ioNamespace

        log.info(`[${uibInstance}] Version ${nodeVersion} started at URL ${fullPath}`)
        log.info(`[${uibInstance}] UI Source files at ${node.customFolder}`)
        RED.log.info(`uibuilder:${uibInstance}: UI Builder Version ${nodeVersion} started at URL ${fullPath}`)
        RED.log.info(`uibuilder:${uibInstance}: UI Source files at ${node.customFolder}`)

        //console.dir(app._router.stack)
        //if (debug && process.env.NODE_ENV === 'development') { // Only in dev environment
            // Absolute path to output file
            //var filepath = path.join(__dirname, './routes.generated.txt')
            // Invoke express-print-routes
            //require('express-print-routes')(app, filepath)
        //}

        // We only do the following if io is not already assigned (e.g. after a redeploy)
        uiblib.setNodeStatus( { fill: 'blue', shape: 'dot', text: 'Node Initialised' }, node )

        /** Each deployed instance has it's own namespace @type {Object.ioNameSpace} */
        var ioNs = io.of(node.ioNamespace)

        /** When someone loads the page, it will try to connect over Socket.IO
         *  note that the connection returns the socket instance to monitor for responses from
         *  the ui client instance */
        ioNs.on('connection', function(socket) {
            node.ioClientsCount++

            log.verbose(`[${uibInstance}] Socket connected, clientCount: ${node.ioClientsCount}, ID: ${socket.id}`)

            uiblib.setNodeStatus( { fill: 'green', shape: 'dot', text: 'connected ' + node.ioClientsCount }, node )

            // Let the clients (and output #2) know we are connecting & send the desired debug state
            uiblib.sendControl({
                'uibuilderCtrl': 'client connect',
                'cacheControl': 'REPLAY',          // @since 2017-11-05 v0.4.9 @see WIKI for details
                'debug': node.debugFE,
                '_socketId': socket.id,
                'from': 'server',
                // @since 2018-10-07 v1.0.9 - send server timestamp so that client can work out
                // time difference (UTC->Local) without needing clever libraries.
                'serverTimestamp': (new Date()),
            }, ioNs, node)
            //ioNs.emit( node.ioChannels.control, { 'uibuilderCtrl': 'server connected', 'debug': node.debugFE } )

            // if the client sends a specific msg channel...
            socket.on(node.ioChannels.client, function(msg) {
                log.debug(`[${uibInstance}] Data received from client, ID: ${socket.id}, Msg:`, msg)

                // Make sure the incoming msg is a correctly formed Node-RED msg
                switch ( typeof msg ) {
                    case 'string':
                    case 'number':
                    case 'boolean':
                        msg = { 'topic': node.topic, 'payload': msg}
                }

                // If the sender hasn't added msg._clientId, add the Socket.id now
                if ( ! msg.hasOwnProperty('_socketId') ) {
                    msg._socketId = socket.id
                }

                // Send out the message for downstream flows
                // TODO: This should probably have safety validations!
                node.send(msg)
            })
            socket.on(node.ioChannels.control, function(msg) {
                log.debug(`[${uibInstance}] Control Msg from client, ID: ${socket.id}, Msg:`, msg)

                // Make sure the incoming msg is a correctly formed Node-RED msg
                switch ( typeof msg ) {
                    case 'string':
                    case 'number':
                    case 'boolean':
                        msg = { 'uibuilderCtrl': msg }
                }

                // If the sender hasn't added msg._clientId, add the Socket.id now
                if ( ! msg.hasOwnProperty('_socketId') ) {
                    msg._socketId = socket.id
                }

                // @since 2017-11-05 v0.4.9 If the sender hasn't added msg.from, add it now
                if ( ! msg.hasOwnProperty('from') ) {
                    msg.from = 'client'
                }

                // Send out the message on port #2 for downstream flows
                uiblib.sendControl(msg, ioNs, node)  // fn adds topic if needed
                //node.send([null,msg])
            })

            socket.on('disconnect', function(reason) {
                node.ioClientsCount--
                log.debug(
                    `[${uibInstance}] Socket disconnected, clientCount: ${node.ioClientsCount}, Reason: ${reason}, ID: ${socket.id}`
                )
                if ( node.ioClientsCount <= 0) uiblib.setNodeStatus( { fill: 'blue', shape: 'dot', text: 'connected ' + node.ioClientsCount }, node )
                else uiblib.setNodeStatus( { fill: 'green', shape: 'ring', text: 'connected ' + node.ioClientsCount }, node )
                // Let the control output port know a client has disconnected
                uiblib.sendControl({
                    'uibuilderCtrl': 'client disconnect',
                    'reason': reason,
                    '_socketId': socket.id,
                    'from': 'server'
                }, ioNs, node)
                //node.send([null, {'uibuilderCtrl': 'client disconnect', '_socketId': socket.id, 'topic': node.topic}])
            })

            socket.on('error', function(err) {
                log.error(`[${uibInstance}] ERROR received, ID: ${socket.id}, Reason: ${err.message}`)
                // Let the control output port know there has been an error
                uiblib.sendControl({
                    'uibuilderCtrl': 'socket error',
                    'error': err.message,
                    '_socketId': socket.id,
                    'from': 'server'
                }, ioNs, node)
            })

            /* More Socket.IO events but we really don't need to monitor them
                socket.on('disconnecting', function(reason) {
                    RED.log.audit({
                        'UIbuilder': node.url+' DISCONNECTING received', 'ID': socket.id,
                        'data': reason
                    })
                })
                socket.on('newListener', function(data) {
                    RED.log.audit({
                        'UIbuilder': node.url+' NEWLISTENER received', 'ID': socket.id,
                        'data': data
                    })
                })
                socket.on('removeListener', function(data) {
                    RED.log.audit({
                        'UIbuilder': node.url+' REMOVELISTENER received', 'ID': socket.id,
                        'data': data
                    })
                })
                socket.on('ping', function(data) {
                    RED.log.audit({
                        'UIbuilder': node.url+' PING received', 'ID': socket.id,
                        'data': data
                    })
                })
                socket.on('pong', function(data) {
                    RED.log.audit({
                        'UIbuilder': node.url+' PONG received', 'ID': socket.id,
                        'data': data
                    })
                })
            */

        }) // ---- End of ioNs.on connection ---- //

        /** Handler function for node input events (when a node instance receives a msg)
         * @param {Object} msg The msg object received.
         **/
        function nodeInputHandler(msg) {
            log.verbose(`[${uibInstance}] nodeGo:nodeInputHandler - emit received msg - Namespace: ${node.url}`) //debug

            // If msg is null, nothing will be sent
            if ( msg !== null ) {
                // if msg isn't null and isn't an object
                // NOTE: This is paranoid and shouldn't be possible!
                if ( typeof msg !== 'object' ) {
                    // Force msg to be an object with payload of original msg
                    msg = { 'payload': msg }
                }
                // Add topic from node config if present and not present in msg
                if ( !(msg.hasOwnProperty('topic')) || msg.topic === '' ) {
                    if ( node.topic !== '' ) msg.topic = node.topic
                    else msg.topic = 'uibuilder'
                }
            }

            // Keep this fn small for readability so offload
            // any further, more customised code to another fn
            msg = uiblib.inputHandler(msg, node, RED, io, ioNs, log)

        } // -- end of msg received processing -- //

        // Process inbound messages
        node.on('input', nodeInputHandler)

        // Do something when Node-RED is closing down
        // which includes when this node instance is redeployed
        node.on('close', function(removed,done) {
            log.debug(`[${uibInstance}] nodeGo:on-close: ${removed?'Node Removed':'Node (re)deployed'}`)

            node.removeListener('input', nodeInputHandler)

            // Do any complex close processing here if needed - MUST BE LAST
            //processClose(null, node, RED, ioNs, io, app) // swap with below if needing async
            uiblib.processClose(done, node, RED, ioNs, io, app, log, instances)

            done()
        })

    }
1121635
function (apiBaseUrl, apiKey, projectId) {
  this.config = {
    apiBaseUrl: apiBaseUrl,
    apiKey:     apiKey,
    projectId:  projectId
  };
}
523575
function (config) {
        if (typeof config !== 'object') {
            throw new Error('Invalid Route Config');
        }
        if (typeof config.route !== 'string') {
            var name_1 = config.name || '(no name)';
            throw new Error('Invalid Route Config for "' + name_1 + '": You must specify a "route:" pattern.');
        }
        if (!('redirect' in config || config.moduleId || config.navigationStrategy || config.viewPorts)) {
            throw new Error('Invalid Route Config for "' + config.route + '": You must specify a "moduleId:", "redirect:", "navigationStrategy:", or "viewPorts:".');
        }
    }
529338
function init(config) {
  var hydroConfig = config.hydro || {};
  var hydroJs = hydroConfig.path || dirname(dirname(require.resolve('hydro'))) + '/dist/hydro.js';
  var before = hydroConfig.before || [];

  config.files.unshift(createPattern(__dirname + '/adapter.js'));
  config.files.unshift(createPattern(hydroJs));

  before.reverse().forEach(function(file) {
    config.files.unshift(createPattern(path.resolve(file)));
  });
}
586070
function(url, version, config) {
		if (!config.rewriteScheme) {
			return url;
		}

		var basename = path.basename(url);
		var ext = path.extname(url).substr(1);
		var filename = basename.replace(new RegExp('\\.' + ext + '$'), '');

		var data = {
			url: url,
			dirname: path.dirname(url),
			basename: basename,
			ext: ext,
			filename: filename,
			version: version
		};

		if (typeof config.rewriteScheme == 'string') {
			return _.template(config.rewriteScheme, data);
		}

		return config.rewriteScheme(data);
	}
410902
function build(base, config) {
  var result = resolver(base);
  Object.keys(config).forEach(function (key) {
    var value = config[key];
    if (typeof value === "string") {
      result[key] = resolver(result(value, true));
    } else if (Array.isArray(value) && value.length === 2 &&
        typeof value[0] === "string" &&  typeof value[1] === "object") {
      result[key] = build(result(value[0], true), value[1]);
    } else {
      throw new TypeError("Invalid value at: " + key);
    }
  });
  return result;
}
728724
function Config(module) {
  if (!(this instanceof Config))
    return new Config(module);

  assert(typeof module === 'string');
  assert(module.length > 0);

  this.module = module;
  this.network = 'mainnet';
  this.prefix = Path.join(HOME, `.${module}`);

  this.options = Object.create(null);
  this.data = Object.create(null);
  this.env = Object.create(null);
  this.args = Object.create(null);
  this.argv = [];
  this.pass = [];
  this.query = Object.create(null);
  this.hash = Object.create(null);
}
633140
function INIT(config) {
  if (__init) return;

  CONF = _.extend(CONF, config)

  LOG = LOG.use(require('./lib/sentry')(CONF.sentry))

  JOBS = Q.init(CONF, LOG)

  if (CONF.auth)
    WWW.use('/'+CONF.admin_url_prefix,
            express.basicAuth(CONF.auth.user, CONF.auth.pass));

  WWW.use(express.bodyParser())
  WWW.use('/'+CONF.admin_url_prefix, Q.kue.app)

  __init = true
}
1180101
function Ifttt(config) {
  config = _.defaults(config || {}, {
    apiVersion: 'v1',
    authMode: 'header', // 'header', 'oauth2'
    logger: console,
    testAccessToken: ''
  });

  if (_.isUndefined(config.channelKey)) {
    throw new Error('Property `channelKey` is required.');
  }

  this.iftttApiVersion = config.apiVersion;

  // IFTTT channel key, needed for test setup verification.
  this.iftttChannelKey = config.channelKey;

  // IFTTT version basepath
  this.iftttBasepath = '/ifttt/' + this.iftttApiVersion;

  // IFTTT auth mode
  this.iftttAuthMode = config.authMode;

  // IFTTT test access token
  this.iftttTestAccessToken = config.testAccessToken;

  // Internal reference to desired logger.
  this.logger = config.logger; // Must support `info`, `error`, `warn`

  // Internal registry for actions & triggers.
  this.registry = {
    action: {},
    trigger: {}
  };

  // Internal registry for generic handlers.
  this.handlers = {
    status: null,
    user_info: null,
    test_setup_fake: null
  };

  // Internal storage of current user data for triggers / triggerFields.
  this.currentUserData = null;
}
801955
def _construct_config(self, basedir, port, name=None, isreplset=False):
        """"""
        if isreplset:
            return self._construct_replset(basedir=basedir, portstart=port,
                                           name=name,
                                           num_nodes=list(range(
                                               self.args['config'])),
                                           arbiter=False, extra='--configsvr')
        else:
            datapath = self._create_paths(basedir, name)
            self._construct_mongod(os.path.join(datapath, 'db'),
                                   os.path.join(datapath, 'mongod.log'),
                                   port, replset=None, extra='--configsvr')
157767
function auth(app, config) {
  /* Ensure authorizer */
  if (is.not.function(config.authorizer)) {
    throw new Error(ERR_AUTHORIZER);
  }

  /* Check debug type */
  if (is.function(config.debug)) {
    debug = config.debug;
  } else if (config.debug) {
    debug = console.log.bind(console);
  }

  /* Set the authorized property in 'req.session' */
  app.use((req, res, next) => {
    req.session.authorized = config.authorizer(req);
    next();
  });

  /* Set authorization rules for each route */
  config.routes.forEach((route) => {
    route = normalize(route);

    var router = app.route(route.path);

    if (is.array(route.method) && route.method.length) {
      route.method.forEach((method) => {
        logAssignment(method, route.path, route.allows);
        router[method](generate(route.allows), authorize);
      });
    } else if (is.string(route.method)) {
      logAssignment(route.method, route.path, route.allows);
      router[route.method](generate(route.allows), authorize);
    } else {
      logAssignment(ALL, route.path, route.allows);
      router.all(generate(route.allows), authorize);
    }
  });
}
562371
function(config, name) {
            if (config && config !== Object(config)) {
                throw new Error('Config object should be a key/value object.');
            }

            var defaultConfig = {
                loop: false,
                maxLoops: Infinity
            };

            var instance = Object.create(Queue);

            this.queues.push(name ? {
                name: name,
                instance: instance
            } : {
                instance: instance
            });

            merge(instance, {
                config: merge({}, defaultConfig, config),
                steps: []
            });

            return instance;
        }
1282012
public CRestBuilder basicAuth(String username, String password) {
        this.auth = "basic";
        this.username = username;
        this.password = password;
        return this;
    }