');
36 | $el.should.equal(inst.$($el));
37 | });
38 | });
39 |
40 | describe('document object', function() {
41 | it('should accept document object', function() {
42 | inst.$(window.document).should.be.instanceOf(Cheerio);
43 | inst.$('document').should.be.instanceOf(Cheerio);
44 | });
45 | describe('#ready', function() {
46 | it('should work on query', function(done) {
47 | inst.$('document').ready(done);
48 | });
49 | it('should work on literal', function(done) {
50 | inst.$(window.document).ready(done);
51 | });
52 | });
53 | it('should fake event binding', function() {
54 | var doc = inst.$(window.document);
55 | doc.on('foo', function(){}).should.equal(doc);
56 | doc.off('foo', function(){}).should.equal(doc);
57 | });
58 | it('should accept as context', function() {
59 | inst = $(window, '
');
60 | inst.$('div', window.document).length.should.equal(1);
61 | });
62 | });
63 | describe('window object', function() {
64 | it('should accept window object', function() {
65 | inst.$(window).should.be.instanceOf(Cheerio);
66 | });
67 | it('should fake event binding', function() {
68 | var doc = inst.$(window);
69 | doc.on('foo', function(){}).should.equal(doc);
70 | doc.off('foo', function(){}).should.equal(doc);
71 | });
72 | it('should accept as context', function() {
73 | inst = $(window, '
');
74 | inst.$('div', window).length.should.equal(1);
75 | });
76 | });
77 |
78 | describe('known caching', function() {
79 | it('should cache root', function() {
80 | inst = $(window, '');
81 | inst.$('html', window).should.equal(inst.$(':root', window));
82 | });
83 | it('should cache head object', function() {
84 | inst = $(window, '');
85 | inst.$('head', window).should.equal(inst.$('head', window));
86 |
87 | inst = $(window, '');
88 | inst.$('head', window).should.equal(inst.$('head', window));
89 | });
90 | it('should cache body object', function() {
91 | inst = $(window, '');
92 | inst.$('body', window).should.equal(inst.$('body', window));
93 |
94 | inst = $(window, '');
95 | inst.$('body', window).should.equal(inst.$('body', window));
96 | });
97 | it('should not fail if there are no such objects', function() {
98 | inst.$('html', window).length.should.equal(0);
99 | inst.$('head', window).length.should.equal(0);
100 | inst.$('body', window).length.should.equal(0);
101 |
102 | inst = $(window, '
');
103 | inst.$('html', window).length.should.equal(0);
104 | inst.$('head', window).length.should.equal(0);
105 | inst.$('body', window).length.should.equal(0);
106 | });
107 | });
108 |
109 | describe('$.fn', function() {
110 | it('should allow augmentation', function() {
111 | inst = $(window, '
');
112 | window.$.fn.should.equal(inst.$.fn);
113 | inst.$.fn.foo = function() {
114 | return 'success';
115 | };
116 | inst.$('div').foo().should.equal('success');
117 | should.not.exist(inst.$('div').bar);
118 |
119 | inst.$.fn.bar = function() {
120 | return 'success';
121 | };
122 | inst.$('div').bar().should.equal('success');
123 | inst.$('div').find('span').bar().should.equal('success');
124 |
125 | inst = $(window, '
');
126 | should.not.exist(inst.$('div').foo);
127 | should.not.exist(inst.$('div').bar);
128 | });
129 | });
130 |
131 | describe('#each', function() {
132 | it('should iterate arrays', function() {
133 | var spy = this.spy(function(i, value) {
134 | this.should.equal(value);
135 | value.should.equal((i+1)*10);
136 | });
137 | inst.$.each([10, 20, 30, 40], spy);
138 | spy.callCount.should.equal(4);
139 | });
140 | it('should iterate objects', function() {
141 | var spy = this.spy(function(key, value) {
142 | this.should.equal(value);
143 | if (key === 'a') {
144 | value.should.equal(10);
145 | } else if (key === 'b') {
146 | value.should.equal(20);
147 | } else if (key === 'c') {
148 | value.should.equal(30);
149 | } else if (key === 'd') {
150 | value.should.equal(40);
151 | } else {
152 | throw new Error();
153 | }
154 | });
155 | inst.$.each({'a':10, 'b':20, 'c':30, 'd':40}, spy);
156 | spy.callCount.should.equal(4);
157 | });
158 | it('should terminate early', function() {
159 | var spy = this.spy(function(i, value) {
160 | this.should.equal(value);
161 | if (i === 2) {
162 | return false;
163 | }
164 | });
165 | inst.$.each([10, 20, 30, 40], spy);
166 | spy.callCount.should.equal(3);
167 | });
168 | });
169 |
170 | describe('#extend', function() {
171 | it('should extend the object', function() {
172 | inst.$.extend({}, {'foo': 'bar'}, {'baz': 'bat'}).should.eql({
173 | 'foo': 'bar',
174 | 'baz': 'bat'
175 | });
176 | });
177 | it('should handle deep parameter', function() {
178 | inst.$.extend(true, {}, {'foo': [1,2,3,4], 'bat': {'bat': true}}, {'foo': [3,4], 'bat': {baz: 'bar'}}).should.eql({
179 | 'foo': [3,4,3,4],
180 | 'bat': {bat: true, baz: 'bar'}
181 | });
182 | });
183 | });
184 | describe('#globalEval', function() {
185 | it('should execute eval', function() {
186 | inst.$.globalEval('foo');
187 | window.eval.should.have.been.calledWith('foo');
188 | });
189 | });
190 | describe('#grep', function() {
191 | it('should filter', function() {
192 | inst.$.grep([1,2,3], function(value) { return value > 1; }).should.eql([2,3]);
193 | });
194 | });
195 | describe('#inArray', function() {
196 | it('should look up elements', function() {
197 | inst.$.inArray(1, [1,2,3]).should.equal(0);
198 | inst.$.inArray(2, [1,2,3]).should.equal(1);
199 | });
200 | it('should handle missing', function() {
201 | inst.$.inArray(4, [1,2,3]).should.equal(-1);
202 | });
203 | it('should handle fromIndex', function() {
204 | inst.$.inArray(1, [1,2,3], 0).should.equal(0);
205 | inst.$.inArray(1, [1,2,3], 1).should.equal(-1);
206 | });
207 | });
208 |
209 | describe('#isArray', function() {
210 | it('should handle arrays', function() {
211 | inst.$.isArray([]).should.be.true;
212 | });
213 | it('should handle non-arrays', function() {
214 | inst.$.isArray({}).should.be.false;
215 | });
216 | });
217 | describe('#isFunction', function() {
218 | it('should handle functions', function() {
219 | inst.$.isFunction(function() {}).should.be.true;
220 | });
221 | it('should handle non-functions', function() {
222 | inst.$.isFunction({}).should.be.false;
223 | });
224 | });
225 | describe('#isNumeric', function() {
226 | it('should handle number', function() {
227 | inst.$.isNumeric(4).should.be.true;
228 | inst.$.isNumeric(new Number(4)).should.be.true;
229 | });
230 | it('should handle non-number', function() {
231 | inst.$.isNumeric({}).should.be.false;
232 | });
233 | });
234 | describe('#isEmptyObject', function() {
235 | it('should handle empty objects', function() {
236 | inst.$.isEmptyObject({}).should.be.true;
237 | });
238 | it('should handle non-empty objects', function() {
239 | inst.$.isEmptyObject({foo: true}).should.be.false;
240 | inst.$.isEmptyObject([]).should.be.false;
241 | inst.$.isEmptyObject(1).should.be.false;
242 | inst.$.isEmptyObject(window).should.be.false;
243 | inst.$.isEmptyObject(window.document).should.be.false;
244 | inst.$.isEmptyObject(inst.$(window.document)).should.be.false;
245 | });
246 | });
247 | describe('#isPlainObject', function() {
248 | it('should handle plain objects', function() {
249 | inst.$.isPlainObject({}).should.be.true;
250 | inst.$.isPlainObject({foo: true}).should.be.true;
251 | });
252 | it('should handle non-plain objects', function() {
253 | inst.$.isPlainObject(1).should.be.false;
254 | inst.$.isPlainObject(window).should.be.false;
255 | inst.$.isPlainObject(window.document).should.be.false;
256 | inst.$.isPlainObject(inst.$(window.document)).should.be.false;
257 | });
258 | });
259 | describe('#isWindow', function() {
260 | it('should handle window', function() {
261 | inst.$.isWindow(window).should.be.true;
262 | });
263 | it('should handle non-window', function() {
264 | inst.$.isWindow({}).should.be.false;
265 | });
266 | });
267 | describe('#type', function() {
268 | it('should handle "undefined"', function() {
269 | inst.$.type(undefined).should.equal('undefined');
270 | inst.$.type().should.equal('undefined');
271 | inst.$.type(window.notDefined).should.equal('undefined');
272 | });
273 | it('should handle "null"', function() {
274 | inst.$.type(null).should.equal('null');
275 | });
276 | it('should handle "boolean"', function() {
277 | inst.$.type(true).should.equal('boolean');
278 | inst.$.type(new Boolean()).should.equal('boolean');
279 | });
280 | it('should handle "number"', function() {
281 | inst.$.type(3).should.equal('number');
282 | inst.$.type(new Number(3)).should.equal('number');
283 | });
284 | it('should handle "string"', function() {
285 | inst.$.type("test").should.equal('string');
286 | inst.$.type(new String("test")).should.equal('string');
287 | });
288 | it('should handle "function"', function() {
289 | inst.$.type(function(){}).should.equal('function');
290 | });
291 | it('should handle "array"', function() {
292 | inst.$.type([]).should.equal('array');
293 | });
294 | it('should handle "array"', function() {
295 | inst.$.type(new Array()).should.equal('array');
296 | });
297 | it('should handle "date"', function() {
298 | inst.$.type(new Date()).should.equal('date');
299 | });
300 | it('should handle "error"', function() {
301 | inst.$.type(new Error()).should.equal('error');
302 | });
303 | it('should handle "regexp"', function() {
304 | inst.$.type(/test/).should.equal('regexp');
305 | });
306 | it('should handle "window"', function() {
307 | inst.$.type(window).should.equal('window');
308 | });
309 | });
310 |
311 | describe('#merge', function() {
312 | it('should merge arrays', function() {
313 | var arr = [1,2,3];
314 | inst.$.merge(arr, [4,5]).should.equal(arr);
315 | arr.should.eql([1,2,3,4,5]);
316 | });
317 | });
318 |
319 | describe('#now', function() {
320 | it('should return current time', function() {
321 | var base = Date.now();
322 | inst.$.now().should.equal(base);
323 | this.clock.tick(123);
324 | inst.$.now().should.equal(base + 123);
325 | });
326 | });
327 |
328 | describe('#param', function() {
329 | it('should return params', function() {
330 | inst.$.param({foo: ' bar', baz: 'bat='}).should.equal('foo=%20bar&baz=bat%3D');
331 | });
332 | });
333 |
334 | describe('#proxy', function() {
335 | it('should bind function', function() {
336 | var context = {},
337 | spy = this.spy();
338 | inst.$.proxy(spy, context, 1, 2)();
339 | spy.should.have.been.calledOn(context);
340 | spy.should.have.been.calledWith(1, 2);
341 | });
342 | it('should bind key function', function() {
343 | var spy = this.spy(),
344 | context = {key: spy};
345 |
346 | inst.$.proxy(context, 'key', 1, 2)();
347 | spy.should.have.been.calledOn(context);
348 | spy.should.have.been.calledWith(1, 2);
349 | });
350 | });
351 |
352 | describe('#trim', function() {
353 | it('should trim', function() {
354 | inst.$.trim(' foo ').should.equal('foo');
355 | });
356 | });
357 | });
358 |
--------------------------------------------------------------------------------
/lib/page.js:
--------------------------------------------------------------------------------
1 | var _ = require('lodash'),
2 | async = require('async'),
3 | Contextify = require('contextify'),
4 | dom = require('./dom'),
5 | Exec = require('./exec'),
6 | fs = require('fs'),
7 | jQuery = require('./jquery'),
8 | path = require('path');
9 |
10 | var pageCache = {},
11 | scriptCache = {},
12 | windowId = 0;
13 |
14 | // Load the client mode scripts.
15 | // Load sync here as it's only done on init and we are loading from a known local file. This
16 | // is somewhat akin to a deferred require in that manner.
17 | var ClientScripts = [
18 | __dirname + '/bootstrap/window.js'
19 | ].map(function(href) {
20 | var src = fs.readFileSync(href);
21 | return Contextify.createScript(src.toString(), href);
22 | });
23 |
24 | module.exports = exports = function(options) {
25 | var context = new Window(),
26 | _id = windowId++,
27 |
28 | // We need to set this up here to ensure that the defineProperty propagates properly to the
29 | // context
30 | // https://github.com/joyent/node/commit/3c5ea410ca56da3d4785e2563cb2724364669fd2
31 | locationPreInit = dom.location.preInit(context);
32 |
33 | context = Contextify.createContext(context);
34 |
35 | var host = options.host || 'localhost',
36 | protocol = options.protocol || 'http:',
37 | callback = options.callback,
38 | emitCallbacks = [],
39 | scripts,
40 |
41 | exec = Exec.create(_callback),
42 | pending = exec.pending,
43 | window = context.getGlobal(),
44 | requestId = 0,
45 | pageCount = 1, // Number of times this page has navigated
46 | $,
47 |
48 | status = 200;
49 |
50 | // Primary external API
51 | var FruitLoops = {
52 | id: _id,
53 | start: process.hrtime(),
54 |
55 | hrtime: function(start) {
56 | // The c code impl of hrtime expects a literal number of arguments.
57 | if (start) {
58 | return process.hrtime(start);
59 | } else {
60 | return process.hrtime();
61 | }
62 | },
63 |
64 | redirect: function(url) {
65 | _callback(undefined, {redirect: url});
66 |
67 | // Cancel futher exec
68 | throw new exec.RedirectError(url);
69 | },
70 | statusCode: function(_status) {
71 | status = _status;
72 | },
73 |
74 | emit: function(after) {
75 | function checkComplete() {
76 | if (isComplete()) {
77 | var associatedRequestId = requestId;
78 | setImmediate(function() {
79 | // Avoid a race condtion where pooled requests may come in while we still have
80 | // pending emit calls. This will generally only happen for very chatty emit callers.
81 | if (requestId === associatedRequestId) {
82 | emit();
83 | }
84 | });
85 | }
86 | }
87 | function isComplete() {
88 | if (after === 'ajax') {
89 | return $.ajax.allComplete();
90 | } else if (after === 'events') {
91 | return !pending.pending();
92 | } else {
93 | // If we are in immediate mode (i.e. the default behavior) then we
94 | // always consider ourselves complete.
95 | return true;
96 | }
97 | }
98 |
99 | if (!callback) {
100 | // This should be considered a framework error as the pending tracker
101 | // should prevent this from happening.
102 | throw new Error('Emit outside of request: ' + _id);
103 | }
104 |
105 | if (after === 'ajax') {
106 | $.ajax.once('complete', checkComplete);
107 | } else if (after === 'events') {
108 | pending.on('pop', checkComplete);
109 | }
110 |
111 | // If it doesn't look like anything is running or we have an explicit emit
112 | // then defer the exec and emit if nothing comes into the queue for the remainder
113 | // of the tick.
114 | if (isComplete()) {
115 | setImmediate(function() {
116 | checkComplete();
117 | });
118 | }
119 | },
120 | onEmit: function(callback) {
121 | emitCallbacks.push(callback);
122 | },
123 |
124 | loadInContext: function(href, callback) {
125 | try {
126 | if (options.resolver) {
127 | href = options.resolver(href, page);
128 | } else {
129 | href = path.resolve(path.join(path.dirname(options.index), href));
130 | }
131 | } catch (err) {
132 | return callback(err);
133 | }
134 |
135 | var loaded = pending.wrap('load', href, function(err) {
136 | if (!context) {
137 | // We've been disposed, but there was something on the setImmediate list,
138 | // silently ignore
139 | return;
140 | }
141 | if (err) {
142 | return callback(err);
143 | }
144 |
145 | exec.exec(function() {
146 | script.runInContext(context);
147 |
148 | callback && callback();
149 | }, callback);
150 | });
151 |
152 | var script = scriptCache[href];
153 | if (!script) {
154 | fs.readFile(href, function(err, src) {
155 | if (!context) {
156 | // Another disposed race condition. NOP
157 | return;
158 | }
159 |
160 | if (err) {
161 | return loaded(err);
162 | }
163 |
164 | try {
165 | script = Contextify.createScript(src.toString(), href);
166 | } catch (err) {
167 | return loaded(err);
168 | }
169 |
170 | if (options.cacheResources) {
171 | scriptCache[href] = script;
172 | }
173 |
174 | // Pop off the stack here so any code that might cause an Error.stack
175 | // retain doesn't retain on the fs buffers, etc. This is a horrible reason
176 | // to do this but it does help isolate the host and client code.
177 | setImmediate(loaded);
178 | });
179 | } else {
180 | setImmediate(loaded);
181 | }
182 | }
183 | };
184 |
185 | window.FruitLoops = FruitLoops;
186 |
187 | ClientScripts.forEach(function(script) {
188 | script.runInContext(context);
189 | });
190 |
191 | var location = dom.location(window, protocol + '//' + host + options.path);
192 |
193 | var toReset = [
194 | dom.performance(window),
195 | dom.storage(window, 'localStorage'),
196 | dom.storage(window, 'sessionStorage'),
197 | ];
198 | var toCleanup = toReset.concat([
199 | dom.async(window, exec),
200 | dom.console(window, exec),
201 | dom.dynamic(window, options),
202 | dom.history(window),
203 | dom.navigator(window, options),
204 | locationPreInit,
205 | location
206 | ]);
207 |
208 | function emit() {
209 | if (!callback) {
210 | // A pending emit that has already completed
211 | return;
212 | }
213 |
214 | $.$('script').remove();
215 |
216 | // Emit error if any of these fail.
217 | try {
218 | emitCallbacks.forEach(function(callback) {
219 | callback();
220 | });
221 | } catch (err) {
222 | return _callback(exec.processError(err));
223 | }
224 |
225 | // Inline any script content that we may have received
226 | // We are using text here for two reasons. The first is that it ensures that content like
227 | // doesn't create multiple elements and the second is that it removes parser overhead
228 | // when constructing the cheerio object due to the parser iterating ove the JSON content itself.
229 | var serverCache = $.$('');
230 | serverCache.text('var $serverCache = ' + $.ajax.toJSON() + ';');
231 | $.$('body').append(serverCache);
232 |
233 | // Ensure sure that we have all of our script content and that it it at the end of the document
234 | // this has two benefits: the body element may be rendered to directly and this will push
235 | // all of the scripts after the content elements
236 | $.$('body').append(scripts);
237 |
238 | options.finalize && options.finalize(page);
239 |
240 | // And output the thing
241 | _callback(undefined, $.root.html());
242 | }
243 |
244 | function _callback(err, data) {
245 | if (!callback) {
246 | // This should be considered a framework error as the pending tracker
247 | // should prevent this from happening.
248 | var hint = err ? (err.stack || err.toString()) : data.toString().substr(0, 100);
249 | throw new Error('Emit outside of request: ' + _id + ' ' + hint);
250 | }
251 |
252 | var minimumCache,
253 | incompleteTasks = pending.pending(),
254 | taskLog = pending.log(),
255 | maxTasks = pending.maxPending();
256 | if ($) {
257 | minimumCache = $.ajax.minimumCache();
258 | }
259 |
260 | // Kill off anything that may be pending as well as all logs, etc
261 | pending.reset();
262 | if ($ && $.ajax) {
263 | $.ajax.reset();
264 | }
265 |
266 | // Invalidate our callback so if there is a bug and future callback attempts occur we will
267 | // fail using the check above.
268 | var _callback = callback;
269 | callback = undefined;
270 |
271 | _callback(err, data, {
272 | status: status,
273 | cache: minimumCache,
274 | pageId: _id,
275 | pageCount: pageCount,
276 |
277 | taskLog: taskLog,
278 | incompleteTasks: incompleteTasks,
279 | maxTasks: maxTasks
280 | });
281 |
282 | status = 200;
283 | }
284 |
285 | function loadPage(src) {
286 | $ = page.$ = jQuery(window, src, exec, options);
287 | toCleanup.push($);
288 |
289 | pending.push('beforeExec', 1);
290 | if (options.beforeExec) {
291 | setImmediate(function() {
292 | options.beforeExec(page, loadScripts);
293 | });
294 | } else {
295 | loadScripts();
296 | }
297 | }
298 | function loadScripts(err) {
299 | if (err) {
300 | return _callback(err);
301 | }
302 |
303 | pending.pop('beforeExec', 1);
304 |
305 | scripts = $.$('script');
306 |
307 | var loaders = _.map(scripts, function(script, i) {
308 | return pending.wrap('script', i, function(callback) {
309 |
310 | var el = $.$(script),
311 | text = el.text(),
312 | external = el.attr('src');
313 |
314 | if (external) {
315 | FruitLoops.loadInContext(external, callback);
316 | } else {
317 | page.runScript(text, callback);
318 | }
319 | });
320 | });
321 |
322 | async.series(loaders, function(err) {
323 | if (err) {
324 | if (err._redirect) {
325 | return;
326 | }
327 |
328 | _callback(err);
329 | } else {
330 | try {
331 | options.loaded && options.loaded(page);
332 | } catch (err) {
333 | if (err._redirect) {
334 | return;
335 | } else {
336 | _callback(err);
337 | }
338 | }
339 | }
340 | });
341 | }
342 |
343 | var page = new Page();
344 | _.extend(page, {
345 | id: _id,
346 | window: window,
347 | $: $,
348 | exec: _.bind(exec.exec, exec),
349 | rewriteStack: _.bind(exec.rewriteStack, exec),
350 | runScript: function(text, callback) {
351 | exec.exec(function() {
352 | try {
353 | context.run(text, text);
354 | } catch (err) {
355 | var stack = err.stack,
356 | toThrow = /SyntaxError/.test(stack) ? new SyntaxError(err.message) : new Error(err.message);
357 | toThrow.stack = stack.split(/\n/)[0] + '\n\nInline Script:\n\t';
358 | toThrow._redirect = err._redirect;
359 | throw toThrow;
360 | }
361 |
362 | callback();
363 | }, callback);
364 | },
365 |
366 | emit: FruitLoops.emit,
367 | pending: pending,
368 |
369 | metadata: options.metadata,
370 |
371 | dispose: function() {
372 | // Reset anything pending should we happen to be disposed of outside of an emit response
373 | pending.reset();
374 | if ($ && $.ajax) {
375 | $.ajax.reset();
376 | }
377 |
378 | _.each(toCleanup, function(toCleanup) {
379 | toCleanup.dispose();
380 | });
381 |
382 | emitCallbacks.length = 0;
383 |
384 | options = callback =
385 | window = context =
386 | toReset = toCleanup = location = $ =
387 | window.FruitLoops =
388 | emitCallbacks = scripts =
389 | page.metadata = page.window = page.emit = page.$ = undefined;
390 | },
391 |
392 | navigate: function(path, metadata, _callback) {
393 | requestId++;
394 | pageCount++;
395 | FruitLoops.start = process.hrtime();
396 |
397 | callback = _callback || metadata;
398 | page.metadata = _callback ? metadata : undefined;
399 |
400 | _.each(toReset, function(toReset) {
401 | toReset.reset();
402 | });
403 |
404 | location.reset(protocol + '//' + host + path);
405 | }
406 | });
407 |
408 | if (pageCache[options.index]) {
409 | loadPage(pageCache[options.index]);
410 | } else {
411 | fs.readFile(options.index, function(err, src) {
412 | if (err) {
413 | return _callback(err);
414 | }
415 |
416 | // Buffer -> String
417 | src = src.toString();
418 |
419 | if (options.cacheResources) {
420 | pageCache[options.index] = src;
421 | }
422 |
423 | loadPage(src);
424 | });
425 | }
426 |
427 | return page;
428 | };
429 |
430 |
431 | function Window() {
432 | }
433 |
434 | function Page() {
435 | }
436 |
--------------------------------------------------------------------------------
/test/pool.js:
--------------------------------------------------------------------------------
1 | var _ = require('lodash'),
2 | FruitLoops = require('../lib'),
3 | fs = require('fs');
4 |
5 | describe('#pool', function() {
6 | var pool;
7 | afterEach(function() {
8 | pool && pool.dispose();
9 | pool = undefined;
10 | });
11 |
12 | it('should serve pages on navigate', function(done) {
13 | var emitCalled;
14 |
15 | pool = FruitLoops.pool({
16 | poolSize: 2,
17 | host: 'winning',
18 | index: __dirname + '/artifacts/pool-page.html',
19 | loaded: function(page) {
20 | page.window.$.should.exist;
21 | page.window.$serverSide.should.be.true;
22 | page.window.loadedCallback = true;
23 | },
24 | navigated: function(page, existingPage) {
25 | existingPage.should.be.false;
26 | page.metadata.should.equal('meta!');
27 |
28 | page.window.navigated();
29 | page.emit('events');
30 | },
31 | callback: function() {
32 | throw new Error('should not be called');
33 | },
34 | cleanup: function() {
35 | emitCalled.should.be.true;
36 | done();
37 | }
38 | });
39 | pool.navigate('/bar', 'meta!', function(err, html) {
40 | emitCalled = true;
41 | should.not.exist(err);
42 | html.should.match(/"location-info">http:\/\/winning\/bar true<\/div>/);
43 | });
44 | });
45 | it('should create up to poolSize VMs', function(done) {
46 | this.clock.restore();
47 |
48 | function _done() {
49 | returned++;
50 | if (returned >= 2) {
51 | _.keys(ids).length.should.equal(2);
52 |
53 | done();
54 | }
55 | }
56 |
57 | var ids = {},
58 | returned = 0;
59 |
60 | pool = FruitLoops.pool({
61 | poolSize: 2,
62 | host: 'winning',
63 | index: __dirname + '/artifacts/pool-page.html',
64 | loaded: function(page) {
65 | page.window.$.should.exist;
66 | page.window.$serverSide.should.be.true;
67 | page.window.loadedCallback = true;
68 |
69 | ids[page.window.FruitLoops.id] = true;
70 | },
71 | navigated: function(page, existingPage) {
72 | existingPage.should.be.false;
73 |
74 | page.window.navigated();
75 | setTimeout(function() {
76 | page.emit('events');
77 | }, 10);
78 | },
79 | callback: function() {
80 | throw new Error('should not be called');
81 | }
82 | });
83 | pool.navigate('/bar', function(err, html) {
84 | should.not.exist(err);
85 | html.should.match(/"location-info">http:\/\/winning\/bar true<\/div>/);
86 |
87 | _done();
88 | });
89 | pool.navigate('/baz', function(err, html) {
90 | should.not.exist(err);
91 | html.should.match(/"location-info">http:\/\/winning\/baz true<\/div>/);
92 |
93 | _done();
94 | });
95 | });
96 | it('should queue requests above the pool size', function(done) {
97 | this.clock.restore();
98 |
99 | function _done() {
100 | returned++;
101 | if (returned >= 3) {
102 | _.keys(ids).length.should.equal(2);
103 |
104 | done();
105 | }
106 | }
107 |
108 | var ids = {},
109 | navigated = 0,
110 | returned = 0;
111 |
112 | pool = FruitLoops.pool({
113 | poolSize: 2,
114 | host: 'winning',
115 | index: __dirname + '/artifacts/pool-page.html',
116 | loaded: function(page) {
117 | page.window.$.should.exist;
118 | page.window.$serverSide.should.be.true;
119 | page.window.loadedCallback = true;
120 |
121 | ids[page.window.FruitLoops.id] = true;
122 | },
123 | navigated: function(page, existingPage) {
124 | existingPage.should.equal(++navigated > 2);
125 |
126 | page.window.navigated();
127 | setTimeout(function() {
128 | page.emit('events');
129 | }, 10);
130 | },
131 | callback: function() {
132 | throw new Error('should not be called');
133 | }
134 | });
135 | pool.navigate('/bar', function(err, html, meta) {
136 | should.not.exist(err);
137 | html.should.match(/"location-info">http:\/\/winning\/bar true<\/div>/);
138 | meta.status.should.equal(404);
139 |
140 | _done();
141 | });
142 | pool.navigate('/baz', function(err, html, meta) {
143 | should.not.exist(err);
144 | html.should.match(/"location-info">http:\/\/winning\/baz true<\/div>/);
145 | meta.status.should.equal(200);
146 |
147 | _done();
148 | });
149 | pool.navigate('/bat', function(err, html, meta) {
150 | should.not.exist(err);
151 | html.should.match(/"location-info">http:\/\/winning\/bat true<\/div>/);
152 | meta.status.should.equal(200);
153 |
154 | pool.info().should.eql({queued: 0, pages: 2, free: 1});
155 |
156 | _done();
157 | });
158 | });
159 | it('should reject requests above the queue size', function(done) {
160 | this.clock.restore();
161 |
162 | function _done() {
163 | returned++;
164 | if (returned >= 3) {
165 | _.keys(ids).length.should.equal(1);
166 |
167 | done();
168 | }
169 | }
170 |
171 | var ids = {},
172 | navigated = 0,
173 | returned = 0;
174 |
175 | pool = FruitLoops.pool({
176 | poolSize: 1,
177 | maxQueue: 1,
178 | host: 'winning',
179 | index: __dirname + '/artifacts/pool-page.html',
180 | loaded: function(page) {
181 | page.window.$.should.exist;
182 | page.window.$serverSide.should.be.true;
183 | page.window.loadedCallback = true;
184 |
185 | ids[page.window.FruitLoops.id] = true;
186 | },
187 | navigated: function(page, existingPage) {
188 | existingPage.should.equal(++navigated > 1);
189 |
190 | page.window.navigated();
191 | setTimeout(function() {
192 | page.emit('events');
193 | }, 10);
194 | },
195 | callback: function() {
196 | throw new Error('should not be called');
197 | }
198 | });
199 | pool.navigate('/bar', function(err, html, meta) {
200 | should.not.exist(err);
201 | html.should.match(/"location-info">http:\/\/winning\/bar true<\/div>/);
202 | meta.status.should.equal(404);
203 |
204 | _done();
205 | });
206 | pool.navigate('/baz', function(err, html, meta) {
207 | should.not.exist(err);
208 | html.should.match(/"location-info">http:\/\/winning\/baz true<\/div>/);
209 | meta.status.should.equal(200);
210 |
211 | _done();
212 | });
213 | pool.navigate('/bat', function(err, html, meta) {
214 | err.should.match(/EQUEUEFULL/);
215 | should.not.exist(html);
216 | should.not.exist(meta);
217 |
218 | pool.info().should.eql({queued: 1, pages: 1, free: 0});
219 |
220 | _done();
221 | });
222 | });
223 | it('should timeout requests in queue', function(done) {
224 | this.clock.restore();
225 |
226 | function _done() {
227 | returned++;
228 | if (returned >= 2) {
229 | _.keys(ids).length.should.equal(1);
230 |
231 | done();
232 | }
233 | }
234 |
235 | var ids = {},
236 | navigated = 0,
237 | returned = 0;
238 |
239 | pool = FruitLoops.pool({
240 | poolSize: 1,
241 | queueTimeout: 10,
242 | host: 'winning',
243 | index: __dirname + '/artifacts/pool-page.html',
244 | loaded: function(page) {
245 | page.window.$.should.exist;
246 | page.window.$serverSide.should.be.true;
247 | page.window.loadedCallback = true;
248 |
249 | ids[page.window.FruitLoops.id] = true;
250 | },
251 | navigated: function(page, existingPage) {
252 | existingPage.should.equal(++navigated > 1);
253 |
254 | page.window.navigated();
255 | setTimeout(function() {
256 | page.emit('events');
257 | }, 100);
258 | },
259 | callback: function() {
260 | throw new Error('should not be called');
261 | }
262 | });
263 | pool.navigate('/bar', function(err, html, meta) {
264 | should.not.exist(err);
265 | html.should.match(/"location-info">http:\/\/winning\/bar true<\/div>/);
266 | meta.status.should.equal(404);
267 |
268 | _done();
269 | });
270 | pool.navigate('/bat', function(err, html, meta) {
271 | err.should.match(/EQUEUETIMEOUT/);
272 | should.not.exist(html);
273 | should.not.exist(meta);
274 |
275 | pool.info().should.eql({queued: 0, pages: 1, free: 0});
276 |
277 | _done();
278 | });
279 | });
280 | it('should not-timeout requests in queue', function(done) {
281 | this.clock.restore();
282 |
283 | function _done() {
284 | returned++;
285 | if (returned >= 2) {
286 | _.keys(ids).length.should.equal(1);
287 |
288 | done();
289 | }
290 | }
291 |
292 | var ids = {},
293 | navigated = 0,
294 | returned = 0;
295 |
296 | pool = FruitLoops.pool({
297 | poolSize: 1,
298 | queueTimeout: 100,
299 | host: 'winning',
300 | index: __dirname + '/artifacts/pool-page.html',
301 | loaded: function(page) {
302 | page.window.$.should.exist;
303 | page.window.$serverSide.should.be.true;
304 | page.window.loadedCallback = true;
305 |
306 | ids[page.window.FruitLoops.id] = true;
307 | },
308 | navigated: function(page, existingPage) {
309 | existingPage.should.equal(++navigated > 1);
310 |
311 | page.window.navigated();
312 | setTimeout(function() {
313 | page.emit('events');
314 | }, 10);
315 | },
316 | callback: function() {
317 | throw new Error('should not be called');
318 | }
319 | });
320 | pool.navigate('/bar', function(err, html, meta) {
321 | should.not.exist(err);
322 | html.should.match(/"location-info">http:\/\/winning\/bar true<\/div>/);
323 | meta.status.should.equal(404);
324 |
325 | _done();
326 | });
327 | pool.navigate('/bat', function(err, html, meta) {
328 | should.not.exist(err);
329 | html.should.match(/"location-info">http:\/\/winning\/bat true<\/div>/);
330 | meta.status.should.equal(200);
331 |
332 | pool.info().should.eql({queued: 0, pages: 1, free: 0});
333 |
334 | _done();
335 | });
336 | });
337 | it('should invalidate pages on error', function(done) {
338 | this.clock.restore();
339 |
340 | function _done() {
341 | returned++;
342 | if (returned >= 3) {
343 | _.keys(ids).length.should.equal(3);
344 |
345 | setImmediate(function() {
346 | pool.info().should.eql({
347 | queued: 0,
348 | pages: 0,
349 | free: 0
350 | });
351 |
352 | done();
353 | });
354 | }
355 | }
356 |
357 | var ids = {},
358 | returned = 0;
359 |
360 | pool = FruitLoops.pool({
361 | poolSize: 2,
362 | host: 'winning',
363 | index: __dirname + '/artifacts/pool-page.html',
364 | loaded: function(page) {
365 | page.window.$.should.exist;
366 | page.window.$serverSide.should.be.true;
367 | page.window.loadedCallback = true;
368 |
369 | ids[page.window.FruitLoops.id] = true;
370 | },
371 | navigated: function(page, existingPage) {
372 | existingPage.should.be.false;
373 |
374 | page.window.navigated();
375 | page.window.setTimeout(function() {
376 | throw new Error('Errored!');
377 | }, 10);
378 | },
379 | callback: function() {
380 | throw new Error('should not be called');
381 | }
382 | });
383 | pool.navigate('/bar', function(err, html) {
384 | err.toString().should.match(/Errored!/);
385 | _done();
386 | });
387 | pool.navigate('/baz', function(err, html) {
388 | err.toString().should.match(/Errored!/);
389 | _done();
390 | });
391 | pool.navigate('/bat', function(err, html) {
392 | err.toString().should.match(/Errored!/);
393 | _done();
394 | });
395 | });
396 | it('should reset on watch change', function(done) {
397 | this.clock.restore();
398 |
399 | var watchCallback;
400 | this.stub(fs, 'watch', function(fileName, options, callback) {
401 | watchCallback = callback;
402 | return { close: function() {} };
403 | });
404 |
405 | var ids = {};
406 |
407 | pool = FruitLoops.pool({
408 | poolSize: 2,
409 | host: 'winning',
410 | index: __dirname + '/artifacts/script-page.html',
411 | loaded: function(page) {
412 | ids[page.window.FruitLoops.id] = true;
413 | },
414 | navigated: function(page, existingPage) {
415 | existingPage.should.be.false;
416 |
417 | ids[page.window.FruitLoops.id] = true;
418 |
419 | page.window.emit();
420 | }
421 | });
422 | pool.navigate('/bar', function(err, html) {
423 | setImmediate(function() {
424 | watchCallback();
425 |
426 | pool.navigate('/baz', function(err, html) {
427 | _.keys(ids).length.should.equal(2);
428 | done();
429 | });
430 | });
431 | });
432 | });
433 | it('should error with incorrect args', function() {
434 | should.Throw(function() {
435 | FruitLoops.pool({
436 | loaded: function(page) {
437 | throw new Error('should not be called');
438 | },
439 | navigated: function(page) {
440 | throw new Error('should not be called');
441 | },
442 | callback: function() {
443 | throw new Error('should not be called');
444 | }
445 | });
446 | }, Error, /Must pass in a poolSize value/);
447 | });
448 | });
449 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ***
2 | # NOTICE:
3 |
4 | ## This repository has been archived and is not supported.
5 |
6 | [](http://unmaintained.tech/)
7 | ***
8 | NOTICE: SUPPORT FOR THIS PROJECT HAS ENDED
9 |
10 | This projected was owned and maintained by Walmart. This project has reached its end of life and Walmart no longer supports this project.
11 |
12 | We will no longer be monitoring the issues for this project or reviewing pull requests. You are free to continue using this project under the license terms or forks of this project at your own risk. This project is no longer subject to Walmart's bug bounty program or other security monitoring.
13 |
14 |
15 | ## Actions you can take
16 |
17 | We recommend you take the following action:
18 |
19 | * Review any configuration files used for build automation and make appropriate updates to remove or replace this project
20 | * Notify other members of your team and/or organization of this change
21 | * Notify your security team to help you evaluate alternative options
22 |
23 | ## Forking and transition of ownership
24 |
25 | For [security reasons](https://www.theregister.co.uk/2018/11/26/npm_repo_bitcoin_stealer/), Walmart does not transfer the ownership of our primary repos on Github or other platforms to other individuals/organizations. Further, we do not transfer ownership of packages for public package management systems.
26 |
27 | If you would like to fork this package and continue development, you should choose a new name for the project and create your own packages, build automation, etc.
28 |
29 | Please review the licensing terms of this project, which continue to be in effect even after decommission.
30 |
31 | # Fruit Loops
32 |
33 | Provides a performant jQuery-like environment for rendering of client-side SPA application within node servers.
34 |
35 | ## Example
36 |
37 | ```javascript
38 | FruitLoops.page({
39 | index: __dirname + '/index.html',
40 |
41 | host: 'www.github.com',
42 | path: '/foo/bar',
43 |
44 | resolver: function(href, page) {
45 | // Add -server suffix to load the server-specific build.
46 | if (href && !/-server\.js^/.test(href)) {
47 | href = href.replace(/\.js$/, '-server.js');
48 | }
49 |
50 | // Remap the external URL space to the local file system
51 | if (href) {
52 | href = path.relative('/r/phoenix/', href);
53 | href = __dirname + '/src/' + href;
54 | }
55 |
56 | return href;
57 | },
58 |
59 | callback: function(err, html) {
60 | if (err) {
61 | reply(err);
62 | } else {
63 | reply(html);
64 | }
65 | }
66 | });
67 | ```
68 |
69 | ## Page Lifecyle
70 |
71 | For a given page request cycle a few different stages occur, approximating the browser's life cycle.
72 |
73 | 1. Page created
74 | 1. Initial DOM is loaded
75 | 1. (optional) `beforeExec` callback is run allowing the host to modify the page environment.
76 | 1. Embedded scripts are executed
77 | Scripts are executed sequentially and are blocking regardless of inlined or external. Currently `async` and `defer` attributes are ignored.
78 | 1. (optional) `loaded` callback is executed
79 | 1. Client code continues executing until emit occurs. See [Emit Behaviors](#emit-behaviors) below for details on this behavior.
80 |
81 | ### Emit Behaviors
82 |
83 | Once the page has completed rendering it needs to notify the fruit-loops container that the response is ready for the user. This is done via the `emit` method.
84 |
85 | `emit` supports one of three modes:
86 |
87 | - Immediate: `emit()`
88 |
89 | Outputs the page immediately after this call is made.
90 |
91 | - AJAX completion: `emit('ajax')`
92 |
93 | Outputs the page once all AJAX events have completed. If none are pending at the time this is called emits immediately.
94 |
95 | - Event loop cleared: `emit('events')`
96 |
97 | Outputs the page once all async behaviors have completed. This is a superset of the AJAX completion mode, also waiting for all pending timeouts to complete prior to emitting. This mode is similar to Node's full process life cycle.
98 |
99 | Both the immediate and ajax emit modes will wait for the next node event loop before emitting the page, allowing any pending operations to have a chance to complete. Note that these operations are not guaranteed to complete and critical behaviors generally should not rely on this timeout.
100 |
101 | Note that Fruit loops will cancel pending async behaviors once the page emit's its contents. For ajax calls this means that the request will be aborted at whatever stage they are currently in. For `setTimeout` and `setImmediate` will be cleared by their respective clear API.
102 |
103 | Once the emit process beings, the flow is as follows:
104 |
105 | 1. All callbacks registered through `onEmit` are executed.
106 | 1. All cancellable pending operations are canceled.
107 | 1. (Optional) The `finalize` callback is called
108 | 1. The current request's `callback` is called with the rendered HTML content
109 |
110 | ## Public Only Rendering
111 |
112 | One of the primary goals for Fruit Loops is to enable rendering of public only data. This allows for the server-side tier to handle the SEO concerns and fast load of common content and the client tier can handle augmenting the initial HTML payload with time or user specific data.
113 |
114 | In many situations this architecture allows for the burden of rendering a page to be pushed out to the CDN and client tier rather than forcing the server to handle all pages.
115 |
116 | With this goal in mind Fruit Loops does not currently support features like cookie propagation to the AJAX layer or persistence of the `localStorage` and `sessionStorage` shims. PRs are accepted for this of course.
117 |
118 | ## Security
119 |
120 | Like any other web server framework there are a variety of possible security concerns that might arise within a Fruit Loops environment. Where possible the framework attempts to fail safe but care needs to be taken, particularly when handling user input, to ensure application integrity.
121 |
122 |
123 | ### Sandbox
124 |
125 | All code for a given page is executed within a sandbox which isolates page code from node code. Things such as the host's `require` and other globals are not available to the page unless explicitly exposed through host code such as `beforeExec`.
126 |
127 | Page lifecycle callbacks such as `beforeExec`, `loaded`, etc are not run in the sandbox.
128 |
129 | ### Script Loader
130 |
131 | Fruit Loop's default script loader is intended to be somewhat restrictive to limit risk. To this end it will only automatically load scripts:
132 |
133 | - On the initial page load
134 | - Defined statically within the index's HTML file
135 | - Can be loaded from the file system or from inlined scripts in the HTML
136 |
137 | No attempts will be made to load scripts that are injected at later stages in the page's life cycle. Any such scripts will be executed on the client side so standard XSS protections must be employed to avoid the creation of unauthorized `script` tags.
138 |
139 | Should other scripts be loaded the `loadInContext` utility is available to client code. Even this still has the limitation of requiring that all files be loaded from the local file system.
140 |
141 | ### Dynamic Scripts
142 |
143 | In an effort to reduce possible attack vectors, the ability to execute dynamic code not loaded from the file system is disabled by default. This means that `eval`, `Function()` and `setTimeout(string)` will all explicitly throw if used. Should these behaviors be needed the `evil` flag may be set on the page's options. Enabling this should be done after thorough analysis of the codebase to ensure that there are no cases where arbitrary user input may be executed in an unsafe manner.
144 |
145 | Some libraries, particularly templating libraries, will not operate properly without the evil flag. For Handlebars in particular, the recommendation is that build time precompilation be utilized as this removes the need for dynamic evaluation.
146 |
147 | ### Shared State
148 |
149 | If using the VM pooling functionality then the consequences of an XSS exploit could easily have a much larger impact as attacks can be crafted that will be persistent for the lifetime of the VM.
150 |
151 | ## Supported Features
152 |
153 | Due to differences in the goals of server vs. client rendering, Fruit Loops does not support the following behaviors that might be available within a full browser environment.
154 |
155 | - Most DOM APIs, particularly DOM events
156 | - Layout calculation
157 | - `setInterval`
158 | - Persistent storage
159 | - Cookies
160 |
161 | As such there are some jQuery APIs that are not implemented when running within a fruit-loops context. See [Client APIs](#client-apis) for the complete list of supported APIs.
162 |
163 | There are three different methods generally available for handling the differences between the two tiers.
164 |
165 | 1. Feature detection: Most of the unsupported features are simply not implemented vs. stubed for failure. Any such features can be omitted from the server execution flow simply by using standard feature detection practices.
166 | 1. `$serverSide` global conditional: The global `$serverSide` is set to true on within Fruit Loops page environments and may be used for controlling conditional behavior. It's recommended that these be compiled out using a tool such a Uglify's [conditional compilation](https://github.com/mishoo/UglifyJS2#conditional-compilation) to avoid overhead in one environment or the other.
167 | 1. Server-specific build resolution: If using a tool such as [Lumbar](https://github.com/walmartlabs/lumbar), a server-specific build may be created and loaded via a [`resolver`](#pageoptions) that loads the server specific build.
168 |
169 | It's highly recommended that a framework such as [Thorax](http://thoraxjs.org) be used as this abstracts away many of the differences between the two environments but this is not required.
170 |
171 | ## Performance
172 |
173 | Even though the Fruit Loops strives for an environment with minimal differences between the client and server there are a number of performance concerns that are either specific to the server-side or exacerbated by execution on the server.
174 |
175 | The two biggest performance concerns that have been seen are initialization time and overhead due to rendering otherwise hidden content on the server side.
176 |
177 | ### Initialization Time
178 |
179 | Creating the sandbox and initializing the client SPA infrastructure takes a bit of time and can also lead to confusion for the optimizer. Users that are rendering in a public only system and whose application support safely transitioning between pages via the `navigate` API may want to consider pooling and reusing page instances to avoid unnecessary overhead from repeated operations.
180 |
181 | In one anecdote, an application pooling was able to reduce response times by a factor of 5 due to avoiding the context overhead and recreating the base application logic on each request. The impact of this will vary by application and should be examined in context.
182 |
183 | ### Unnecessary Operations
184 |
185 | Things like rendering menus and other initially hidden content all add to the CPU load necessary for parsing the content. While this is a concern for the client-side rendering as well this is much more noticeable when rendering on the server when all requests share the same event loop. It's recommended that any operations that won't generate meaningful content for the user on the initial load be setup so that the rendering is deferred until the point that it is needed. Generally this optimization should improve the initial load experience for both client and server environments.
186 |
187 | ## Node APIs
188 |
189 | ### `#page(options)`
190 |
191 | Creates a new page object with the given options.
192 |
193 | Available options:
194 | - `index`: Path to the bootstrap file that is used to initialize the page instance
195 | - `callback(err, html, meta)`: Callback called when the page is emitted. Returned data includes:
196 | - `html`: HTML content of the page at emit time
197 | - `meta`: Metadata regarding the rendering cycle. Includes:
198 | - `status`: HTTP Status code for the response
199 | - `cache`: Minimum cache values of all components used in the response.
200 | - `taskLog`: List of tasks such as AJAX requests made along with basic response and duration info.
201 | - `incompleteTasks`: Number of pending operations that were running at the time of emit.
202 | - `maxTasks`: Maximum number of concurrent tasks running at any given time for the response.
203 | - `beforeExec(page, next)`: Optional callback called after the DOM has loaded, but prior to any scripts executing. Must call `next` once complete to continue page execution.
204 | - `loaded(page)`: Optional callback called after the DOM and all scripts have been loaded
205 | - `finalize(page)`: Optional callback called just prior to the callback method being called.
206 | - `resolver(href, page)`: Callback used to resolve the file path external resources needed to render the page. The default behavior is to lookup resources relative to the `index` file.
207 | - `host`: Host name that will be passed to the page's context.
208 | - `protocol`: Used to generate the `window.location` object. Defaults to `http:`
209 | - `path`: Path of the page, including any query or hash information. The should be relative to the host's root.
210 | - `userAgent`: Use agent value used to seed the `window.navigator.userAgent` value.
211 | - `cacheResources`: Truthy to cache script and page resources within the javascript heap. When this is enabled, no attempt will be made to reload content from disk after it's initially loaded/parsed.
212 | - `ajax`: Object defining ajax request options
213 | - `shortCircuit(options, callback)`: Optional method that may be used to provide alternative processing for the AJAX request. Should return truthy if the method can process the request and should preempt the normal AJAX request processing. This may be used with utilities like Hapi's `server.inject` to optimize local requests, for example. `callback` expects `callback(err, response, cache, report)` where `response` is an object with fields `{statusCode, data}`. `cache` and `report` are optional reporting parameters that match the Catbox return data.
214 | - `cache`: Optional [Catbox Policy](https://github.com/spumko/catbox#policy) instance used to cache AJAX responses used to generate the page. All responses will be cached per the HTTP cache headers returned.
215 | - `timeout`: Default timeout for AJAX requests. When client calls specify a timeout and this value is specified, the lower of the two values will be used as the effective timeout for the call. Defaults to no timeout.
216 | - `evil`: Truthy to enable dynamic code execution via `eval`, `Function`, and `setTimeout`. See [dynamic scripts](#dynamic-scripts) for more information.
217 | - `metadata`: Metadata that is assigned to the page instance and may be used within callbacks.
218 |
219 | The returned page instance consists of:
220 | - `id`: Unique id value that may be used to identify the page
221 | - `window`: The page's global object
222 | - `$`: The page's internal `$` API. Note that this is not the same object as `window.$` as it exposes internal interfaces.
223 | - `exec`: Utility method used to safely execute client code
224 | - `emit`: Alias for `window.emit`
225 | - `dispose()`: Should be called after a page is no longer needed in order to clean up resources.
226 | - `navigate(path, callback)`: Updates the existing page to point to a new path. This will clear a variety of the page's state and should only be done for pages that expect this behavior. See the [performance](#performance) section for further discussion.
227 |
228 | ### `#pool(options)`
229 |
230 | Creates a pool of page objects.
231 |
232 | Shares the same options as the `page` method with a few distinctions:
233 | - `path` and `callback` will be ignored. The values passed to `navigate` will be used instead.
234 | - Adds the `poolSize` option used to specify the number of pages to create at once.
235 | - Adds the `maxQueue` option used to limit the number of requests that can be queued at a given time. If set a `EQUEUEFULL` error will be returned if this limit is exceeded.
236 | - Add the `queueTimeout` option used to timeout requests that pending in the queue. If triggered this will return a `EQUEUETIMEOUT` error.
237 | - Adds `navigated(page, existingPage)` callback which is called after a page is reused. This should be used to notify the application that the path has changed, i.e. `Backbone.history.loadUrl()` or similar. Will be called for all `pool.navigated` calls. `existingPage` will be true when the page has been used in a previous render cycle.
238 | - When `cacheResources` is falsy a `fs.watch` will be performed on all script files loaded into the pool. Should one change then the pool will be restarted. This will preempt any running requests, leaving them in an indeterminate state. In production it's recommended that this flag be set to `true`.
239 |
240 | The returned pool instance consists of:
241 | - `navigate(path [, metadata], callback)`: Renders a given path and returns it to callback. Optional `metadata` argument may be passed to override the initial metadata for a given page.
242 | - `dispose()`: Should be called after a pool is no longer needed in order to clean up resources.
243 |
244 | ```javascript
245 | var pool = FruitLoops.pool({
246 | poolSize: 2,
247 | index: __dirname + '/artifacts/pool-page.html',
248 | navigated: function(page, existingPage) {
249 | if (existingPage) {
250 | // Force backbone navigation if the page has been previously used.
251 | page.window.Backbone.history.loadUrl();
252 | }
253 | }
254 | });
255 | pool.navigate('/bar', function(err, html) {
256 | if (err) {
257 | reply(err);
258 | } else {
259 | reply(html);
260 | }
261 | });
262 | ```
263 |
264 | ### `page.$.ajax`
265 |
266 | There are a number of utility methods exposed on the node-side ajax instance including:
267 |
268 | - `.allComplete` Returns `true` if there are no requests currently waiting.
269 | - `.toJSON` Returns a stringified JSON object containing the response content from all requests involved in the page.
270 | - `.minimumCache` Returns a structure containing the minimum cache of all requests. Contains
271 | - `no-cache`: Truthy if the response is not cacheable
272 | - `private`: Truthy if the response must be private cached
273 | - `expires`: Number of seconds that the response should expire in. `Number.MAX_VALUE` if no content contained a cache expiration.
274 |
275 | ## Client APIs
276 |
277 | ### $ APIs
278 |
279 | The following APIs are supported and should match the [jQuery](http://api.jquery.com/)/[Zepto](http://zeptojs.com/) implementation unless otherwise noted.
280 |
281 | #### Constructors
282 |
283 | - `$(selector)`
284 | - `$(fruit loops collection)`
285 | - `$(function() {})` / `.ready(function() {})`
286 |
287 | #### Tree Traversal
288 |
289 | - `.find`
290 | - `.parent`
291 | - `.parents`
292 | - `.closest`
293 | - `.next`
294 | - `.nextAll`
295 | - `.nextUntil`
296 | - `.prev`
297 | - `.prevAll`
298 | - `.prevUntil`
299 | - `.siblings`
300 | - `.children`
301 | - `.contents`
302 |
303 | # Set Handling
304 |
305 | - `.each`
306 | - `.forEach`
307 | - `.map`
308 | - `.filter`
309 | - `.first`
310 | - `.last`
311 | - `.eq`
312 | - `.get`
313 | - `.slice`
314 | - `.end`
315 | - `.toArray`
316 | - `.pluck`
317 |
318 | #### Tree Manipulation
319 |
320 | - `.append`
321 | - `.appendTo`
322 | - `.prepend`
323 | - `.prependTo`
324 | - `.after`
325 | - `.insertAfter`
326 | - `.before`
327 | - `.insertBefore`
328 | - `.detach`
329 | - `.remove`
330 | - `.replaceWith`
331 | - `.replaceAll`
332 | - `.empty`
333 | - `.html`
334 | - `.text`
335 | - `.clone`
336 |
337 | #### Node Manipulation
338 |
339 | - `.attr`
340 | - `.data`
341 | - `.val`
342 | - `.removeAttr`
343 | - `.hasClass`
344 | - `.addClass`
345 | - `.removeClass`
346 | - `.toggleClass`
347 | - `.is`
348 | - `.css`
349 | - `.toggle`
350 | - `.show`
351 | - `.hide`
352 | - `.focus` - Sets the `autofocus` attribute
353 | - `.blur` - Unsets the `autofocus` attribute
354 |
355 | Not implemented:
356 |
357 | - `.height`
358 | - `.innerHeight`
359 | - `.innerWidth`
360 | - `.offset`
361 | - `.offsetParent`
362 | - `.outerHeight`
363 | - `.outerWidth`
364 | - `.position`
365 | - `.scrollLeft`
366 | - `.scrollTop`
367 | - `.width`
368 | - `.prop`
369 | - `.removeProp`
370 |
371 | #### Event APIs
372 |
373 | Fruit loops implements stubs for:
374 |
375 | - `.bind`
376 | - `.unbind`
377 | - `.on`
378 | - `.off`
379 | - `.live`
380 | - `.die`
381 | - `.delegate`
382 | - `.undelegate`
383 | - `.one`
384 |
385 | Each of the above methods will perform no operations but may be chained.
386 |
387 | Methods designed to trigger events are explicitly not implemented.
388 |
389 | - `.change`
390 | - `.click`
391 | - `.dblclick`
392 | - `.error`
393 | - `.focusin`
394 | - `.focusout`
395 | - `.hover`
396 | - `.keydown`
397 | - `.keypress`
398 | - `.keyup`
399 | - `.mousedown`
400 | - `.mouseenter`
401 | - `.mouseleave`
402 | - `.mousemove`
403 | - `.mouseout`
404 | - `.mouseover`
405 | - `.mouseup`
406 | - `.resize`
407 | - `.scroll`
408 | - `.select`
409 | - `.trigger`
410 | - `.triggerHandler`
411 | - `.submit`
412 | - `.unload`
413 |
414 | #### Detect
415 |
416 | Fruit loop implements a direct port of Zepto's `$.detect` library.
417 |
418 | #### AJAX
419 |
420 | - `$.ajax`
421 | - `$.param`
422 |
423 | Not currently supported:
424 | - `$.ajaxJSONP`
425 | - `$.ajaxSettings`
426 | - `$.get`
427 | - `$.getJSON`
428 | - `$.post`
429 | - `.load`
430 |
431 | #### Form
432 |
433 | Form handling methods are not supported at this time. This includes:
434 |
435 | - `.serialize`
436 | - `.serializeArray`
437 | - `.submit`
438 |
439 | #### Effects
440 |
441 | Effects APIs are generally not support in fruit loops. The exception being:
442 |
443 | - `.animate` - Implements immediate set operation
444 |
445 | #### Static Methods
446 |
447 | - `$.contains`
448 | - `$.each`
449 | - `$.extend`
450 | - `$.globalEval`
451 | - `$.grep`
452 | - `$.inArray`
453 | - `$.isArray`
454 | - `$.isFunction`
455 | - `$.isNumeric`
456 | - `$.isEmptyObject`
457 | - `$.isPlainObject`
458 | - `$.isWindow`
459 | - `$.makeArray`
460 | - `$.map`
461 | - `$.merge`
462 | - `$.noop`
463 | - `$.now`
464 | - `$.parseHTML`
465 | - `$.proxy`
466 | - `$.trim`
467 | - `$.type`
468 |
469 | Not implement:
470 | - `$.getScript`
471 | - `$.isXMLDoc`
472 | - `$.parseXML`
473 |
474 | ### DOM APIs
475 |
476 | In addition to the `$` APIs, Fruit Loops implements a variety of DOM and global browser APIs.
477 |
478 | - `console`
479 |
480 | Outputs to the process's console.
481 |
482 | - `setTimeout`
483 |
484 | The responses from these methods are generally `$` instances rather than true DOM objects. Code that is expecting true DOM objects will need to be updated to account for this or otherwise utilize the `$` APIs.
485 |
486 | - `history`
487 | - `pushState`
488 | - `replaceState`
489 |
490 | Note that both of these APIs perform a generic redirect and will terminate pending operations on the page.
491 |
492 | - `location`
493 | - `navigator`
494 | - `userAgent`
495 | - `performance`
496 | - `timing`
497 | - `localStorage`/`sessionStorage`
498 |
499 | Transient storage for the duration of the page's life cycle. This is not persisted in any way.
500 |
501 | ### Fruit Loops Extensions
502 |
503 | - `$serverSide`
504 |
505 | Constant flag. Set to `true`, allowing client code to differentiate between client and server contexts.
506 |
507 | - `FruitLoops.emit(action)`
508 |
509 | Begins the page output process. See [emit behaviors](#emit-behaviors) for more details.
510 |
511 | - `FruitLoops.loadInContext(href, callback)`
512 |
513 | Loads a given script. `href` should be a relative client script path. The `resolver` callback may be be used to remap this if needed. Upon completion `callback()` will be called.
514 |
515 | - `FruitLoops.statusCode(code)`
516 |
517 | Sets the desired status code for the response. This does not terminate further page execution.
518 |
519 | - `FruitLoops.redirect(url)`
520 |
521 | Stops further execution and emits a redirect to `url` as the page's response.
522 |
523 | - `setImmediate(callback)`
524 |
525 | Exposes node's `setImmediate` API. Allows for more performant timeout calls vs. `setTimeout` without a timeout.
526 |
527 | - `nextTick(callback)`
528 |
529 | Exposes node's `nextTick` API. `setImmediate` is preferred in most case as `nextTick` can lead to IO starvation.
530 |
531 |
--------------------------------------------------------------------------------
/test/page.js:
--------------------------------------------------------------------------------
1 | var _ = require('lodash'),
2 | fruitLoops = require('../lib'),
3 | ajax = require('../lib/jquery/ajax'),
4 | fs = require('fs'),
5 | hapi = require('hapi'),
6 | sinon = require('sinon');
7 |
8 | describe('page', function() {
9 | var server,
10 | page;
11 | before(function(done) {
12 | server = new hapi.Server(0);
13 | server.route({
14 | path: '/',
15 | method: 'GET',
16 | config: {jsonp: 'callback'},
17 | handler: function(req, reply) {
18 | setTimeout(function() {
19 | reply({data: 'get!'});
20 | }, 10);
21 | }
22 | });
23 | server.route({
24 | path: '/script',
25 | method: 'GET',
26 | handler: function(req, reply) {
27 | reply({data: ''});
28 | }
29 | });
30 | server.start(done);
31 | });
32 | after(function(done) {
33 | server.stop(done);
34 | });
35 | afterEach(function() {
36 | page.dispose();
37 | page = undefined;
38 | });
39 |
40 | it('should load html source', function(done) {
41 | page = fruitLoops.page({
42 | userAgent: 'anything but android',
43 | url: {
44 | path: '/foo'
45 | },
46 | index: __dirname + '/artifacts/empty-page.html',
47 | loaded: function(page) {
48 | page.window.$.should.exist;
49 | page.window.$serverSide.should.be.true;
50 | done();
51 | }
52 | });
53 | });
54 | it('should handle page load errors', function(done) {
55 | page = fruitLoops.page({
56 | userAgent: 'anything but android',
57 | url: {
58 | path: '/foo'
59 | },
60 | index: __dirname + '/artifacts/does-not-exist.html',
61 | callback: function(err) {
62 | err.should.be.instanceOf(Error);
63 | done();
64 | }
65 | });
66 | });
67 | it('should callback before script init', function(done) {
68 | var execCalled;
69 | page = fruitLoops.page({
70 | userAgent: 'anything but android',
71 | url: {
72 | path: '/foo'
73 | },
74 | index: __dirname + '/artifacts/script-page.html',
75 | beforeExec: function(page, next) {
76 | should.exist(page);
77 | execCalled = true;
78 | next();
79 | },
80 | loaded: function() {
81 | execCalled.should.be.true;
82 | page.window.inlinedVar.should.equal(1);
83 | page.window.externalVar.should.equal(2);
84 | page.window.syncVar.should.equal(3);
85 | done();
86 | }
87 | });
88 | });
89 | it('should handle resolver error', function(done) {
90 | var execCalled;
91 | page = fruitLoops.page({
92 | userAgent: 'anything but android',
93 | url: {
94 | path: '/foo'
95 | },
96 | index: __dirname + '/artifacts/script-page.html',
97 | resolver: function(href, page) {
98 | execCalled = true;
99 | throw new Error('failed');
100 | },
101 | callback: function(err) {
102 | err.should.be.instanceOf(Error);
103 | err.message.should.equal('failed');
104 | done();
105 | }
106 | });
107 | });
108 | it('should handle before script error', function(done) {
109 | var execCalled;
110 | page = fruitLoops.page({
111 | userAgent: 'anything but android',
112 | url: {
113 | path: '/foo'
114 | },
115 | index: __dirname + '/artifacts/script-page.html',
116 | beforeExec: function(page, next) {
117 | execCalled = true;
118 | next(new Error('failed'));
119 | },
120 | callback: function(err) {
121 | err.should.be.instanceOf(Error);
122 | err.message.should.equal('failed');
123 | done();
124 | }
125 | });
126 | });
127 | it('should load all inlined scripts', function(done) {
128 | page = fruitLoops.page({
129 | userAgent: 'anything but android',
130 | url: {
131 | path: '/foo'
132 | },
133 | index: __dirname + '/artifacts/script-page.html',
134 | loaded: function() {
135 | page.window.inlinedVar.should.equal(1);
136 | page.window.externalVar.should.equal(2);
137 | page.window.syncVar.should.equal(3);
138 | done();
139 | }
140 | });
141 | });
142 | it('should allow custom file resolution', function(done) {
143 | var resolver = this.spy(function() {
144 | return __dirname + '/artifacts/other-script.js';
145 | });
146 |
147 | page = fruitLoops.page({
148 | userAgent: 'anything but android',
149 | url: '/foo',
150 | index: __dirname + '/artifacts/script-page.html',
151 | resolver: resolver,
152 | loaded: function() {
153 | resolver.should
154 | .have.been.calledOnce
155 | .have.been.calledWith('/test-script.js', page);
156 |
157 | page.window.inlinedVar.should.equal(1);
158 | page.window.externalVar.should.equal(3);
159 | page.window.syncVar.should.equal(4);
160 | done();
161 | }
162 | });
163 | });
164 | it('should error on missing scripts', function(done) {
165 | var callback = this.spy();
166 |
167 | page = fruitLoops.page({
168 | userAgent: 'anything but android',
169 | url: {
170 | path: '/foo'
171 | },
172 | index: __dirname + '/artifacts/script-page.html',
173 | resolver: function() {
174 | return __dirname + '/artifacts/not-a-script.js';
175 | },
176 | callback: function(err) {
177 | err.should.be.instanceOf(Error);
178 | done();
179 | }
180 | });
181 | });
182 | it('should error on external syntax error', function(done) {
183 | var callback = this.spy();
184 |
185 | page = fruitLoops.page({
186 | userAgent: 'anything but android',
187 | url: {
188 | path: '/foo'
189 | },
190 | index: __dirname + '/artifacts/script-page.html',
191 | resolver: function() {
192 | return __dirname + '/artifacts/syntax-error.js';
193 | },
194 | callback: function(err) {
195 | err.should.be.instanceOf(Error);
196 | done();
197 | }
198 | });
199 | });
200 |
201 | it('should prevent exec on redirect in external script', function(done) {
202 | this.clock.restore();
203 |
204 | page = fruitLoops.page({
205 | userAgent: 'anything but android',
206 | index: __dirname + '/artifacts/script-page.html',
207 | resolver: function() {
208 | return __dirname + '/artifacts/redirect-script.js';
209 | },
210 | callback: function(err, data) {
211 | should.not.exist(err);
212 | data.should.eql({redirect: '/foo'});
213 |
214 | setTimeout(done, 100);
215 | }
216 | });
217 | });
218 |
219 | it('should prevent exec on error in external script', function(done) {
220 | this.clock.restore();
221 |
222 | page = fruitLoops.page({
223 | userAgent: 'anything but android',
224 | index: __dirname + '/artifacts/script-page.html',
225 | resolver: function() {
226 | return __dirname + '/artifacts/error-script.js';
227 | },
228 | callback: function(err) {
229 | err.should.be.instanceOf(Error);
230 | err.toString().should.match(/error-script expected/);
231 |
232 | setTimeout(done, 100);
233 | }
234 | });
235 | });
236 | it('should prevent exec on error in internal script', function(done) {
237 | this.clock.restore();
238 |
239 | page = fruitLoops.page({
240 | userAgent: 'anything but android',
241 | index: __dirname + '/artifacts/inline-script-error.html',
242 | callback: function(err) {
243 | err.should.be.instanceOf(Error);
244 | err.toString().should.match(/Expected/);
245 |
246 | setTimeout(done, 100);
247 | }
248 | });
249 | });
250 | it('should prevent exec on error in internal script', function(done) {
251 | this.clock.restore();
252 |
253 | page = fruitLoops.page({
254 | userAgent: 'anything but android',
255 | index: __dirname + '/artifacts/inline-script-syntax-error.html',
256 | callback: function(err) {
257 | err.should.be.instanceOf(SyntaxError);
258 | err.stack.should.match(/SyntaxError: Unexpected token \]\n\nInline Script:\n\t