-
Notifications
You must be signed in to change notification settings - Fork 60
/
vash-runtime-all.js
6041 lines (5102 loc) · 155 KB
/
vash-runtime-all.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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.vash = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
var debug = require('debug')
var lg = debug('vash:main');
var Lexer = require('./lib/lexer');
var Parser = require('./lib/parser');
var codegen = require('./lib/codegen');
var runtime = require('./runtime');
var helperbatch = require('./lib/helperbatch');
var copyrtl = require('./lib/util/copyrtl');
// Attach all runtime exports to enable backwards compatible behavior,
// like `vash.install` to still be accessible in a full build.
require('./lib/helpers');
copyrtl(exports, runtime);
exports.config = {
// Parser Options
favorText: false,
// TODO: are these even needed with proper codegen?
saveAT: false,
saveTextTag: false,
// Compiler Options
useWith: false,
htmlEscape: true,
helpersName: 'html',
modelName: 'model',
debug: true,
source: null,
simple: false,
// Runtime options
asHelper: false,
args: null // Internal, for compiled helpers
}
exports.version = require('./package.json').version;
exports.compileStream = function() {
// This could eventually handle waiting until a `null`
// is pushed into the lexer, etc.
throw new Error('NotImplemented');
}
exports.compile = function(markup, options) {
if(markup === '' || typeof markup !== 'string') {
throw new Error('Empty or non-string cannot be compiled');
}
var opts = copyrtl({}, exports.config, options || {});
var l = new Lexer();
l.write(markup);
var tokens = l.read();
var p = new Parser(opts);
p.write(tokens);
var more = true;
while(more !== null) more = p.read();
p.checkStack();
// Stash the original input (new lines normalized by the lexer).
opts.source = l.originalInput;
p.lg(p.dumpAST());
var compiled = codegen(p.stack[0], opts);
lg(compiled);
var tpl = runtime.link(compiled, opts);
return tpl;
}
///////////////////////////////////////////////////////////////////////////
// VASH.COMPILEHELPER
//
// Allow multiple helpers to be compiled as templates, for helpers that
// do a lot of markup output.
//
// Takes a template such as:
//
// vash.helpers.p = function(text){
// <p>@text</p>
// }
//
// And compiles it. The template is then added to `vash.helpers`.
//
// Returns the compiled templates as named properties of an object.
//
// This is string manipulation at its... something. It grabs the arguments
// and function name using a regex, not actual parsing. Definitely error-
// prone, but good enough. This is meant to facilitate helpers with complex
// markup, but if something more advanced needs to happen, a plain helper
// can be defined and markup added using the manual Buffer API.
exports['compileHelper'] = helperbatch.bind(null, 'helper', exports.compile);
///////////////////////////////////////////////////////////////////////////
// VASH.COMPILEBATCH
//
// Allow multiple templates to be contained within the same string.
// Templates are separated via a sourceURL-esque string:
//
// //@batch = tplname/or/path
//
// The separator is forgiving in terms of whitespace:
//
// // @ batch=tplname/or/path
//
// Is just as valid.
//
// Returns the compiled templates as named properties of an object.
exports['compileBatch'] = exports['batch'] = helperbatch.bind(null, 'batch', exports.compile);
},{"./lib/codegen":2,"./lib/helperbatch":4,"./lib/helpers":6,"./lib/lexer":9,"./lib/parser":24,"./lib/util/copyrtl":26,"./package.json":35,"./runtime":36,"debug":30}],2:[function(require,module,exports){
var debug = require('debug');
var lg = debug('vash:codegen');
var gens = {}
gens.VashProgram = function(node, opts, generate) {
return node.body.map(generate).join('');
}
gens.VashExplicitExpression = function(node, opts, generate) {
var str = node.values.map(generate).join('');
str = '(' + maybeHTMLEscape(node, opts, str) + ')';
if (parentIsContent(node)) {
str = bewrap(str);
}
return str;
}
gens.VashExpression = function(node, opts, generate) {
var str = node.values.map(generate).join('');
str = bewrap(maybeHTMLEscape(node, opts, str));
return str;
}
gens.VashRegex = function(node, opts, generate) {
var str = node.values.map(generate).join('');
str = maybeHTMLEscape(node, opts, str);
if (parentIsContent(node)) {
str = bewrap(str);
}
return str;
}
gens.VashMarkup = function(node, opts, generate) {
var isText = node.name === 'text';
var name = node.name ? bcwrap(node.name) : '';
var tagNameValue = name
+ (node.expression ? generate(node.expression) : '');
var tagOpen = ''
+ bcwrap('<')
+ tagNameValue
+ bcwrap(node.attributes.length ? ' ' : '')
+ node.attributes.map(generate).join(bcwrap(' '))
var values;
var tagClose;
if (node.isVoid) {
tagOpen += bcwrap(node.voidClosed ? ' />' : '>');
values = '';
tagClose = '';
} else {
tagOpen += bcwrap('>');
values = node.values.map(generate).join('');
tagClose = node.isClosed ? bcwrap('</') + tagNameValue + bcwrap('>') : '';
}
if (isText) {
tagOpen = tagClose = '';
}
return ''
+ (parentIsExpression(node) ? '(function () {' : '')
+ dbgstart(node, opts)
+ tagOpen
+ values
+ tagClose
+ dbgend(node, opts)
+ (parentIsExpression(node) ? '}())' : '')
}
gens.VashMarkupAttribute = function(node, opts, generate) {
var quote = node.rightIsQuoted || '';
quote = escapeMarkupContent(quote);
return ''
+ dbgstart(node, opts)
+ node.left.map(generate).join('')
+ (node.right.length || node.rightIsQuoted
? bcwrap('=' + quote)
+ node.right.map(generate).join('')
+ bcwrap(quote)
: '')
+ dbgend(node, opts);
}
gens.VashMarkupContent = function(node, opts, generate) {
return ''
+ dbgstart(node, opts)
+ node.values.map(generate).join('')
+ dbgend(node, opts);
}
gens.VashMarkupComment = function(node, opts, generate) {
return ''
+ bcwrap('<!--')
+ dbgstart(node, opts)
+ node.values.map(generate).join('')
+ dbgend(node, opts)
+ bcwrap('-->');
}
gens.VashBlock = function(node, opts, generate) {
var hasValues = node.values.length > 0;
var unsafeForDbg = node.keyword === 'switch'
|| !node.name
|| !hasValues;
var openBrace = hasValues || node.hasBraces
? '{' + (unsafeForDbg ? '' : dbgstart(node, opts))
: '';
var closeBrace = hasValues || node.hasBraces
? (unsafeForDbg ? '' : dbgend(node, opts)) + '}'
: '';
return ''
+ (node.keyword ? node.keyword : '')
+ node.head.map(generate).join('')
+ openBrace
+ node.values.map(generate).join('')
+ closeBrace
+ node.tail.map(generate).join('');
}
gens.VashIndexExpression = function(node, opts, generate) {
var str = node.values.map(generate).join('');
return '[' + str + ']';
}
gens.VashText = function(node, opts, generate) {
if (!node.value.length) return '';
return parentIsContent(node)
? ''
+ dbgstart(node, opts)
+ bcwrap(escapeMarkupContent(node.value))
+ dbgend(node, opts)
: node.value;
}
gens.VashComment = function(node, opts, generate) {
return '';
}
var reQuote = /(['"])/g;
var reEscapedQuote = /\\+(["'])/g;
var reLineBreak = /\n/g;
var reHelpersName = /HELPERSNAME/g;
var reModelName = /MODELNAME/g;
var reOriginalMarkup = /ORIGINALMARKUP/g;
function escapeMarkupContent(str) {
return str
.replace(/\\/g, '\\\\')
.replace(reQuote, '\\$1')
.replace(reLineBreak, '\\n');
}
var BUFFER_HEAD = '\n__vbuffer.push(';
var BUFFER_TAIL = ');\n';
// buffer content wrap
function bcwrap(str) {
return BUFFER_HEAD + '\'' + str.replace(/\n/, '\\n') + '\'' + BUFFER_TAIL;
}
// buffer expression wrap
function bewrap(str) {
return BUFFER_HEAD + str + BUFFER_TAIL;
}
function parentIsContent(node) {
return node.parent.type === 'VashMarkup'
|| node.parent.type === 'VashMarkupContent'
|| node.parent.type === 'VashMarkupComment'
|| node.parent.type === 'VashMarkupAttribute'
|| node.parent.type === 'VashProgram';
}
function parentIsExpression(node) {
return node.parent.type === 'VashExpression'
|| node.parent.type === 'VashExplicitExpression'
|| node.parent.type === 'VashIndexExpression';
}
function dbgstart(node, opts) {
return opts.debug
? ''
+ opts.helpersName + '.vl = ' + node.startloc.line + ', '
+ opts.helpersName + '.vc = ' + node.startloc.column + '; \n'
: '';
}
function dbgend(node, opts) {
return opts.debug
? ''
+ opts.helpersName + '.vl = ' + node.endloc.line + ', '
+ opts.helpersName + '.vc = ' + node.endloc.column + '; \n'
: '';
}
function maybeHTMLEscape(node, opts, str) {
if (parentIsContent(node) && opts.htmlEscape) {
return opts.helpersName + '.escape(' + str + ').toHtmlString()';
} else {
return str;
}
}
function replaceDevTokens(str, opts){
return str
.replace( reHelpersName, opts.helpersName )
.replace( reModelName, opts.modelName );
}
function head(opts){
var str = ''
+ (opts.debug ? 'try { \n' : '')
+ 'var __vbuffer = HELPERSNAME.buffer; \n'
+ 'HELPERSNAME.options = __vopts; \n'
+ 'MODELNAME = MODELNAME || {}; \n'
+ (opts.useWith ? 'with( MODELNAME ){ \n' : '');
str = replaceDevTokens(str, opts);
return str;
}
function helperHead(opts){
var str = ''
+ (opts.debug ? 'try { \n' : '')
+ 'var __vbuffer = this.buffer; \n'
+ 'var MODELNAME = this.model; \n'
+ 'var HELPERSNAME = this; \n';
str = replaceDevTokens(str, opts);
return str;
}
function tail(opts){
var str = ''
+ (opts.simple
? 'return HELPERSNAME.buffer.join(""); \n'
: ';(__vopts && __vopts.onRenderEnd && __vopts.onRenderEnd(null, HELPERSNAME)); \n'
+ 'return (__vopts && __vopts.asContext) \n'
+ ' ? HELPERSNAME \n'
+ ' : HELPERSNAME.toString(); \n' )
+ (opts.useWith ? '} \n' : '')
+ (opts.debug ? '} catch( e ){ \n'
+ ' HELPERSNAME.reportError( e, HELPERSNAME.vl, HELPERSNAME.vc, "ORIGINALMARKUP", "!LB!", true ); \n'
+ '} \n' : '');
str = replaceDevTokens(str, opts)
.replace(reOriginalMarkup, escapeForDebug(opts.source));
return str;
}
function helperTail(opts){
var str = ''
+ (opts.debug ? '} catch( e ){ \n'
+ ' HELPERSNAME.reportError( e, HELPERSNAME.vl, HELPERSNAME.vc, "ORIGINALMARKUP", "!LB!", true ); \n'
+ '} \n' : '');
str = replaceDevTokens(str, opts)
.replace(reOriginalMarkup, escapeForDebug(opts.source));
return str;
}
function escapeForDebug( str ){
return str
.replace(reLineBreak, '!LB!')
.replace(reQuote, '\\$1')
.replace(reEscapedQuote, '\\$1')
}
// Not necessary, but provides faster execution when not in debug mode
// and looks nicer.
function condenseContent(str) {
return str
.replace(/'\);\n+__vbuffer.push\('/g, '')
.replace(/\n+/g, '\n');
}
function generate(node, opts) {
function gen(opts, node) {
lg('Entering ' + node.type);
var str = gens[node.type](node, opts, genChild);
lg('Leaving ' + node.type);
return str;
function genChild(child) {
if (!child.parent) child.parent = node;
lg('Generating child type %s of parent type %s', child.type, node.type)
return gen(opts, child);
}
}
var generated = gen(opts, node);
var body;
if(!opts.asHelper){
body = head(opts) + generated + tail(opts);
} else {
body = helperHead(opts) + generated + helperTail(opts);
}
return opts.debug
? body
: condenseContent(body);
}
module.exports = generate;
},{"debug":30}],3:[function(require,module,exports){
exports.context = function(input, lineno, columnno, linebreak) {
linebreak = linebreak || '!LB!';
var lines = input.split(linebreak)
, contextSize = lineno === 0 && columnno === 0 ? lines.length - 1 : 3
, start = Math.max(0, lineno - contextSize)
, end = Math.min(lines.length, lineno + contextSize);
return lines
.slice(start, end)
.map(function(line, i, all){
var curr = i + start + 1;
return (curr === lineno ? ' > ' : ' ')
+ (curr < 10 ? ' ' : '')
+ curr
+ ' | '
+ line;
}).join('\n');
}
},{}],4:[function(require,module,exports){
var slice = Array.prototype.slice
, reHelperFuncHead = /vash\.helpers\.([^= ]+?)\s*=\s*function([^(]*?)\(([^)]*?)\)\s*{/
, reHelperFuncTail = /\}$/
, reBatchSeparator = /^\/\/\s*@\s*batch\s*=\s*(.*?)$/
// The logic for compiling a giant batch of templates or several
// helpers is nearly exactly the same. The only difference is the
// actual compilation method called, and the regular expression that
// determines how the giant string is split into named, uncompiled
// template strings.
module.exports = function compile(type, compile, str, options){
var separator = type === 'helper'
? reHelperFuncHead
: reBatchSeparator;
var tpls = splitByNamedTpl(separator, str, function(ma, name){
return name.replace(/^\s+|\s+$/, '');
}, type === 'helper' ? true : false);
if(tpls){
Object.keys(tpls).forEach(function(path){
tpls[path] = type === 'helper'
? compileSingleHelper(compile, tpls[path], options)
: compile('@{' + tpls[path] + '}', options);
});
tpls.toClientString = function(){
return Object.keys(tpls).reduce(function(prev, curr){
if(curr === 'toClientString'){
return prev;
}
return prev + tpls[curr].toClientString() + '\n';
}, '')
}
}
return tpls;
}
// Given a separator regex and a function to transform the regex result
// into a name, take a string, split it, and group the rejoined strings
// into an object.
// This is useful for taking a string, such as
//
// // tpl1
// what what
// and more
//
// // tpl2
// what what again
//
// and returning:
//
// {
// tpl1: 'what what\nand more\n',
// tpl2: 'what what again'
// }
var splitByNamedTpl = function(reSeparator, markup, resultHandler, keepSeparator){
var lines = markup.split(/[\n\r]/g)
,tpls = {}
,paths = []
,currentPath = ''
lines.forEach(function(line, i){
var pathResult = reSeparator.exec(line)
,handlerResult = pathResult ? resultHandler.apply(pathResult, pathResult) : null
if(handlerResult){
currentPath = handlerResult;
tpls[currentPath] = [];
}
if((!handlerResult || keepSeparator) && line){
tpls[currentPath].push(line);
}
});
Object.keys(tpls).forEach(function(key){
tpls[key] = tpls[key].join('\n');
})
return tpls;
}
var compileSingleHelper = function(compile, str, options){
options = options || {};
// replace leading/trailing spaces, and parse the function head
var def = str.replace(/^[\s\n\r]+|[\s\n\r]+$/, '').match(reHelperFuncHead)
// split the function arguments, kill all whitespace
,args = def[3].split(',').map(function(arg){ return arg.replace(' ', '') })
,name = def[1]
,body = str
.replace( reHelperFuncHead, '' )
.replace( reHelperFuncTail, '' )
// Wrap body in @{} to simulate it actually being inside a function
// definition, since we manually stripped it. Without this, statements
// such as `this.what = "what";` that are at the beginning of the body
// will be interpreted as markup.
body = '@{' + body + '}';
// `args` and `asHelper` inform `vash.compile/link` that this is a helper
options.args = args;
options.asHelper = name;
return compile(body, options);
}
},{}],5:[function(require,module,exports){
var helpers = require('../../runtime').helpers;
///////////////////////////////////////////////////////////////////////////
// EXAMPLE HELPER: syntax highlighting
helpers.config.highlighter = null;
helpers.highlight = function(lang, cb){
// context (this) is and instance of Helpers, aka a rendering context
// mark() returns an internal `Mark` object
// Use it to easily capture output...
var startMark = this.buffer.mark();
// cb() is simply a user-defined function. It could (and should) contain
// buffer additions, so we call it...
cb( this.model );
// ... and then use fromMark() to grab the output added by cb().
var cbOutLines = this.buffer.fromMark(startMark);
// The internal buffer should now be back to where it was before this
// helper started, and the output is completely contained within cbOutLines.
this.buffer.push( '<pre><code>' );
if( helpers.config.highlighter ){
this.buffer.push( helpers.config.highlighter(lang, cbOutLines.join('')).value );
} else {
this.buffer.push( cbOutLines );
}
this.buffer.push( '</code></pre>' );
// returning is allowed, but could cause surprising effects. A return
// value will be directly added to the output directly following the above.
}
},{"../../runtime":36}],6:[function(require,module,exports){
require('./trim');
require('./highlight');
require('./layout');
module.exports = require('../../runtime');
},{"../../runtime":36,"./highlight":5,"./layout":7,"./trim":8}],7:[function(require,module,exports){
(function (global){
var helpers = require('../../runtime').helpers;
var copyrtl = require('../util/copyrtl');
// For now, using the layout helpers requires a full build. For now.
var vash = require('../../index');
module.exports = vash;
///////////////////////////////////////////////////////////////////////////
// LAYOUT HELPERS
// semi hacky guard to prevent non-nodejs erroring
// switched from window not existing to global existing
// to avoid conflict with Jest where window is always defined(!)
if( typeof global !== 'undefined' ){
var fs = require('fs')
,path = require('path')
}
// TRUE implies that all TPLS are loaded and waiting in cache
helpers.config.browser = false;
vash.loadFile = function(filepath, options, cb){
// options are passed in via Express
// {
// settings:
// {
// env: 'development',
// 'jsonp callback name': 'callback',
// 'json spaces': 2,
// views: '/Users/drew/Dropbox/js/vash/test/fixtures/views',
// 'view engine': 'vash'
// },
// _locals: [Function: locals],
// cache: false
// }
// The only required options are:
//
// settings: {
// views: ''
// }
options = copyrtl({}, vash.config, options || {});
var browser = helpers.config.browser
,tpl
if( !browser && options.settings && options.settings.views ){
// this will really only have an effect on windows
filepath = path.normalize( filepath );
if( filepath.indexOf( path.normalize( options.settings.views ) ) === -1 ){
// not an absolute path
filepath = path.join( options.settings.views, filepath );
}
if( !path.extname( filepath ) ){
filepath += '.' + ( options.settings['view engine'] || 'vash' )
}
}
// TODO: auto insert 'model' into arguments
try {
// if browser, tpl must exist in tpl cache
tpl = options.cache || browser
? helpers.tplcache[filepath] || ( helpers.tplcache[filepath] = vash.compile(fs.readFileSync(filepath, 'utf8')) )
: vash.compile( fs.readFileSync(filepath, 'utf8') )
cb && cb(null, tpl);
} catch(e) {
cb && cb(e, null);
}
}
vash.renderFile = vash.__express = function(filepath, options, cb){
vash.loadFile(filepath, options, function(err, tpl){
// auto setup an `onRenderEnd` callback to seal the layout
var prevORE = options.onRenderEnd;
cb( err, !err && tpl(options, function(err, ctx){
ctx.finishLayout()
if( prevORE ) prevORE(err, ctx);
}) );
})
}
helpers._ensureLayoutProps = function(){
this.appends = this.appends || {};
this.prepends = this.prepends || {};
this.blocks = this.blocks || {};
this.blockMarks = this.blockMarks || {};
}
helpers.finishLayout = function(){
this._ensureLayoutProps();
var self = this, name, marks, blocks, prepends, appends, injectMark, m, content, block
// each time `.block` is called, a mark is added to the buffer and
// the `blockMarks` stack. Find the newest/"highest" mark on the stack
// for each named block, and insert the rendered content (prepends, block, appends)
// in place of that mark
for( name in this.blockMarks ){
marks = this.blockMarks[name];
prepends = this.prepends[name];
blocks = this.blocks[name];
appends = this.appends[name];
injectMark = marks.pop();
// mark current point in buffer in prep to grab rendered content
m = this.buffer.mark();
prepends && prepends.forEach(function(p){ self.buffer.pushConcat( p ); });
// a block might never have a callback defined, e.g. is optional
// with no default content
block = blocks.pop();
block && this.buffer.pushConcat( block );
appends && appends.forEach(function(a){ self.buffer.pushConcat( a ); });
// grab rendered content
content = this.buffer.fromMark( m )
// Join, but split out the VASHMARKS so further buffer operations are still
// sane. Join is required to prevent max argument errors when large templates
// are being used.
content = compactContent(content);
// Prep for apply, ensure the right location (mark) is used for injection.
content.unshift( injectMark, 0 );
this.buffer.spliceMark.apply( this.buffer, content );
}
for( name in this.blockMarks ){
// kill all other marks registered as blocks
this.blockMarks[name].forEach(function(m){ m.destroy(); });
}
// this should only be able to happen once
delete this.blockMarks;
delete this.prepends;
delete this.blocks;
delete this.appends;
// and return the whole thing
return this.toString();
}
// Given an array, condense all the strings to as few array elements
// as possible, while preserving `Mark`s as individual elements.
function compactContent(content) {
var re = vash.Mark.re;
var parts = [];
var str = '';
content.forEach(function(part) {
if (re.exec(part)) {
parts.push(str, part);
str = '';
} else {
// Ensure `undefined`s are not `toString`ed
str += (part || '');
}
});
// And don't forget the rest.
parts.push(str);
return parts;
}
helpers.extend = function(path, ctn){
var self = this
,buffer = this.buffer
,origModel = this.model
,layoutCtx;
this._ensureLayoutProps();
// this is a synchronous callback
vash.loadFile(path, this.model, function(err, tpl){
if (err) throw err;
// any content that is outside of a block but within an "extend"
// callback is completely thrown away, as the destination for such
// content is undefined
var start = self.buffer.mark();
ctn(self.model);
// ... and just throw it away
var content = self.buffer.fromMark( start )
// TODO: unless it's a mark id? Removing everything means a block
// MUST NOT be defined in an extend callback
//,filtered = content.filter( vash.Mark.uidLike )
//self.buffer.push( filtered );
// `isExtending` is necessary because named blocks in the layout
// will be interpreted after named blocks in the content. Since
// layout named blocks should only be used as placeholders in the
// event that their content is redefined, `block` must know to add
// the defined content at the head or tail or the block stack.
self.isExtending = true;
tpl( self.model, { context: self } );
self.isExtending = false;
});
this.model = origModel;
}
helpers.include = function(name, model){
var self = this
,buffer = this.buffer
,origModel = this.model;
// TODO: should this be in a new context? Jade looks like an include
// is not shared with parent context
// this is a synchronous callback
vash.loadFile(name, this.model, function(err, tpl){
if (err) throw err;
tpl( model || self.model, { context: self } );
});
this.model = origModel;
}
helpers.block = function(name, ctn){
this._ensureLayoutProps();
var self = this
// ensure that we have a list of marks for this name
,marks = this.blockMarks[name] || ( this.blockMarks[name] = [] )
// ensure a list of blocks for this name
,blocks = this.blocks[name] || ( this.blocks[name] = [] )
,start
,content;
// render out the content immediately, if defined, to attempt to grab
// "dependencies" like other includes, blocks, etc
if( ctn ){
start = this.buffer.mark();
ctn( this.model );
content = this.buffer.fromMark( start );
// add rendered content to named list of blocks
if( content.length && !this.isExtending ){
blocks.push( content );
}
// if extending the rendered content must be allowed to be redefined
if( content.length && this.isExtending ){
blocks.unshift( content );
}
}
// mark the current location as "where this block will end up"
marks.push( this.buffer.mark( 'block-' + name ) );
}
helpers._handlePrependAppend = function( type, name, ctn ){
this._ensureLayoutProps();
var start = this.buffer.mark()
,content
,stack = this[type]
,namedStack = stack[name] || ( stack[name] = [] )
ctn( this.model );
content = this.buffer.fromMark( start );
namedStack.push( content );
}
helpers.append = function(name, ctn){
this._handlePrependAppend( 'appends', name, ctn );
}
helpers.prepend = function(name, ctn){
this._handlePrependAppend( 'prepends', name, ctn );
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../../index":1,"../../runtime":36,"../util/copyrtl":26,"fs":"fs","path":"path"}],8:[function(require,module,exports){
var helpers = require('../../runtime').helpers;
// Trim whitespace from the start and end of a string
helpers.trim = function(val){
return val.replace(/^\s*|\s*$/g, '');
}
},{"../../runtime":36}],9:[function(require,module,exports){
var debug = require('debug');
var tokens = require('./tokens');
// This pattern and basic lexer code were originally from the
// Jade lexer, but have been modified:
// https://github.com/visionmedia/jade/blob/master/lib/lexer.js
function VLexer(){
this.lg = debug('vash:lexer');
this.input = '';
this.originalInput = '';
this.lineno = 1;
this.charno = 0;
}
module.exports = VLexer;
VLexer.prototype = {
write: function(input) {
var normalized = input.replace(/\r\n|\r/g, '\n');
// Kill BOM if this is the first chunk.
if (this.originalInput.length == 0) {
normalized = normalized.replace(/^\uFEFF/, '');
}
this.input += normalized;
this.originalInput += normalized;
return true;
},
read: function() {
var out = []
, result;
while(this.input.length) {
result = this.advance();
if (result) {
out.push(result);
this.lg('Read %s at line %d, column %d with content %s',
result.type, result.line, result.chr, result.val.replace(/(\n)/, '\\n'));
}
}
return out;
},
scan: function(regexp, type){
var captures, token;
if (captures = regexp.exec(this.input)) {
this.input = this.input.substr((captures[1].length));
token = {
type: type
,line: this.lineno
,chr: this.charno
,val: captures[1] || ''
,toString: function(){
return '[' + this.type
+ ' (' + this.line + ',' + this.chr + '): '
+ this.val.replace(/(\n)/, '\\n') + ']';
}
};
this.charno += captures[0].length;
return token;
}
}
,advance: function() {
var i, name, test, result;
for(i = 0; i < tokens.tests.length; i += 2){
test = tokens.tests[i+1];
test.displayName = tokens.tests[i];
if(typeof test === 'function'){
// assume complex callback
result = test.call(this);
}