-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
1201 lines (1054 loc) · 32.7 KB
/
index.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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
var Formidable = require('formidable').IncomingForm
, fabricate = require('fabricator')
, helpers = require('./helpers')
, debug = require('diagnostics')
, dot = require('dot-component')
, destroy = require('demolish')
, Route = require('routable')
, fuse = require('fusing')
, async = require('async')
, path = require('path')
, url = require('url');
//
// Cache long prototype lookups to increase speed + write shorter code.
//
var slice = Array.prototype.slice;
//
// Methods that needs data buffering.
//
var operations = 'POST, PUT, DELETE, PATCH'.toLowerCase().split(', ');
/**
* Simple helper function to generate some what unique id's for given
* constructed pagelet.
*
* @returns {String}
* @api private
*/
function generator(n) {
if (!n) return Date.now().toString(36).toUpperCase();
return Math.random().toString(36).substring(2, 10).toUpperCase();
}
/**
* A pagelet is the representation of an item, section, column or widget.
* It's basically a small sandboxed application within your application.
*
* @constructor
* @param {Object} options Optional configuration.
* @api public
*/
function Pagelet(options) {
if (!this) return new Pagelet(options);
this.fuse();
options = options || {};
//
// Use the temper instance on Pipe if available.
//
if (options.bigpipe && options.bigpipe._temper) {
options.temper = options.bigpipe._temper;
}
this.writable('_enabled', []); // Contains all enabled pagelets.
this.writable('_disabled', []); // Contains all disable pagelets.
this.writable('_active', null); // Are we active.
this.writable('_req', options.req); // Incoming HTTP request.
this.writable('_res', options.res); // Incoming HTTP response.
this.writable('_params', options.params); // Params extracted from the route.
this.writable('_temper', options.temper); // Attach the Temper instance.
this.writable('_bigpipe', options.bigpipe); // Actual pipe instance.
this.writable('_bootstrap', options.bootstrap); // Reference to bootstrap Pagelet.
this.writable('_append', options.append || false); // Append content client-side.
this.writable('debug', debug('pagelet:'+ this.name)); // Namespaced debug method
//
// Allow overriding the reference to parent pagelet.
// A reference to the parent is normally set on the
// constructor prototype by optimize.
//
if (options.parent) this.writable('_parent', options.parent);
}
fuse(Pagelet, require('eventemitter3'));
/**
* Unique id, useful for internal querying.
*
* @type {String}
* @public
*/
Pagelet.writable('id', null);
/**
* The name of this pagelet so it can checked to see if's enabled. In addition
* to that, it can be injected in to placeholders using this name.
*
* @type {String}
* @public
*/
Pagelet.writable('name', '');
/**
* The HTTP pathname that we should be matching against.
*
* @type {String|RegExp}
* @public
*/
Pagelet.writable('path', null);
/**
* Which HTTP methods should this pagelet accept. It can be a comma
* separated string or an array.
*
* @type {String|Array}
* @public
*/
Pagelet.writable('method', 'GET');
/**
* The default status code that we should send back to the user.
*
* @type {Number}
* @public
*/
Pagelet.writable('statusCode', 200);
/**
* The pagelets that need to be loaded as children of this pagelet.
*
* @type {Object}
* @public
*/
Pagelet.writable('pagelets', {});
/**
* With what kind of generation mode do we need to output the generated
* pagelets. We're supporting 3 different modes:
*
* - sync: Fully render without any fancy flushing of pagelets.
* - async: Render all pagelets async and flush them as fast as possible.
* - pipeline: Same as async but in the specified order.
*
* @type {String}
* @public
*/
Pagelet.writable('mode', 'async');
/**
* Save the location where we got our resources from, this will help us with
* fetching assets from the correct location.
*
* @type {String}
* @public
*/
Pagelet.writable('directory', '');
/**
* The environment that we're running this pagelet in. If this is set to
* `development` It would be verbose.
*
* @type {String}
* @public
*/
Pagelet.writable('env', (process.env.NODE_ENV || 'development').toLowerCase());
/**
* Conditionally load this pagelet. It can also be used as authorization handler.
* If the incoming request is not authorized you can prevent this pagelet from
* showing. The assigned function receives 3 arguments.
*
* - req, the http request that initialized the pagelet
* - list, array of pagelets that will be tried
* - done, a callback function that needs to be called with only a boolean.
*
* ```js
* Pagelet.extend({
* if: function conditional(req, list, done) {
* done(true); // True indicates that the request is authorized for access.
* }
* });
* ```
*
*/
Pagelet.writable('if', null);
/**
* A pagelet has been initialized.
*
* @type {Function}
* @public
*/
Pagelet.writable('initialize', null);
/**
* Remove the DOM element if we are not enabled. This will make it easier to
* create conditional layouts without having to manage the pointless DOM
* elements.
*
* @type {Boolean}
* @public
*/
Pagelet.writable('remove', true);
/**
* List of keys in the data that will be supplied to the client-side script.
* Paths to nested keys can be supplied via dot notation.
*
* @type {Array}
* @public
*/
Pagelet.writable('query', []);
/**
* The location of your view template. But just because you've got a view
* template it doesn't mean we will render it. It depends on how the pagelet is
* called. If it's called from the client side we will only forward the data to
* server.
*
* As a user you need to make sure that your template runs on the client as well
* as on the server side.
*
* @type {String}
* @public
*/
Pagelet.writable('view', null);
/**
* The location of your error template. This template will be rendered when:
*
* 1. We receive an `error` argument from your `get` method.
* 2. Your view throws an error when rendering the template.
*
* If no view has been set it will default to the Pagelet's default error
* template which outputs a small HTML fragment that states the error.
*
* @type {String}
* @public
*/
Pagelet.writable('error', path.join(__dirname, 'error.html'));
/**
* Optional template engine preference. Useful when we detect the wrong template
* engine based on the view's file name. If no engine is provide we will attempt
* to figure out the correct template engine based on the file extension of the
* provided template path.
*
* @type {String}
* @public
*/
Pagelet.writable('engine', '');
/**
* The Style Sheet for this pagelet. The location can be a string or multiple paths
* in an array. It should contain all the CSS that's needed to render this pagelet.
* It doesn't have to be a `CSS` extension as these files are passed through
* `smithy` for automatic pre-processing.
*
* @type {String|Array}
* @public
*/
Pagelet.writable('css', '');
/**
* The JavaScript files needed for this pagelet. The location can be a string or
* multiple paths in an array. This file needs to be included in order for
* this pagelet to function.
*
* @type {String|Array}
* @public
*/
Pagelet.writable('js', '');
/**
* An array with dependencies that your pagelet depends on. This can be CSS or
* JavaScript files/frameworks whatever. It should be an array of strings
* which represent the location of these files.
*
* @type {Array}
* @public
*/
Pagelet.writable('dependencies', []);
/**
* Save the location where we got our resources from, this will help us with
* fetching assets from the correct location. This property is automatically set
* when the you do:
*
* ```js
* Pagelet.extend({}).on(module);
* ```
*
* If you do not use this pattern make sure you set an absolute path the
* directory that the pagelet and all it's resources are in.
*
* @type {String}
* @public
*/
Pagelet.writable('directory', '');
/**
* Reference to parent Pagelet name.
*
* @type {Object}
* @private
*/
Pagelet.writable('_parent', null);
/**
* Set of optimized children Pagelet.
*
* @type {Object}
* @private
*/
Pagelet.writable('_children', {});
/**
* Cataloged dependencies by extension.
*
* @type {Object}
* @private
*/
Pagelet.writable('_dependencies', {});
/**
* Default character set, UTF-8.
*
* @type {String}
* @private
*/
Pagelet.writable('_charset', 'UTF-8');
/**
* Default content type of the Pagelet.
*
* @type {String}
* @private
*/
Pagelet.writable('_contentType', 'text/html');
/**
* Default asynchronous get function. Override to provide specific data to the
* render function.
*
* @param {Function} done Completion callback when we've received data to render.
* @api public
*/
Pagelet.writable('get', function get(done) {
(global.setImmediate || global.setTimeout)(done);
});
/**
* Get parameters that were extracted from the route.
*
* @type {Object}
* @public
*/
Pagelet.readable('params', {
enumerable: false,
get: function params() {
return this._params || this.bootstrap._params || Object.create(null);
}
}, true);
/**
* Report the length of the queue (e.g. amount of children). The length
* is increased with one as the reporting pagelet is part of the queue.
*
* @return {Number} Length of queue.
* @api private
*/
Pagelet.get('length', function length() {
return this._children.length;
});
/**
* Get and initialize a given child Pagelet.
*
* @param {String} name Name of the child pagelet.
* @returns {Array} The pagelet instances.
* @api public
*/
Pagelet.readable('child', function child(name) {
if (Array.isArray(name)) name = name[0];
return (this.has(name) || this.has(name, true) || []).slice(0);
});
/**
* Helper to invoke a specific route with an optionally provided method.
* Useful for serving a pagelet after handling POST requests for example.
*
* @param {String} route Registered path.
* @param {String} method Optional HTTP verb.
* @returns {Pagelet} fluent interface.
*/
Pagelet.readable('serve', function serve(route, method) {
var req = this._req
, res = this._res;
req.method = (method || 'get').toUpperCase();
req.uri = url.parse(route);
this._bigpipe.router(req, res);
return this;
});
/**
* Helper to check if the pagelet has a child pagelet by name, must use
* prototype.name since pagelets are not always constructed yet.
*
* @param {String} name Name of the pagelet.
* @param {String} enabled Make sure that we use the enabled array.
* @returns {Array} The constructors of matching Pagelets.
* @api public
*/
Pagelet.readable('has', function has(name, enabled) {
if (!name) return [];
if (enabled) return this._enabled.filter(function filter(pagelet) {
return pagelet.name === name;
});
var pagelets = this._children
, i = pagelets.length
, pagelet;
while (i--) {
pagelet = pagelets[i][0];
if (
pagelet.prototype && pagelet.prototype.name === name
|| pagelets.name === name
) return pagelets[i];
}
return [];
});
/**
* Render execution flow.
*
* @api private
*/
Pagelet.readable('init', function init() {
var method = this._req.method.toLowerCase()
, pagelet = this;
//
// Only start reading the incoming POST request when we accept the incoming
// method for read operations. Render in a regular mode if we do not accept
// these requests.
//
if (~operations.indexOf(method)) {
var pagelets = this.child(this._req.query._pagelet)
, reader = this.read(pagelet);
this.debug('Processing %s request', method);
async.whilst(function work() {
return !!pagelets.length;
}, function process(next) {
var Child = pagelets.shift()
, child;
if (!(method in Pagelet.prototype)) return next();
child = new Child({ bigpipe: pagelet._bigpipe });
child.conditional(pagelet._req, pagelets, function allowed(accepted) {
if (!accepted) {
if (child.destroy) child.destroy();
return next();
}
reader.before(child[method], child);
});
}, function nothing() {
if (method in pagelet) {
reader.before(pagelet[method], pagelet);
} else {
pagelet._bigpipe[pagelet.mode](pagelet);
}
});
} else {
this._bigpipe[this.mode](this);
}
});
/**
* Start buffering and reading the incoming request.
*
* @returns {Form}
* @api private
*/
Pagelet.readable('read', function read() {
var form = new Formidable
, pagelet = this
, fields = {}
, files = {}
, context
, before;
form.on('progress', function progress(received, expected) {
//
// @TODO if we're not sure yet if we should handle this form, we should only
// buffer it to a predefined amount of bytes. Once that limit is reached we
// need to `form.pause()` so the client stops uploading data. Once we're
// given the heads up, we can safely resume the form and it's uploading.
//
}).on('field', function field(key, value) {
fields[key] = value;
}).on('file', function file(key, value) {
files[key] = value;
}).on('error', function error(err) {
pagelet.capture(err, true);
fields = files = {};
}).on('end', function end() {
form.removeAllListeners();
if (before) {
before.call(context, fields, files);
}
});
/**
* Add a hook for adding a completion callback.
*
* @param {Function} callback
* @returns {Form}
* @api public
*/
form.before = function befores(callback, contexts) {
if (form.listeners('end').length) {
form.resume(); // Resume a possible buffered post.
before = callback;
context = contexts;
return form;
}
callback.call(contexts || context, fields, files);
return form;
};
return form.parse(this._req);
});
//
// !IMPORTANT
//
// These function's & properties should never overridden as we might depend on
// them internally, that's why they are configured with writable: false and
// configurable: false by default.
//
// !IMPORTANT
//
/**
* Discover pagelets that we're allowed to use.
*
* @returns {Pagelet} fluent interface
* @api private
*/
Pagelet.readable('discover', function discover() {
var req = this._req
, res = this._res
, pagelet = this;
//
// We need to do an async map/filter of the pagelets, in order to this as
// efficient as possible we're going to use a reduce.
//
async.reduce(this._children, {
disabled: [],
enabled: []
}, function reduce(memo, children, next) {
children = children.slice(0);
var child, last;
async.whilst(function work() {
return children.length && !child;
}, function work(next) {
var Child = children.shift()
, test = new Child({
bootstrap: pagelet.bootstrap,
bigpipe: pagelet._bigpipe,
res: res,
req: req
});
test.conditional(req, children, function conditionally(accepted) {
if (last && last.destroy) last.destroy();
if (accepted) child = test;
else last = test;
next(!!child);
});
}, function found() {
if (child) memo.enabled.push(child);
else memo.disabled.push(last);
next(undefined, memo);
});
}, function discovered(err, children) {
pagelet._disabled = children.disabled;
pagelet._enabled = children.enabled;
pagelet._enabled.forEach(function initialize(child) {
if ('function' === typeof child.initialize) child.initialize();
});
pagelet.debug('Initialized all allowed pagelets');
pagelet.emit('discover');
});
return this;
});
/**
* Process the pagelet for an async or pipeline based render flow.
*
* @param {String} name Optional name, defaults to pagelet.name.
* @param {Mixed} chunk Content of Pagelet.
* @returns {Bootstrap} Reference to bootstrap Pagelet.
* @api private
*/
Pagelet.readable('write', function write(name, chunk) {
if (!chunk) {
chunk = name;
name = this.name;
}
this.debug('Queueing data chunk');
return this.bootstrap.queue(name, this._parent, chunk);
});
/**
* Close the connection once all pagelets are sent.
*
* @param {Mixed} chunk Fragment of data.
* @returns {Boolean} Closed the connection.
* @api private
*/
Pagelet.readable('end', function end(chunk) {
var pagelet = this;
//
// Write data chunk to the queue.
//
if (chunk) this.write(chunk);
//
// Do not close the connection before all pagelets are send.
//
if (this.bootstrap.length > 0) {
this.debug('Not all pagelets have been written, (%s out of %s)',
this.bootstrap.length, this.length
);
return false;
}
//
// Everything is processed, close the connection and clean up references.
//
this.bootstrap.flush(function close(error) {
if (error) return pagelet.capture(error, true);
pagelet.debug('Closed the connection');
pagelet._res.end();
});
return true;
});
/**
* Set or get the value of the character set, only allows strings.
*
* @type {String}
* @api public
*/
Pagelet.set('charset', function get() {
return this._charset;
}, function set(value) {
if ('string' !== typeof value) return;
return this._charset = value;
});
/**
* The Content-Type of the response. This defaults to text/html with a charset
* preset inherited from the charset property.
*
* @type {String}
* @api public
*/
Pagelet.set('contentType', function get() {
return this._contentType +';charset='+ this._charset;
}, function set(value) {
return this._contentType = value;
});
/**
* Returns reference to bootstrap Pagelet, which could be the Pagelet itself.
* Allows more chaining and valid bootstrap Pagelet references.
*
* @type {String}
* @public
*/
Pagelet.set('bootstrap', function get() {
return !this._bootstrap && this.name === 'bootstrap' ? this : this._bootstrap || {};
}, function set(value) {
if (value && value.name === 'bootstrap') return this._bootstrap = value;
});
/**
* Checks if we're an active Pagelet or if we still need to a do an check
* against the `if` function.
*
* @type {Boolean}
* @private
*/
Pagelet.set('active', function get() {
return 'function' !== typeof this.if // No conditional check needed.
|| this._active !== null && this._active; // Conditional check has been done.
}, function set(value) {
return this._active = !!value;
});
/**
* Helper method that proxies to the redirect of the BigPipe instance.
*
* @param {String} path Redirect URI.
* @param {Number} status Optional status code.
* @param {Object} options Optional options, e.g. caching headers.
* @returns {Pagelet} fluent interface.
* @api public
*/
Pagelet.readable('redirect', function redirect(path, status, options) {
this._bigpipe.redirect(this, path, status, options);
return this;
});
/**
* Proxy to return the compiled server template from Temper.
*
* @param {String} view Absolute path to the templates location.
* @param {Object} data Used to render the server-side template.
* @return {String} Generated HTML.
* @public
*/
Pagelet.readable('template', function template(view, data) {
if ('string' !== typeof view) {
data = view;
view = this.view;
}
return this._temper.fetch(view).server(data || {});
});
/**
* Render takes care of all the data merging and `get` invocation.
*
* Options:
*
* - context: Context on which to call `after`, defaults to pagelet.
* - data: stringified object representation to pass to the client.
* - pagelets: Alternate pagelets to be used when this pagelet is not enabled.
*
* @param {Object} options Add post render functionality.
* @param {Function} fn Completion callback.
* @returns {Pagelet}
* @api private
*/
Pagelet.readable('render', function render(options, fn) {
if ('undefined' === typeof fn) {
fn = options;
options = {};
}
options = options || {};
var framework = this._bigpipe._framework
, compiler = this._bigpipe._compiler
, context = options.context || this
, mode = options.mode || 'async'
, data = options.data || {}
, bigpipe = this._bigpipe
, temper = this._temper
, query = this.query
, pagelet = this
, state = {};
/**
* Write the fragmented data.
*
* @param {String} content The content to respond with.
* @returns {Pagelet}
* @api private
*/
function fragment(content) {
var active = pagelet.active;
if (!active) content = '';
if (mode === 'sync') return fn.call(context, undefined, content);
data.id = data.id || pagelet.id; // Pagelet id.
data.path = data.path || pagelet.path; // Reference to the path.
data.mode = data.mode || pagelet.mode; // Pagelet render mode.
data.remove = active ? false : pagelet.remove; // Remove from DOM.
data.parent = pagelet._parent; // Send parent name along.
data.append = pagelet._append; // Content should be appended.
data.remaining = pagelet.bootstrap.length; // Remaining pagelets number.
data.hash = { // Temper md5's for template ref
error: temper.fetch(pagelet.error).hash.client,
client: temper.fetch(pagelet.view).hash.client
};
fn.call(context, undefined, framework.get('fragment', {
template: content.replace(/<!--(.|\s)*?-->/, ''),
name: pagelet.name,
id: pagelet.id,
state: state,
data: data
}));
return pagelet;
}
return this.conditional(this._req, options.pagelets, function auth(enabled) {
if (!enabled) return fragment('');
//
// Invoke the provided get function and make sure options is an object, from
// which `after` can be called in proper context.
//
pagelet.get(function receive(err, result) {
var view = temper.fetch(pagelet.view).server
, content;
//
// Add some template defaults.
//
result = result || {};
if (!('path' in result)) result.path = pagelet.path;
//
// We've made it this far, but now we have to cross our fingers and HOPE
// that our given template can actually handle the data correctly
// without throwing an error. As the rendering is done synchronously, we
// wrap it in a try/catch statement and hope that an error is thrown
// when the template fails to render the content. If there's an error we
// will process the error template instead.
//
try {
if (err) {
pagelet.debug('Render %s/%s resulted in a error', pagelet.name, pagelet.id, err);
throw err; // Throw so we can capture it again.
}
content = view(result, { html: true });
} catch (e) {
if ('production' !== pagelet.env) {
pagelet.debug('Captured rendering error: %s', e.stack);
}
//
// This is basically fly or die, if the supplied error template throws
// an error while rendering we're basically fucked, your server will
// crash, an angry mob of customers with pitchforks will kick in the
// doors of your office and smear you with peck and feathers for not
// writing a more stable application.
//
if (!pagelet.error) return fn(e);
content = temper.fetch(pagelet.error).server(pagelet.merge(result, {
reason: 'Failed to render: '+ pagelet.name,
env: pagelet.env,
message: e.message,
stack: e.stack,
error: e
}), { html: true });
}
//
// Add queried parts of data, so the client-side script can use it.
//
if ('object' === typeof result && Array.isArray(query) && query.length) {
state = query.reduce(function find(memo, q) {
memo[q] = dot.get(result, q);
return memo;
}, {});
}
fragment(content);
});
});
});
/**
* Authenticate the Pagelet.
*
* @param {Request} req The HTTP request.
* @param {Function} list Array of optional alternate pagelets that take it's place.
* @param {Function} fn The authorized callback.
* @returns {Pagelet}
* @api private
*/
Pagelet.readable('conditional', function conditional(req, list, fn) {
var pagelet = this;
if ('function' !== typeof fn) {
fn = list;
list = [];
}
/**
* Callback for the `pagelet.if` function to see if we're enabled or disabled.
* Use cached value in _active to prevent the same Pagelet being authorized
* multiple times for the same request.
*
* @param {Boolean} value Are we enabled or disabled.
* @api private
*/
function enabled(value) {
fn.call(pagelet, pagelet.active = value || false);
}
if ('boolean' === typeof pagelet._active) {
fn(pagelet.active);
} else if ('function' !== typeof this.if) {
fn(pagelet.active = true);
} else {
if (pagelet.if.length === 2) pagelet.if(req, enabled);
else pagelet.if(req, list, enabled);
}
return pagelet;
});
/**
* Destroy the pagelet and remove all the back references so it can be safely
* garbage collected.
*
* @api public
*/
Pagelet.readable('destroy', destroy([
'_temper', '_bigpipe', '_enabled', '_disabled', '_children'
], {
after: 'removeAllListeners'
}));
/**
* Expose the Pagelet on the exports and parse our the directory. This ensures
* that we can properly resolve all relative assets:
*
* ```js
* Pagelet.extend({
* ..
* }).on(module);
* ```
*
* The use of this function is for convenience and optional. Developers can
* choose to provide absolute paths to files.
*
* @param {Module} module The reference to the module object.
* @returns {Pagelet}
* @api public
*/
Pagelet.on = function on(module) {
var prototype = this.prototype
, dir = prototype.directory = path.dirname(module.filename);
//
// Resolve the view and error templates to ensure
// absolute paths are provided to Temper.
//
if (prototype.error) prototype.error = path.resolve(dir, prototype.error);
if (prototype.view) prototype.view = path.resolve(dir, prototype.view);
return module.exports = this;
};
/**
* Discover all pagelets recursive. Fabricate will create constructable
* instances from the provided value of prototype.pagelets.
*
* @param {String} parent Reference to the parent pagelet name.
* @return {Array} collection of pagelets instances.
* @api public
*/
Pagelet.children = function children(parent, stack) {
var pagelets = this.prototype.pagelets
, log = debug('pagelet:'+ parent);
stack = stack || [];
return fabricate(pagelets, {
source: this.prototype.directory,
recursive: 'string' === typeof pagelets
}).reduce(function each(stack, Pagelet) {
//
// Pagelet could be conditional, simple crawl this function
// again to get the children of each conditional.
//