-
Notifications
You must be signed in to change notification settings - Fork 69
/
ember-app.js
493 lines (428 loc) · 16 KB
/
ember-app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
'use strict';
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const najax = require('najax');
const SimpleDOM = require('simple-dom');
const existsSync = require('exists-sync');
const debug = require('debug')('fastboot:ember-app');
const FastBootInfo = require('./fastboot-info');
const Result = require('./result');
const FastBootSchemaVersions = require('./fastboot-schema-versions');
/**
* @private
*
* The `EmberApp` class serves as a non-sandboxed wrapper around a sandboxed
* `Ember.Application`. This bridge allows the FastBoot to quickly spin up new
* `ApplicationInstances` initialized at a particular route, then destroy them
* once the route has finished rendering.
*/
class EmberApp {
/**
* Create a new EmberApp.
* @param {Object} options
* @param {string} options.distPath - path to the built Ember application
* @param {Sandbox} [options.sandbox=VMSandbox] - sandbox to use
* @param {Object} [options.sandboxGlobals] - sandbox variables that can be added or used for overrides in the sandbox.
*/
constructor(options) {
let distPath = path.resolve(options.distPath);
let config = this.readPackageJSON(distPath);
this.appFilePaths = config.appFiles;
this.vendorFilePaths = config.vendorFiles;
this.moduleWhitelist = config.moduleWhitelist;
this.hostWhitelist = config.hostWhitelist;
this.config = config.config;
this.appName = config.appName;
if (process.env.APP_CONFIG) {
let appConfig = JSON.parse(process.env.APP_CONFIG);
let appConfigKey = this.appName;
if (!appConfig.hasOwnProperty(appConfigKey)) {
this.config[appConfigKey] = appConfig;
}
}
if (process.env.ALL_CONFIG) {
let allConfig = JSON.parse(process.env.ALL_CONFIG);
this.config = allConfig;
}
this.html = fs.readFileSync(config.htmlFile, 'utf8');
this.sandbox = this.buildSandbox(distPath, options.sandbox, options.sandboxGlobals);
this.app = this.retrieveSandboxedApp();
}
/**
* @private
*
* Builds and initializes a new sandbox to run the Ember application in.
*
* @param {string} distPath path to the built Ember app to load
* @param {Sandbox} [sandboxClass=VMSandbox] sandbox class to use
* @param {Object} [sandboxGlobals={}] any additional variables to expose in the sandbox or override existing in the sandbox
*/
buildSandbox(distPath, sandboxClass, sandboxGlobals) {
let sandboxRequire = this.buildWhitelistedRequire(this.moduleWhitelist, distPath);
const config = this.config;
const appName = this.appName;
function fastbootConfig(key) {
if (!key) {
// default to app key
key = appName;
}
if (config) {
return { default: config[key] };
} else {
return { default: undefined };
}
}
// add any additional user provided variables or override the default globals in the sandbox
let globals = {
najax,
FastBoot: {
require: sandboxRequire,
config: fastbootConfig
}
};
globals = Object.assign(globals, sandboxGlobals);
return new sandboxClass({ globals });
}
/**
* @private
*
* The Ember app runs inside a sandbox that doesn't have access to the normal
* Node.js environment, including the `require` function. Instead, we provide
* our own `require` method that only allows whitelisted packages to be
* requested.
*
* This method takes an array of whitelisted package names and the path to the
* built Ember app and constructs this "fake" `require` function that gets made
* available globally inside the sandbox.
*
* @param {string[]} whitelist array of whitelisted package names
* @param {string} distPath path to the built Ember app
*/
buildWhitelistedRequire(whitelist, distPath) {
whitelist.forEach(function(whitelistedModule) {
debug("module whitelisted; module=%s", whitelistedModule);
});
return function(moduleName) {
if (whitelist.indexOf(moduleName) > -1) {
let nodeModulesPath = path.join(distPath, 'node_modules', moduleName);
if (existsSync(nodeModulesPath)) {
return require(nodeModulesPath);
} else {
// If it's not on disk, assume it's a built-in node package
return require(moduleName);
}
} else {
throw new Error("Unable to require module '" + moduleName + "' because it was not in the whitelist.");
}
};
}
/**
* @private
*
* Loads the app and vendor files in the sandbox (Node vm).
*
*/
loadAppFiles() {
let sandbox = this.sandbox;
let appFilePaths = this.appFilePaths;
let vendorFilePaths = this.vendorFilePaths;
sandbox.eval('sourceMapSupport.install(Error);');
debug("evaluating app and vendor files");
vendorFilePaths.forEach(function(vendorFilePath) {
debug("evaluating vendor file %s", vendorFilePath);
let vendorFile = fs.readFileSync(vendorFilePath, 'utf8');
sandbox.eval(vendorFile, vendorFilePath);
});
debug("vendor file evaluated");
appFilePaths.forEach(function(appFilePath) {
debug("evaluating app file %s", appFilePath);
let appFile = fs.readFileSync(appFilePath, 'utf8');
sandbox.eval(appFile, appFilePath);
});
debug("app files evaluated");
}
/**
* @private
*
* Create the ember application in the sandbox.
*
*/
createEmberApp() {
let sandbox = this.sandbox;
// Retrieve the application factory from within the sandbox
let AppFactory = sandbox.run(function(ctx) {
return ctx.require('~fastboot/app-factory');
});
// If the application factory couldn't be found, throw an error
if (!AppFactory || typeof AppFactory['default'] !== 'function') {
throw new Error('Failed to load Ember app from app.js, make sure it was built for FastBoot with the `ember fastboot:build` command.');
}
// Otherwise, return a new `Ember.Application` instance
return AppFactory['default']();
}
/**
* @private
*
* Initializes the sandbox by evaluating the Ember app's JavaScript
* code, then retrieves the application factory from the sandbox and creates a new
* `Ember.Application`.
*
* @returns {Ember.Application} the Ember application from the sandbox
*/
retrieveSandboxedApp() {
this.loadAppFiles();
return this.createEmberApp();
}
/**
* Destroys the app and its sandbox.
*/
destroy() {
if (this.app) {
this.app.destroy();
}
this.sandbox = null;
}
/**
* @private
*
* Creates a new `ApplicationInstance` from the sandboxed `Application`.
*
* @returns {Promise<Ember.ApplicationInstance>} instance
*/
buildAppInstance() {
return this.app.boot().then(function(app) {
debug('building instance');
return app.buildInstance();
});
}
/**
* @private
*
* Main funtion that creates the app instance for every `visit` request, boots
* the app instance and then visits the given route and destroys the app instance
* when the route is finished its render cycle.
*
* Ember apps can manually defer rendering in FastBoot mode if they're waiting
* on something async the router doesn't know about. This function fetches
* that promise for deferred rendering from the app.
*
* @param {string} path the URL path to render, like `/photos/1`
* @param {Object} fastbootInfo An object holding per request info
* @param {Object} bootOptions An object containing the boot options that are used by
* by ember to decide whether it needs to do rendering or not.
* @param {Object} result
* @return {Promise<instance>} instance
*/
visitRoute(path, fastbootInfo, bootOptions, result) {
let instance;
return this.buildAppInstance()
.then(appInstance => {
instance = appInstance;
result.instance = instance;
registerFastBootInfo(fastbootInfo, instance);
return instance.boot(bootOptions);
})
.then(() => instance.visit(path, bootOptions))
.then(() => fastbootInfo.deferredPromise)
.then(() => instance);
}
/**
* Creates a new application instance and renders the instance at a specific
* URL, returning a promise that resolves to a {@link Result}. The `Result`
* gives you access to the rendered HTML as well as metadata about the
* request such as the HTTP status code.
*
* If this call to `visit()` is to service an incoming HTTP request, you may
* provide Node's `ClientRequest` and `ServerResponse` objects as options
* (e.g., the `res` and `req` arguments passed to Express middleware). These
* are provided to the Ember application via the FastBoot service.
*
* @param {string} path the URL path to render, like `/photos/1`
* @param {Object} options
* @param {string} [options.html] the HTML document to insert the rendered app into
* @param {Object} [options.metadata] Per request specific data used in the app.
* @param {Boolean} [options.shouldRender] whether the app should do rendering or not. If set to false, it puts the app in routing-only.
* @param {Boolean} [options.disableShoebox] whether we should send the API data in the shoebox. If set to false, it will not send the API data used for rendering the app on server side in the index.html.
* @param {Integer} [options.destroyAppInstanceInMs] whether to destroy the instance in the given number of ms. This is a failure mechanism to not wedge the Node process (See: https://github.com/ember-fastboot/fastboot/issues/90)
* @param {ClientRequest}
* @param {ClientResponse}
* @returns {Promise<Result>} result
*/
visit(path, options) {
let req = options.request;
let res = options.response;
let html = options.html || this.html;
let disableShoebox = options.disableShoebox || false;
let destroyAppInstanceInMs = parseInt(options.destroyAppInstanceInMs, 10);
let shouldRender = (options.shouldRender !== undefined) ? options.shouldRender : true;
let bootOptions = buildBootOptions(shouldRender);
let fastbootInfo = new FastBootInfo(
req,
res,
{ hostWhitelist: this.hostWhitelist, metadata: options.metadata }
);
let doc = bootOptions.document;
let result = new Result({
doc: doc,
html: html,
fastbootInfo: fastbootInfo
});
let destroyAppInstanceTimer;
if (destroyAppInstanceInMs > 0) {
// start a timer to destroy the appInstance forcefully in the given ms.
// This is a failure mechanism so that node process doesn't get wedged if the `visit` never completes.
destroyAppInstanceTimer = setTimeout(function() {
if (result._destroyAppInstance()) {
result.error = new Error('App instance was forcefully destroyed in ' + destroyAppInstanceInMs + 'ms');
}
}, destroyAppInstanceInMs);
}
return this.visitRoute(path, fastbootInfo, bootOptions, result)
.then(() => {
if (!disableShoebox) {
// if shoebox is not disabled, then create the shoebox and send API data
createShoebox(doc, fastbootInfo);
}
})
.catch(error => result.error = error)
.then(() => result._finalize())
.finally(() => {
if (result._destroyAppInstance()) {
if (destroyAppInstanceTimer) {
clearTimeout(destroyAppInstanceTimer);
}
}
});
}
/**
* Given the path to a built Ember app, reads the FastBoot manifest
* information from its `package.json` file.
*/
readPackageJSON(distPath) {
let pkgPath = path.join(distPath, 'package.json');
let file;
try {
file = fs.readFileSync(pkgPath);
} catch (e) {
throw new Error(`Couldn't find ${pkgPath}. You may need to update your version of ember-cli-fastboot.`);
}
let manifest;
let schemaVersion;
let pkg;
try {
pkg = JSON.parse(file);
manifest = pkg.fastboot.manifest;
schemaVersion = pkg.fastboot.schemaVersion;
} catch (e) {
throw new Error(`${pkgPath} was malformed or did not contain a manifest. Ensure that you have a compatible version of ember-cli-fastboot.`);
}
const currentSchemaVersion = FastBootSchemaVersions.latest;
// set schema version to 1 if not defined
schemaVersion = schemaVersion || FastBootSchemaVersions.base;
debug('Current schemaVersion from `ember-cli-fastboot` is %s while latest schema version is %s', (schemaVersion, currentSchemaVersion));
if (schemaVersion > currentSchemaVersion) {
let errorMsg = chalk.bold.red('An incompatible version between `ember-cli-fastboot` and `fastboot` was found. Please update the version of fastboot library that is compatible with ember-cli-fastboot.');
throw new Error(errorMsg);
}
if (schemaVersion < FastBootSchemaVersions.manifestFileArrays) {
// transform app and vendor file to array of files
manifest = this.transformManifestFiles(manifest);
}
let config = pkg.fastboot.config;
let appName = pkg.fastboot.appName;
if (schemaVersion < FastBootSchemaVersions.configExtension) {
// read from the appConfig tree
if (pkg.fastboot.appConfig) {
appName = pkg.fastboot.appConfig.modulePrefix;
config = {};
config[appName] = pkg.fastboot.appConfig;
}
}
debug("reading array of app file paths from manifest");
var appFiles = manifest.appFiles.map(function(appFile) {
return path.join(distPath, appFile);
});
debug("reading array of vendor file paths from manifest");
var vendorFiles = manifest.vendorFiles.map(function(vendorFile) {
return path.join(distPath, vendorFile);
});
return {
appFiles: appFiles,
vendorFiles: vendorFiles,
htmlFile: path.join(distPath, manifest.htmlFile),
moduleWhitelist: pkg.fastboot.moduleWhitelist,
hostWhitelist: pkg.fastboot.hostWhitelist,
config: config,
appName: appName,
};
}
/**
* Function to transform the manifest app and vendor files to an array.
*/
transformManifestFiles(manifest) {
manifest.appFiles = [manifest.appFile];
manifest.vendorFiles = [manifest.vendorFile];
return manifest;
}
}
/*
* Builds an object with the options required to boot an ApplicationInstance in
* FastBoot mode.
*/
function buildBootOptions(shouldRender) {
let doc = new SimpleDOM.Document();
let rootElement = doc.body;
return {
isBrowser: false,
document: doc,
rootElement,
shouldRender
};
}
/*
* Writes the shoebox into the DOM for the browser rendered app to consume.
* Uses a script tag with custom type so that the browser will treat as plain
* text, and not expend effort trying to parse contents of the script tag.
* Each key is written separately so that the browser rendered app can
* parse the specific item at the time it is needed instead of everything
* all at once.
*/
const hasOwnProperty = Object.prototype.hasOwnProperty; // jshint ignore:line
function createShoebox(doc, fastbootInfo) {
let shoebox = fastbootInfo.shoebox;
if (!shoebox) { return; }
for (let key in shoebox) {
if (!hasOwnProperty.call(shoebox, key)) { continue; } // TODO: remove this later #144, ember-fastboot/ember-cli-fastboot/pull/417
let value = shoebox[key];
let textValue = JSON.stringify(value);
textValue = escapeJSONString(textValue);
let scriptText = doc.createRawHTMLSection(textValue);
let scriptEl = doc.createElement('script');
scriptEl.setAttribute('type', 'fastboot/shoebox');
scriptEl.setAttribute('id', `shoebox-${key}`);
scriptEl.appendChild(scriptText);
doc.body.appendChild(scriptEl);
}
}
const JSON_ESCAPE = {
'&': '\\u0026',
'>': '\\u003e',
'<': '\\u003c',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
};
const JSON_ESCAPE_REGEXP = /[\u2028\u2029&><]/g;
function escapeJSONString(string) {
return string.replace(JSON_ESCAPE_REGEXP, function(match) {
return JSON_ESCAPE[match];
});
}
/*
* Builds a new FastBootInfo instance with the request and response and injects
* it into the application instance.
*/
function registerFastBootInfo(info, instance) {
info.register(instance);
}
module.exports = EmberApp;