UNPKG

2.91 kBJavaScriptView Raw
1/**
2 * Module dependencies
3 */
4
5var stack = require('simple-stack-common');
6var resolve = require('path').resolve;
7
8var NODE_ENV = process.env.NODE_ENV || 'production';
9
10var xforward = {
11 host: 'x-orig-host',
12 path: 'x-orig-path',
13 port: 'x-orig-port',
14 proto: 'x-orig-proto'
15};
16
17exports = module.exports = function(opts) {
18 opts = opts || {};
19 opt('root', process.cwd());
20 opt('entry', opts.root + '/src');
21 opt('parseCookies', true);
22 opt('parseBody', false);
23 opt('cdnUrl', process.env.CDN_URL || '');
24 opt('apiUrl', process.env.API_URL);
25 opt('proxyApiUrl', opts.apiUrl);
26 opt('xforward', xforward);
27 opt('oauthClientId', process.env.OAUTH_CLIENT_ID);
28 opt('oauthClientSecret', process.env.OAUTH_CLIENT_SECRET);
29 opt('oauthUrl', process.env.OAUTH_URL);
30 opt('assetCache', process.env.ASSET_CACHE);
31
32 var app = stack({
33 base: xforward
34 });
35
36 app.locals({
37 // app: pkg.name,
38 // description: pkg.description,
39 // author: pkg.author,
40 env: {
41 BROWSER_ENV: NODE_ENV,
42 API_URL: opts.apiUrl
43 }
44 });
45
46 // expose a way to set browser environment variables
47 app.env = function(key, value) {
48 app.locals.env[key] = value;
49 };
50
51 app.useBefore('router', function applyEnv(req, res, next) {
52 var env = {};
53 var v;
54 for (var k in app.locals.env) {
55 v = app.locals.env[k];
56 if (typeof v === 'function') env[k] = v(req, res);
57 else env[k] = v;
58 }
59 res.locals.env = env;
60 next();
61 });
62
63 if (opts.parseCookies) app.useBefore('router', stack.middleware.cookieParser());
64
65 if (!opts.parseBody) {
66 app.remove('methodOverride');
67 app.remove('json');
68 app.remove('urlencoded');
69 }
70
71 load(app, opts);
72
73 function opt(name, def) {
74 opts[name] = typeof opts[name] === 'undefined' ? def : opts[name];
75 }
76
77 return app;
78};
79
80exports.middleware = stack.middleware;
81
82function load(app, opts) {
83 function r(path, mode) {
84 path = r.resolve(path, mode);
85 if (!path) return null;
86 return require(path);
87 }
88
89 r.missing = {};
90
91 r.resolve = function(path, mode) {
92 try {
93 return require.resolve(resolve(opts.root + '/node_modules', path));
94 } catch (e) {
95 if (mode === 'silent') return null;
96 console.error(path + ' missing. unexpected behavior may occur if not added to the package.json');
97 if (mode === 'warn') return null;
98 r[path] = true;
99 r.hasMissing = true
100 }
101 };
102
103 [
104 'builder',
105 'assets',
106 'env',
107 'hyperclient',
108 'features',
109 'dev-builder',
110 'dev-proxy',
111 'oauth',
112 'render'
113 ].forEach(function(plugin) {
114 require('./' + plugin)(r, app, opts, NODE_ENV, stack.middleware);
115 });
116
117 if (r.hasMissing) {
118 console.error();
119 console.error('Missing required modules. please install with:');
120 console.error();
121 console.error(' npm i --save ' + Object.keys(r.missing).join(' ') + '`');
122 console.error();
123 process.exit(1);
124 }
125}