function swaggerize(options) { var app; assert.ok(thing.isObject(options), 'Expected options to be an object.'); assert.ok(thing.isObject(options.api), 'Expected an api definition.'); options.basedir = path.dirname(caller()); options.routes = builder(options); app = express(); app.once('mount', mount(options)); Object.defineProperty(app, '_api', { enumerable: false, value: options.api }); Object.defineProperty(app, 'setHost', { enumerable: true, value: function (value) { options.api.host = value; } }); return app; }
exports.getCallerRoot = function getCallerRoot() { try { return findRoot(caller(2)); } catch (err) { return; } };
module.exports = function (options) { var rootapp, app; options = options || {}; options.basedir = options.basedir || path.dirname(caller()); options.onconfig = options.onconfig || function(conf, done) { var engines = conf.get('view engines'); Object.keys(engines).forEach(function(ext) { engines[ext].renderer.arguments.push(rootapp); }); rootapp = null; done( null, conf); }; // 插入 config 读取,让整体 config 的读取顺序如下: // - kranken-js/config/ // - yog/config/ // - app/config/ config(options); app = kraken(options); app.on('mount', function(parent) { rootapp = parent; parent.on('start', function() { parent.yog = parent.kraken; }); }); return app; };
load (root, prefix) { debug('Router: loading by root path ' + root); if ('string' !== typeof root) { throw new Error('Router loading root path is not a string'); } root = path.normalize(root); if (!path.isAbsolute(root)) { debug('Router: root is not absolute, make an absolute one'); root = path.join(path.dirname(caller()), root); } if (prefix) { prefix = String(path.normalize(prefix)).replace(/\\/g,"/"); if (!prefix || !prefix[0] || prefix[0] === '.') { throw new Error('Invalid router prefix ' + prefix); } debug('Router: create a new Router to load with prefix ' + prefix); const opts = extend(true, {}, this.opts); opts.routePrefix = opts.routePrefix || ''; opts.routePrefix += prefix; const router = Router.create(opts).load(root); debug('Router: using the router with prefix ' + prefix); this.use(prefix, router.routes()); return this; } debug('Router; loading by directory structure of ' + root); /** * First load all files, then load directories recrusively **/ const dirlist = []; const filelist = []; const list = fs.readdirSync(root); for (const filename of list) { let routePath = name2routePath(filename, this.options); if (routePath === false) { continue; } routePath = '/' + routePath; const item = { filename, routePath }; const absolutePath = path.join(root, filename); const stat = fs.statSync(absolutePath); if (stat.isDirectory()) { dirlist.push(item); } else if (stat.isFile()) { filelist.push(item); } } for (const item of filelist) { loadRouteByFilename(this, item.filename, item.routePath, root); } for (const item of dirlist) { this.load(path.join(root, item.filename), item.routePath); } return this; }
module.exports = function (options) { var calledFrom = path.dirname(caller()) return new Promise(function (resolve) { var stream = fs.createReadStream(path.resolve(calledFrom, options.path)) , chunks = [] stream .pipe(through(function (chunk, enc, cb) { chunks.push(chunk.toString('utf8')) cb() }, function (cb) { var file = chunks.join('') eval(file) resolve(eval(options.exports)) })) stream.on('error', function () { console.error('error reading', options.path); console.log('full path:', path.join(__dirname, options.path)); }) }) }
constructor(name = caller()) { super(); this.source = new Source(name); this.debuglog = debuglog(this.name); // register debuglog as a default log handler. Is opt-in by default, // so is a noop unless NODE_DEBUG is enabled for a particular name. this.on('log', ({ tags, data }) => { if (data instanceof Error) { data = data.stack; } if (typeof data !== 'string') { data = JSON.stringify(data); } this.debuglog('%s %s', tags.join(','), data); }); // Add methods for each logging level. for (let level of LEVELS) { this[level] = function () { this._log(...arguments, level); }; } }
module.exports.sync = function(filePath){ var absolutePath = path.resolve(path.dirname(caller()), filePath); var fileContent = fs.readFileSync(absolutePath, {encoding: 'utf-8'}); return getAnnotationFromFile(absolutePath, filePath, fileContent); };
function load() { var cwd = path.dirname(caller()); if (arguments.length === 1 || arguments.length === 2) { return loadWithPatterns(cwd, arguments[0], arguments[1]); } loadFromDir(cwd); }
function swaggerize(options) { var schemas; assert.ok(thing.isObject(options), 'Expected options to be an object.'); assert.ok(thing.isObject(options.api), 'Expected an api definition.'); if ('basedir' in options) { assert.ok(thing.isString(options.basedir), 'Expected basedir to be a string.'); assert.ok(options.basedir.length, 'Expected basedir to be a non-empty string.'); } if ('schemas' in options) { assert.ok(thing.isArray(options.schemas), 'Expected schemas option to be an array.'); } if ('handlers' in options) { assert.ok(thing.isString(options.handlers) || thing.isObject(options.handlers), 'Expected handlers to be a string or an object.'); assert.ok(!thing.isString(options.handlers) || options.handlers.length, 'Expected handlers to be a non-empty string.'); } options.basedir = options.basedir || path.dirname(caller()); schemas = { '#': swaggerSchema }; // Map and validate API against schemas if (thing.isArray(options.schemas)) { options.schemas.forEach(function (schema) { assert.ok(thing.isObject(schema), 'Expected schema option to be an object.'); assert.ok(thing.isString(schema.name), 'Expected schema name to be a string.'); assert.ok(schema.name && schema.name !== '#', 'Schema name can not be base schema.'); assert.ok(thing.isString(schema.schema) || thing.isObject(schema.schema), 'Expected schema to to an object.'); if (thing.isString(schema.schema)) { schema.schema = require(path.resolve(options.basedir, schema.schema)); } schemas[schema.name] = schema.schema; }); } enjoi(swaggerSchema, schemas).validate(options.api, function (error) { assert.ifError(error); }); // Resolve path to handlers options.handlers = options.handlers || './handlers'; if (thing.isString(options.handlers) && path.resolve(options.handlers) !== options.handlers) { // Relative path, so resolve to basedir options.handlers = path.join(options.basedir, options.handlers); } return buildroutes(options); }
/** * The main entry point for this module. Creates middleware * to be mounted to a parent application. * @param options the configuration settings for this middleware instance * @returns {Function} express middleware */ function enrouten(options) { var app; options = options || {}; options.basedir = options.basedir || path.dirname(caller()); app = express(); app.once('mount', mount(app, options)); return app; }
function resolveSync(id, opts) { opts = buildOptions(opts) if (!opts.basedir) { opts.basedir = path.dirname(caller()) } if (opts.extensions && !Array.isArray(opts.extensions)) { opts.extensions = [opts.extensions] } return realpath(resolver.sync(id, opts), options.symlink) }
return function (module) { var basedir; if (!isAbsolute(module)) { basedir = path.dirname(caller()); debug('resolving "%s" from directory "%s"', module, basedir); arguments[0] = module = resolve.sync(module, { basedir: basedir, extensions: Object.keys(require.extensions) }); } return fn.apply(this, arguments); };
value: function configure(options) { var parent, root; if (!options.basedir) { parent = path.dirname(caller()); root = common.findFile('package.json', parent); options.basedir = root ? path.dirname(root): parent; } SETTINGS = common.deepFreeze(_.defaults(options, DEFAULTS)); DEFAULT_LOGGER = common.createWinstonLogger(SETTINGS); },
constructor(handlerModule) { switch(typeof handlerModule) { case 'string': this.handlerModuleName = handlerModule; break; case 'object': this.handlerModuleName = path.basename(handlerModule.filename); break; default: this.handlerModuleName = caller(); break; } }
function pine(name, options) { var parent, root; if (typeof name === 'object') { options = name; name = undefined; } if (!DEFAULT_LOGGER) { parent = path.dirname(caller()); root = common.findFile('package.json', parent); DEFAULTS.basedir = root ? path.dirname(root): parent; pine.configure(DEFAULTS); } name = name || caller(); name = (name === path.resolve(name)) ? path.relative(SETTINGS.basedir, name) : name; options = options && _.defaults(options, SETTINGS); // Custom options result in a new logger, otherwise reuse default. return logger(name, options ? common.createWinstonLogger(options) : DEFAULT_LOGGER); }
module.exports = function meddleware(settings) { var basedir, app; // The `require`-ing module (caller) is considered the `basedir` // against which relative file paths will be resolved. // Don't like it? Then pass absolute module paths. :D basedir = path.dirname(caller()); function onmount(parent) { var resolve, mountpath; // Remove the sacrificial express app. parent._router.stack.pop(); resolve = resolvery(basedir); mountpath = app.mountpath; util .mapValues(settings, util.nameObject) .filter(thing.isObject) .sort(compare) .forEach(function register(spec) { var fn, eventargs, route; if (!spec.enabled && 'enabled' in spec) { return; } fn = resolve(spec, spec.name); eventargs = { app: parent, config: spec }; route = mountpath; if (typeof spec.route === 'string') { route += route[route.length - 1] !== '/' ? '/' : ''; route += spec.route[0] === '/' ? spec.route.slice(1) : spec.route; } debug('registering', spec.name, 'middleware'); parent.emit('middleware:before', eventargs); parent.emit('middleware:before:' + spec.name, eventargs); parent.use(route, fn); parent.emit('middleware:after:' + spec.name, eventargs); parent.emit('middleware:after', eventargs); }); } app = express(); app.once('mount', onmount); return app; };
function shush(file) { var root, abs, json; root = path.resolve(caller()); root = path.dirname(root); abs = path.resolve(root, file); abs = require.resolve(abs); json = fs.readFileSync(abs, 'utf8'); json = strip(json); return tryParse(abs, json); }
module.exports = function getAllAnnotations(filePath, callback){ var absolutePath = path.resolve(path.dirname(caller()), filePath); fs.readFile(absolutePath, {encoding: 'utf-8'}, function(err, fileContent){ if(err) return callback(err); try { var result = getAnnotationFromFile(absolutePath, filePath, fileContent); } catch (e) { callback(e); } callback(null, result); }); };
function resolve(id, opts, next) { if (typeof opts === 'function') { next = opts opts = {} } opts = buildOptions(opts) if (!opts.basedir) { opts.basedir = path.dirname(caller()) } return resolver(id, opts, function (err, res) { if (!err) { res = realpath(res, options.symlink) } next.apply(null, [err, res].concat(slice(arguments, 2))) }) }
module.exports = function(){ if (DEBUG) { var args = Array.prototype.slice.apply(arguments), i, len; // get file var _caller = caller(); _caller = path.basename( _caller.indexOf('index.js') != -1 ? _caller.replace('index.js','') : _caller ); for (i = 0, len = args.length; i < len; ++i) { console.log('[DEBUG]['+ _caller +']', args[i]); } } }
module.exports = function (app, config) { config = config||{} var www = app.get('www'); var env = config.env||'prod'; var configMap ={ local:'middleware.loca.js', dev:'middleware.dev.js', test:'middleware.test.js', prod:'middleware.prod.js', }; var dir = config.path || path.resolve(path.dirname(caller()), 'server/config/middleware'); var middlewareConfig = require(path.resolve(dir, configMap[env])).init(app, config); Object.keys(middlewareConfig.middleware).forEach(function (key) { var item = middlewareConfig.middleware[key]; if (item.enabled) { var module = item.module; var method = module.method; var args = module.arguments; var mkey = module.path ? path.join(www, module.path) : (module.name || key); var middleware = require(mkey); if (method) { app.use(middleware[method].apply(null, args)); } else { app.use(middleware.apply(null, args)); } } }); return function (req, res, next) { next(); } };
function swaggerize(options) { var app; assert.ok(thing.isObject(options), 'Expected options to be an object.'); assert.ok(options.api, 'Expected an api definition.'); if (thing.isString(options.api)) { options.api = loadApi(options.api); } assert.ok(thing.isObject(options.api), 'Api definition must resolve to an object.'); options.basedir = path.dirname(caller()); options.routes = routes(options); app = express(); app.once('mount', mount(app, options)); return app; }
global.runTests = (fixture, testName, opts) => { const stream = createTestStream(); const runner = testCafe.createRunner(); const fixturePath = typeof fixture !== 'string' || path.isAbsolute(fixture) ? fixture : path.join(path.dirname(caller()), fixture); const skipJsErrors = opts && opts.skipJsErrors; const disablePageReloads = opts && opts.disablePageReloads; const quarantineMode = opts && opts.quarantineMode; const selectorTimeout = opts && opts.selectorTimeout || FUNCTIONAL_TESTS_SELECTOR_TIMEOUT; const assertionTimeout = opts && opts.assertionTimeout || FUNCTIONAL_TESTS_ASSERTION_TIMEOUT; const pageLoadTimeout = opts && opts.pageLoadTimeout || FUNCTIONAL_TESTS_PAGE_LOAD_TIMEOUT; const onlyOption = opts && opts.only; const skipOption = opts && opts.skip; const screenshotPath = opts && opts.setScreenshotPath ? '___test-screenshots___' : ''; const screenshotPathPattern = opts && opts.screenshotPathPattern; const screenshotsOnFails = opts && opts.screenshotsOnFails; const speed = opts && opts.speed; const appCommand = opts && opts.appCommand; const appInitDelay = opts && opts.appInitDelay; const externalProxyHost = opts && opts.useProxy; const proxyBypass = opts && opts.proxyBypass; const customReporters = opts && opts.reporters; const skipUncaughtErrors = opts && opts.skipUncaughtErrors; const stopOnFirstFail = opts && opts.stopOnFirstFail; const actualBrowsers = browsersInfo.filter(browserInfo => { const { alias, userAgent } = browserInfo.settings; const only = onlyOption ? [alias, userAgent].some(prop => onlyOption.includes(prop)) : true; const skip = skipOption ? [alias, userAgent].some(prop => skipOption.includes(prop)) : false; return only && !skip; }); if (!actualBrowsers.length) { mocha.test.skip(); return Promise.resolve(); } const connections = actualBrowsers.map(browserInfo => { return browserInfo.connection; }); const handleError = (err) => { const shouldFail = opts && opts.shouldFail; if (shouldFail && !err) throw new Error('Test should have failed but it succeeded'); if (err) throw err; }; if (customReporters) customReporters.forEach(r => runner.reporter(r.reporter, r.outStream)); else runner.reporter('json', stream); return runner .useProxy(externalProxyHost, proxyBypass) .browsers(connections) .filter(test => { return testName ? test === testName : true; }) .src(fixturePath) .screenshots(screenshotPath, screenshotsOnFails, screenshotPathPattern) .startApp(appCommand, appInitDelay) .run({ skipJsErrors, disablePageReloads, quarantineMode, selectorTimeout, assertionTimeout, pageLoadTimeout, speed, stopOnFirstFail, skipUncaughtErrors }) .then(failedCount => { if (customReporters) return; const taskReport = JSON.parse(stream.data); const errorDescr = getTestError(taskReport, actualBrowsers); const testReport = taskReport.fixtures.length === 1 ? taskReport.fixtures[0].tests[0] : taskReport; testReport.warnings = taskReport.warnings; testReport.failedCount = failedCount; global.testReport = testReport; handleError(errorDescr); }) .catch(handleError); };
module.exports = function (options) { var app; if (typeof options === 'string') { options = { basedir: options }; } options = options || {}; options.protocols = options.protocols || {}; options.onconfig = options.onconfig || noop; options.basedir = options.basedir || path.dirname(caller()); options.mountpath = null; options.inheritViews = !!options.inheritViews; debug('kraken options\n', options); app = express(); app.once('mount', function onmount(parent) { var start, error, promise; // Remove sacrificial express app parent._router.stack.pop(); // Since this particular `app` instance is // subsequently deleted, the `mountpath` is // moved to `options` for use later. options.mountpath = app.mountpath; start = parent.emit.bind(parent, 'start'); error = parent.emit.bind(parent, 'error'); // Kick off server and add middleware which will block until // server is ready. This way we don't have to block standard // `listen` behavior, but failures will occur immediately. promise = bootstrap(parent, options); promise.then(start, error); parent.use(function startup(req, res, next) { var headers = options.startupHeaders; if (promise.isPending()) { res.status(503); if (headers) { res.header(headers); } res.send('Server is starting.'); return; } if (promise.isRejected()) { res.status(503); res.send('The application failed to start.'); return; } next(); }); }); return app; };