/
TemplateDefaultFilters.cs
1111 lines (944 loc) · 52.4 KB
/
TemplateDefaultFilters.cs
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ServiceStack.Text;
using ServiceStack.Text.Json;
namespace ServiceStack.Templates
{
// ReSharper disable InconsistentNaming
public partial class TemplateDefaultFilters : TemplateFilter
{
public static TemplateDefaultFilters Instance = new TemplateDefaultFilters();
// methods without arguments can be used in bindings, e.g. {{ now | dateFormat }}
public DateTime now() => DateTime.Now;
public DateTime utcNow() => DateTime.UtcNow;
public DateTime addTicks(DateTime target, int count) => target.AddTicks(count);
public DateTime addMilliseconds(DateTime target, int count) => target.AddMilliseconds(count);
public DateTime addSeconds(DateTime target, int count) => target.AddSeconds(count);
public DateTime addMinutes(DateTime target, int count) => target.AddMinutes(count);
public DateTime addHours(DateTime target, int count) => target.AddHours(count);
public DateTime addDays(DateTime target, int count) => target.AddDays(count);
public DateTime addMonths(DateTime target, int count) => target.AddMonths(count);
public DateTime addYears(DateTime target, int count) => target.AddYears(count);
public List<object> itemsOf(int count, object target)
{
AssertWithinMaxQuota(count);
var to = new List<object>();
for (var i = 0; i < count; i++)
{
to.Add(target);
}
return to;
}
public object times(int count) => AssertWithinMaxQuota(count).Times().ToList();
public object range(int count) => Enumerable.Range(0, AssertWithinMaxQuota(count));
public object range(int start, int count) => Enumerable.Range(start, AssertWithinMaxQuota(count));
public bool isEven(int value) => value % 2 == 0;
public bool isOdd(int value) => !isEven(value);
public static bool isTrue(object target) => target is bool b && b;
public static bool isFalsy(object target)
{
if (target == null || target == JsNull.Value)
return true;
if (target is string s)
return string.IsNullOrEmpty(s);
if (target is bool b)
return !b;
if (target is int i)
return i == 0;
if (target is long l)
return l == 0;
if (target is double d)
return d == 0 || double.IsNaN(d);
return false;
}
[HandleUnknownValue] public object iif(object test, object ifTrue, object ifFalse) => isTrue(test) ? ifTrue : ifFalse;
[HandleUnknownValue] public object when(object returnTarget, object test) => @if(returnTarget, test); //alias
[HandleUnknownValue] public object ifNot(object returnTarget, object test) => !isTrue(test) ? returnTarget : null;
[HandleUnknownValue] public object unless(object returnTarget, object test) => ifNot(returnTarget, test); //alias
[HandleUnknownValue] public object otherwise(object returnTaget, object elseReturn) => returnTaget ?? elseReturn;
[HandleUnknownValue] public object ifFalsy(object returnTarget, object test) => isFalsy(test) ? returnTarget : null;
[HandleUnknownValue] public object ifTruthy(object returnTarget, object test) => !isFalsy(test) ? returnTarget : null;
[HandleUnknownValue] public object falsy(object test, object returnIfFalsy) => isFalsy(test) ? returnIfFalsy : null;
[HandleUnknownValue] public object truthy(object test, object returnIfTruthy) => !isFalsy(test) ? returnIfTruthy : null;
[HandleUnknownValue] public bool isNull(object test) => test == null || test == JsNull.Value;
[HandleUnknownValue] public bool isNotNull(object test) => !isNull(test);
[HandleUnknownValue] public bool exists(object test) => !isNull(test);
[HandleUnknownValue] public bool isZero(double value) => value.Equals(0d);
[HandleUnknownValue] public bool isPositive(double value) => value > 0;
[HandleUnknownValue] public bool isNegative(double value) => value < 0;
[HandleUnknownValue] public bool isNaN(double value) => double.IsNaN(value);
[HandleUnknownValue] public bool isInfinity(double value) => double.IsInfinity(value);
[HandleUnknownValue] public object ifExists(object target) => target;
[HandleUnknownValue] public object ifExists(object returnTarget, object test) => test != null ? returnTarget : null;
[HandleUnknownValue] public object ifNotExists(object returnTarget, object target) => target == null ? returnTarget : null;
[HandleUnknownValue] public object ifNo(object returnTarget, object target) => target == null ? returnTarget : null;
[HandleUnknownValue] public object ifNotEmpty(object target) => isEmpty(target) ? null : target;
[HandleUnknownValue] public object ifNotEmpty(object returnTarget, object test) => isEmpty(test) ? null : returnTarget;
[HandleUnknownValue] public object ifEmpty(object returnTarget, object test) => isEmpty(test) ? returnTarget : null;
[HandleUnknownValue] public object ifTrue(object returnTarget, object test) => isTrue(test) ? returnTarget : null;
[HandleUnknownValue] public object ifFalse(object returnTarget, object test) => !isTrue(test) ? returnTarget : null;
[HandleUnknownValue]
public bool isEmpty(object target)
{
if (isNull(target))
return true;
if (target is string s)
return s == string.Empty;
if (target is IEnumerable e)
return !e.GetEnumerator().MoveNext();
return false;
}
[HandleUnknownValue] public StopExecution end() => StopExecution.Value;
[HandleUnknownValue] public Task end(TemplateScopeContext scope, object ignore) => TypeConstants.EmptyTask;
[HandleUnknownValue] public StopExecution end(object ignore) => StopExecution.Value;
[HandleUnknownValue] public object endIfNull(object target) => isNull(target) ? StopExecution.Value : target;
[HandleUnknownValue] public object endIfNull(object ignoreTarget, object target) => isNull(target) ? StopExecution.Value : target;
[HandleUnknownValue] public object endIfNotNull(object target) => !isNull(target) ? (object) StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object endIfNotNull(object ignoreTarget, object target) => !isNull(target) ? (object) StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object endIfExists(object target) => !isNull(target) ? (object) StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object endIfExists(object ignoreTarget, object target) => !isNull(target) ? (object) StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object endIfEmpty(object target) => isEmpty(target) ? StopExecution.Value : target;
[HandleUnknownValue] public object endIfEmpty(object ignoreTarget, object target) => isEmpty(target) ? StopExecution.Value : target;
[HandleUnknownValue] public object endIfNotEmpty(object target) => !isEmpty(target) ? (object) StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object endIfNotEmpty(object ignoreTarget, object target) => !isEmpty(target) ? (object) StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object endIfFalsy(object target) => isFalsy(target) ? (object) StopExecution.Value : target;
[HandleUnknownValue] public object endIfFalsy(object ignoreTarget, object target) => isFalsy(target) ? (object) StopExecution.Value : target;
[HandleUnknownValue] public object endIfTruthy(object target) => !isFalsy(target) ? (object) StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object endIfTruthy(object ignoreTarget, object target) => !isFalsy(target) ? (object) StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object endIf(object test) => isTrue(test) ? (object)StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object endIf(object returnTarget, bool test) => test ? StopExecution.Value : returnTarget;
[HandleUnknownValue] public object endIfAny(TemplateScopeContext scope, object target, object expression) => any(scope, target, expression) ? StopExecution.Value : target;
[HandleUnknownValue] public object endIfAll(TemplateScopeContext scope, object target, object expression) => all(scope, target, expression) ? StopExecution.Value : target;
[HandleUnknownValue] public object endWhere(TemplateScopeContext scope, object target, object expression) => endWhere(scope, target, expression, null);
[HandleUnknownValue]
public object endWhere(TemplateScopeContext scope, object target, object expression, object scopeOptions)
{
var literal = scope.AssertExpression(nameof(count), expression);
var scopedParams = scope.GetParamsWithItemBinding(nameof(count), scopeOptions, out string itemBinding);
literal.ParseConditionExpression(out ConditionExpression expr);
scope.AddItemToScope(itemBinding, target);
var result = expr.Evaluate(scope);
return result
? StopExecution.Value
: target;
}
[HandleUnknownValue] public object ifEnd(bool test) => test ? (object)StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object ifEnd(object ignoreTarget, bool test) => test ? (object)StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object ifNotEnd(bool test) => !test ? (object)StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object ifNotEnd(object ignoreTarget, bool test) => !test ? (object)StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object onlyIfNull(object target) => !isNull(target) ? (object) StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object onlyIfNull(object ignoreTarget, object target) => !isNull(target) ? (object) StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object onlyIfNotNull(object target) => isNull(target) ? StopExecution.Value : target;
[HandleUnknownValue] public object onlyIfNotNull(object ignoreTarget, object target) => isNull(target) ? StopExecution.Value : target;
[HandleUnknownValue] public object onlyIfExists(object target) => isNull(target) ? (object) StopExecution.Value : target;
[HandleUnknownValue] public object onlyIfExists(object ignoreTarget, object target) => isNull(target) ? (object) StopExecution.Value : target;
[HandleUnknownValue] public object onlyIfEmpty(object target) => !isEmpty(target) ? (object) StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object onlyIfEmpty(object ignoreTarget, object target) => !isEmpty(target) ? (object) StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object onlyIfNotEmpty(object target) => isEmpty(target) ? (object) StopExecution.Value : target;
[HandleUnknownValue] public object onlyIfNotEmpty(object ignoreTarget, object target) => isEmpty(target) ? (object) StopExecution.Value : target;
[HandleUnknownValue] public object onlyIfFalsy(object target) => !isFalsy(target) ? (object) StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object onlyIfFalsy(object ignoreTarget, object target) => !isFalsy(target) ? (object) StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object onlyIfTruthy(object target) => isFalsy(target) ? (object) StopExecution.Value : target;
[HandleUnknownValue] public object onlyIfTruthy(object ignoreTarget, object target) => isFalsy(target) ? (object) StopExecution.Value : target;
[HandleUnknownValue] public object onlyIf(object test) => !isTrue(test) ? (object)StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object onlyIf(object returnTarget, bool test) => !test ? StopExecution.Value : returnTarget;
[HandleUnknownValue] public object onlyIfAny(TemplateScopeContext scope, object target, object expression) => !any(scope, target, expression) ? StopExecution.Value : target;
[HandleUnknownValue] public object onlyIfAll(TemplateScopeContext scope, object target, object expression) => !all(scope, target, expression) ? StopExecution.Value : target;
[HandleUnknownValue] public object onlyWhere(TemplateScopeContext scope, object target, object expression) => onlyWhere(scope, target, expression, null);
[HandleUnknownValue]
public object onlyWhere(TemplateScopeContext scope, object target, object expression, object scopeOptions)
{
var literal = scope.AssertExpression(nameof(count), expression);
var scopedParams = scope.GetParamsWithItemBinding(nameof(count), scopeOptions, out string itemBinding);
literal.ParseConditionExpression(out ConditionExpression expr);
scope.AddItemToScope(itemBinding, target);
var result = expr.Evaluate(scope);
return result
? target
: StopExecution.Value;
}
[HandleUnknownValue] public object ifOnly(bool test) => !test ? (object)StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object ifOnly(object ignoreTarget, bool test) => !test ? (object)StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object ifNotOnly(bool test) => test ? (object)StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object ifNotOnly(object ignoreTarget, bool test) => test ? (object)StopExecution.Value : IgnoreResult.Value;
[HandleUnknownValue] public object ifDo(object test) => isTrue(test) ? (object)IgnoreResult.Value : StopExecution.Value;
[HandleUnknownValue] public object ifDo(object ignoreTarget, object test) => isTrue(test) ? (object)IgnoreResult.Value : StopExecution.Value;
[HandleUnknownValue] public object doIf(object test) => isTrue(test) ? (object)IgnoreResult.Value : StopExecution.Value;
[HandleUnknownValue] public object doIf(object ignoreTarget, object test) => isTrue(test) ? (object)IgnoreResult.Value : StopExecution.Value;
[HandleUnknownValue] public object ifUse(object test, object useValue) => isTrue(test) ? useValue : StopExecution.Value;
[HandleUnknownValue] public object ifShow(object test, object useValue) => isTrue(test) ? useValue : StopExecution.Value;
[HandleUnknownValue] public object ifShowRaw(object test, object useValue) => isTrue(test) ? (object) raw(useValue) : StopExecution.Value;
[HandleUnknownValue] public object useIf(object useValue, object test) => isTrue(test) ? useValue : StopExecution.Value;
[HandleUnknownValue] public object showIf(object useValue, object test) => isTrue(test) ? useValue : StopExecution.Value;
public object use(object ignoreTarget, object useValue) => useValue;
public object show(object ignoreTarget, object useValue) => useValue;
public IRawString showRaw(object ignoreTarget, string content) => content.ToRawString();
public object useFmt(object ignoreTarget, string format, object arg) => fmt(format, arg);
public object useFmt(object ignoreTarget, string format, object arg1, object arg2) => fmt(format, arg1, arg2);
public object useFmt(object ignoreTarget, string format, object arg1, object arg2, object arg3) => fmt(format, arg1, arg2, arg3);
public object useFormat(object ignoreTarget, object arg, string fmt) => format(arg, fmt);
public object showFmt(object ignoreTarget, string format, object arg) => fmt(format, arg);
public object showFmt(object ignoreTarget, string format, object arg1, object arg2) => fmt(format, arg1, arg2);
public object showFmt(object ignoreTarget, string format, object arg1, object arg2, object arg3) => fmt(format, arg1, arg2, arg3);
public object showFormat(object ignoreTarget, object arg, string fmt) => format(arg, fmt);
public IRawString showFmtRaw(object ignoreTarget, string format, object arg) => raw(fmt(format, arg));
public IRawString showFmtRaw(object ignoreTarget, string format, object arg1, object arg2) => raw(fmt(format, arg1, arg2));
public IRawString showFmtRaw(object ignoreTarget, string format, object arg1, object arg2, object arg3) => raw(fmt(format, arg1, arg2, arg3));
[HandleUnknownValue] public bool isString(object target) => target is string;
[HandleUnknownValue] public bool isInt(object target) => target is int;
[HandleUnknownValue] public bool isLong(object target) => target is long;
[HandleUnknownValue] public bool isInteger(object target) => target?.GetType()?.IsIntegerType() == true;
[HandleUnknownValue] public bool isDouble(object target) => target is double;
[HandleUnknownValue] public bool isFloat(object target) => target is float;
[HandleUnknownValue] public bool isDecimal(object target) => target is decimal;
[HandleUnknownValue] public bool isBool(object target) => target is bool;
[HandleUnknownValue] public bool isList(object target) => target is IEnumerable && !(target is IDictionary) && !(target is string);
[HandleUnknownValue] public bool isEnumerable(object target) => target is IEnumerable;
[HandleUnknownValue] public bool isDictionary(object target) => target is IDictionary;
[HandleUnknownValue] public bool isChar(object target) => target is char;
[HandleUnknownValue] public bool isChars(object target) => target is char[];
[HandleUnknownValue] public bool isByte(object target) => target is byte;
[HandleUnknownValue] public bool isBytes(object target) => target is byte[];
[HandleUnknownValue] public bool isObjectDictionary(object target) => target is IDictionary<string, object>;
[HandleUnknownValue] public bool isStringDictionary(object target) => target is IDictionary<string, string>;
[HandleUnknownValue] public bool isType(object target, string typeName) => typeName.EqualsIgnoreCase(target?.GetType()?.Name);
[HandleUnknownValue] public bool isNumber(object target) => target?.GetType().IsNumericType() == true;
[HandleUnknownValue] public bool isRealNumber(object target) => target?.GetType().IsRealNumberType() == true;
[HandleUnknownValue] public bool isEnum(object target) => target?.GetType().IsEnum == true;
[HandleUnknownValue] public bool isArray(object target) => target?.GetType().IsArray == true;
[HandleUnknownValue] public bool isAnonObject(object target) => target?.GetType().IsAnonymousType() == true;
[HandleUnknownValue] public bool isClass(object target) => target?.GetType().IsClass == true;
[HandleUnknownValue] public bool isValueType(object target) => target?.GetType().IsValueType == true;
[HandleUnknownValue] public bool isDto(object target) => target?.GetType().IsDto() == true;
[HandleUnknownValue] public bool isTuple(object target) => target?.GetType().IsTuple() == true;
[HandleUnknownValue] public bool isKeyValuePair(object target) => "KeyValuePair`2".Equals(target?.GetType().Name);
[HandleUnknownValue] public int length(object target) => target is IEnumerable e ? e.Cast<object>().Count() : 0;
[HandleUnknownValue] public bool hasMinCount(object target, int minCount) => target is IEnumerable e && e.Cast<object>().Count() >= minCount;
[HandleUnknownValue] public bool hasMaxCount(object target, int maxCount) => target is IEnumerable e && e.Cast<object>().Count() <= maxCount;
public bool or(object lhs, object rhs) => isTrue(lhs) || isTrue(rhs);
public bool and(object lhs, object rhs) => isTrue(lhs) && isTrue(rhs);
public bool equals(object target, object other) =>
target == null || other == null
? target == other
: target.GetType() == other.GetType()
? target.Equals(other)
: target.Equals(other.ConvertTo(target.GetType()));
public bool notEquals(object target, object other) => !equals(target, other);
public bool greaterThan(object target, object other) => compareTo(target, other, i => i > 0);
public bool greaterThanEqual(object target, object other) => compareTo(target, other, i => i >= 0);
public bool lessThan(object target, object other) => compareTo(target, other, i => i < 0);
public bool lessThanEqual(object target, object other) => compareTo(target, other, i => i <= 0);
//aliases
public bool not(bool target) => !target;
public bool eq(object target, object other) => equals(target, other);
public bool not(object target, object other) => notEquals(target, other);
public bool gt(object target, object other) => greaterThan(target, other);
public bool gte(object target, object other) => greaterThanEqual(target, other);
public bool lt(object target, object other) => lessThan(target, other);
public bool lte(object target, object other) => lessThanEqual(target, other);
internal static bool compareTo(object target, object other, Func<int, bool> fn)
{
if (target == null || target == JsNull.Value)
throw new ArgumentNullException(nameof(target));
if (other == null)
throw new ArgumentNullException(nameof(other));
if (target is IComparable c)
{
return target.GetType() == other?.GetType()
? fn(c.CompareTo(other))
: fn(c.CompareTo(other.ConvertTo(target.GetType())));
}
throw new NotSupportedException($"{target} is not IComparable");
}
public object echo(object value) => value;
public IRawString pass(string target) => ("{{ " + target + " }}").ToRawString();
public IEnumerable join(IEnumerable<object> values) => join(values, ",");
public IEnumerable join(IEnumerable<object> values, string delimiter) => values.Map(x => x.AsString()).Join(delimiter);
public IEnumerable<object> reverse(TemplateScopeContext scope, IEnumerable<object> original) => original.Reverse();
public KeyValuePair<string, object> keyValuePair(string key, object value) => new KeyValuePair<string, object>(key, value);
public IgnoreResult prependTo(TemplateScopeContext scope, string value, string argName)
{
if (value == null)
return IgnoreResult.Value;
if (scope.ScopedParams.TryGetValue(argName, out object oString))
{
if (oString is string s)
{
scope.ScopedParams[argName] = value + s;
}
}
else
{
scope.ScopedParams[argName] = value;
}
return IgnoreResult.Value;
}
public IgnoreResult appendTo(TemplateScopeContext scope, string value, string argName)
{
if (value == null)
return IgnoreResult.Value;
if (scope.ScopedParams.TryGetValue(argName, out object oString))
{
if (oString is string s)
{
scope.ScopedParams[argName] = s + value;
}
}
else
{
scope.ScopedParams[argName] = value;
}
return IgnoreResult.Value;
}
public IgnoreResult addToStart(TemplateScopeContext scope, object value, string argName)
{
if (value == null)
return IgnoreResult.Value;
if (scope.ScopedParams.TryGetValue(argName, out object collection))
{
if (collection is IList l)
{
l.Insert(0, value);
}
else if (collection is IEnumerable e && !(collection is string))
{
var to = new List<object> { value };
foreach (var item in e)
{
to.Add(item);
}
scope.ScopedParams[argName] = to;
}
else throw new NotSupportedException(nameof(addToStart) + " can only add to an IEnumerable not a " + collection.GetType().Name);
}
else
{
if (value is IEnumerable && !(value is string))
scope.ScopedParams[argName] = value;
else
scope.ScopedParams[argName] = new List<object> { value };
}
return IgnoreResult.Value;
}
public IgnoreResult addTo(TemplateScopeContext scope, object value, string argName)
{
if (value == null)
return IgnoreResult.Value;
if (scope.ScopedParams.TryGetValue(argName, out object collection))
{
if (collection is IList l)
{
if (value is IEnumerable e && !(value is string))
{
foreach (var item in e)
{
l.Add(item);
}
}
else
{
l.Add(value);
}
}
else if (collection is IDictionary d)
{
if (value is KeyValuePair<string, object> kvp)
{
d[kvp.Key] = kvp.Value;
}
else if (value is IEnumerable<KeyValuePair<string, object>> kvps)
{
foreach (var entry in kvps)
{
d[entry.Key] = entry.Value;
}
}
else if (value is IDictionary dValue)
{
var keys = dValue.Keys;
foreach (var key in keys)
{
d[key] = dValue[key];
}
}
}
else if (collection is IEnumerable e && !(collection is string))
{
var to = new List<object>();
foreach (var item in e)
{
to.Add(item);
}
if (value is IEnumerable eValues && !(value is string))
{
foreach (var item in eValues)
{
to.Add(item);
}
}
else
{
to.Add(value);
}
scope.ScopedParams[argName] = to;
}
else throw new NotSupportedException(nameof(addTo) + " can only add to an IEnumerable not a " + collection.GetType().Name);
}
else
{
if (value is IEnumerable && !(value is string))
scope.ScopedParams[argName] = value;
else
scope.ScopedParams[argName] = new List<object> { value };
}
return IgnoreResult.Value;
}
public object assign(TemplateScopeContext scope, string argExpr, object value) //from filter
{
var targetEndPos = argExpr.IndexOfAny(new[] { '.', '[' });
if (targetEndPos == -1)
{
scope.ScopedParams[argExpr] = value;
}
else
{
var targetName = argExpr.Substring(0, targetEndPos);
if (!scope.ScopedParams.TryGetValue(targetName, out object target))
throw new NotSupportedException($"Cannot assign to non-existing '{targetName}' in {argExpr}");
scope.InvokeAssignExpression(argExpr, target, value);
}
return value;
}
public IgnoreResult assignTo(TemplateScopeContext scope, object value, string argName)
{
scope.ScopedParams[argName] = value;
return IgnoreResult.Value;
}
public Task assignTo(TemplateScopeContext scope, string argName) //from context filter
{
var ms = (MemoryStream)scope.OutputStream;
var value = ms.ReadFully().FromUtf8Bytes();
scope.ScopedParams[argName] = value;
ms.SetLength(0); //just capture output, don't write anything to the ResponseStream
return TypeConstants.EmptyTask;
}
public Task partial(TemplateScopeContext scope, object target) => partial(scope, target, null);
public async Task partial(TemplateScopeContext scope, object target, object scopedParams)
{
var pageName = target.ToString();
var pageParams = scope.AssertOptions(nameof(partial), scopedParams);
scope.TryGetPage(pageName, out TemplatePage page, out TemplateCodePage codePage);
if (page != null)
await page.Init();
await scope.WritePageAsync(page, codePage, pageParams);
}
public Task forEach(TemplateScopeContext scope, object target, object items) => forEach(scope, target, items, null);
public async Task forEach(TemplateScopeContext scope, object target, object items, object scopeOptions)
{
if (items is IEnumerable objs)
{
var scopedParams = scope.GetParamsWithItemBinding(nameof(select), scopeOptions, out string itemBinding);
var i = 0;
var itemScope = scope.CreateScopedContext(target.ToString(), scopedParams);
foreach (var item in objs)
{
itemScope.AddItemToScope(itemBinding, item, i++);
await itemScope.WritePageAsync();
}
}
else if (items != null)
{
throw new ArgumentException($"{nameof(forEach)} in '{scope.Page.VirtualPath}' requires an IEnumerable, but received a '{items.GetType().Name}' instead");
}
}
public string toString(object target) => target?.ToString();
public List<object> toList(IEnumerable target) => target.Map(x => x);
public object[] toArray(IEnumerable target) => target.Map(x => x).ToArray();
public char fromCharCode(int charCode) => Convert.ToChar(charCode);
public char toChar(object target) => target is string s && s.Length == 1 ? s[0] : target.ConvertTo<char>();
public char[] toChars(object target) => target is string s
? s.ToCharArray()
: target is IEnumerable<object> objects
? objects.Where(x => x != null).Select(x => x.ToString()[0]).ToArray()
: target.ConvertTo<char[]>();
public byte[] toUtf8Bytes(string target) => target.ToUtf8Bytes();
public string fromUtf8Bytes(byte[] target) => target.FromUtf8Bytes();
public byte toByte(object target) => target.ConvertTo<byte>();
public int toInt(object target) => target.ConvertTo<int>();
public long toLong(object target) => target.ConvertTo<long>();
public float toFloat(object target) => target.ConvertTo<float>();
public double toDouble(object target) => target.ConvertTo<double>();
public decimal toDecimal(object target) => target.ConvertTo<decimal>();
public bool toBool(object target) => target.ConvertTo<bool>();
public List<string> toKeys(object target)
{
if (target == null)
return null;
if (target is IDictionary<string, object> objDictionary)
return objDictionary.Keys.ToList();
if (target is IDictionary dictionary)
return dictionary.Keys.Map(x => x.ToString());
if (target is IEnumerable<KeyValuePair<string, object>> kvps)
{
var to = new List<string>();
foreach (var kvp in kvps)
{
to.Add(kvp.Key);
}
return to;
}
if (target is IEnumerable<KeyValuePair<string, string>> stringKvps)
{
var to = new List<string>();
foreach (var kvp in stringKvps)
{
to.Add(kvp.Key);
}
return to;
}
throw new NotSupportedException(nameof(toKeys) + " expects an IDictionary or List of KeyValuePairs but received: " + target.GetType().Name);
}
public List<object> toValues(object target)
{
if (target == null)
return null;
if (target is IDictionary<string, object> objDictionary)
return objDictionary.Values.ToList();
if (target is IDictionary dictionary)
return dictionary.Values.Map(x => x);
if (target is IEnumerable<KeyValuePair<string, object>> kvps)
{
var to = new List<object>();
foreach (var kvp in kvps)
{
to.Add(kvp.Value);
}
return to;
}
if (target is IEnumerable<KeyValuePair<string, string>> stringKvps)
{
var to = new List<object>();
foreach (var kvp in stringKvps)
{
to.Add(kvp.Value);
}
return to;
}
throw new NotSupportedException(nameof(toValues) + " expects an IDictionary or List of KeyValuePairs but received: " + target.GetType().Name);
}
public Dictionary<string, object> toObjectDictionary(object target) => target.ToObjectDictionary();
public Dictionary<string, string> toStringDictionary(IDictionary map)
{
if (isNull(map))
return null;
var to = new Dictionary<string, string>();
foreach (var key in map.Keys)
{
var value = map[key];
to[key.ToString()] = value?.ToString();
}
return to;
}
public int AssertWithinMaxQuota(int value)
{
var maxQuota = (int)Context.Args[TemplateConstants.MaxQuota];
if (value > maxQuota)
throw new NotSupportedException($"{value} exceeds Max Quota of {maxQuota}");
return value;
}
public Dictionary<object, object> toDictionary(TemplateScopeContext scope, object target, object expression) => toDictionary(scope, target, expression, null);
public Dictionary<object, object> toDictionary(TemplateScopeContext scope, object target, object expression, object scopeOptions)
{
var items = target.AssertEnumerable(nameof(toDictionary));
var literal = scope.AssertExpression(nameof(toDictionary), expression);
var scopedParams = scope.GetParamsWithItemBinding(nameof(toDictionary), scopeOptions, out string itemBinding);
literal.ToStringSegment().ParseNextToken(out object value, out JsBinding binding);
return items.ToDictionary(item => scope.AddItemToScope(itemBinding, item).Evaluate(value, binding));
}
public IRawString typeName(object target) => (target?.GetType().Name ?? "null").ToRawString();
public IEnumerable of(TemplateScopeContext scope, IEnumerable target, object scopeOptions)
{
var items = target.AssertEnumerable(nameof(of));
var scopedParams = scope.GetParamsWithItemBinding(nameof(of), scopeOptions, out string itemBinding);
if (scopedParams.TryGetValue("type", out object oType))
{
if (oType is string typeName)
return items.Where(x => x?.GetType()?.Name == typeName);
if (oType is Type type)
return items.Where(x => x?.GetType() == type);
}
return items;
}
public object @do(TemplateScopeContext scope, object expression)
{
var literal = scope.AssertExpression(nameof(@do), expression);
literal.ToStringSegment().ParseNextToken(out object value, out JsBinding binding);
var result = scope.Evaluate(value, binding);
return IgnoreResult.Value;
}
[HandleUnknownValue]
public Task @do(TemplateScopeContext scope, object target, object expression) => @do(scope, target, expression, null);
[HandleUnknownValue]
public Task @do(TemplateScopeContext scope, object target, object expression, object scopeOptions)
{
if (isNull(target) || target is bool b && !b)
return TypeConstants.EmptyTask;
var scopedParams = scope.GetParamsWithItemBinding(nameof(@do), scopeOptions, out string itemBinding);
var literal = scope.AssertExpression(nameof(@do), expression);
literal.ToStringSegment().ParseNextToken(out object value, out JsBinding binding);
if (target is IEnumerable objs && !(target is IDictionary) && !(target is string))
{
var items = target.AssertEnumerable(nameof(@do));
var i = 0;
foreach (var item in items)
{
scope.AddItemToScope(itemBinding, item, i++);
var result = scope.Evaluate(value, binding);
}
}
else
{
scope.AddItemToScope(itemBinding, target);
var result = scope.Evaluate(value, binding);
}
return TypeConstants.EmptyTask;
}
public object property(object target, string propertyName)
{
if (isNull(target))
return null;
var props = TypeProperties.Get(target.GetType());
var fn = props.GetPublicGetter(propertyName);
if (fn == null)
throw new NotSupportedException($"There is no public Property '{propertyName}' on Type '{target.GetType().Name}'");
var value = fn(target);
return value;
}
public object field(object target, string fieldName)
{
if (isNull(target))
return null;
var props = TypeFields.Get(target.GetType());
var fn = props.GetPublicGetter(fieldName);
if (fn == null)
throw new NotSupportedException($"There is no public Field '{fieldName}' on Type '{target.GetType().Name}'");
var value = fn(target);
return value;
}
public object map(TemplateScopeContext scope, object items, object expression) => map(scope, items, expression, null);
public object map(TemplateScopeContext scope, object target, object expression, object scopeOptions)
{
var literal = scope.AssertExpression(nameof(map), expression);
var scopedParams = scope.GetParamsWithItemBinding(nameof(map), scopeOptions, out string itemBinding);
literal.ToStringSegment().ParseNextToken(out object value, out JsBinding binding);
if (target is IEnumerable items && !(target is IDictionary) && !(target is string))
{
var i = 0;
return items.Map(item => scope.AddItemToScope(itemBinding, item, i++).Evaluate(value, binding));
}
var result = scope.AddItemToScope(itemBinding, target).Evaluate(value, binding);
return result;
}
public object scopeVars(object target)
{
if (isNull(target))
return null;
if (target is IDictionary<string, object> g)
return new ScopeVars(g);
if (target is IDictionary d)
{
var to = new ScopeVars();
foreach (var key in d.Keys)
{
to[key.ToString()] = d[key];
}
return to;
}
if (target is IEnumerable<KeyValuePair<string, object>> kvps)
{
var to = new ScopeVars();
foreach (var item in kvps)
{
to[item.Key] = item.Value;
}
return to;
}
if (target is IEnumerable e)
{
var to = new List<object>();
foreach (var item in e)
{
var toItem = item is IDictionary
? scopeVars(item)
: item;
to.Add(toItem);
}
return to;
}
throw new NotSupportedException($"'{nameof(scopeVars)}' expects a Dictionary but received a '{target.GetType().Name}'");
}
public object selectFields(object target, object names)
{
if (target == null || names == null)
return null;
if (target is string || target.GetType().IsValueType)
throw new NotSupportedException(nameof(selectFields) + " requires an IEnumerable, IDictionary or POCO Target, received instead: " + target.GetType().Name);
var namesList = names is IEnumerable eKeys
? eKeys.Map(x => x)
: null;
var stringKey = names as string;
var stringKeys = namesList?.OfType<string>().ToList();
if (stringKeys.IsEmpty())
stringKeys = null;
if (stringKey == null && stringKeys == null)
throw new NotSupportedException(nameof(selectFields) + " requires a string or [string] or property names, received instead: " + names.GetType().Name);
if (stringKey?.IndexOf(',') >= 0)
{
stringKeys = stringKey.Split(',').Map(x => x.Trim());
stringKey = null;
}
var stringsSet = stringKeys != null
? new HashSet<string>(stringKeys, StringComparer.OrdinalIgnoreCase)
: new HashSet<string> { stringKey };
var singleItem = target is IDictionary || !(target is IEnumerable);
if (singleItem)
{
var objDictionary = target.ToObjectDictionary();
var to = new Dictionary<string, object>();
foreach (var key in objDictionary.Keys)
{
if (stringsSet.Contains(key))
to[key] = objDictionary[key];
}
return to;
}
else
{
var to = new List<Dictionary<string,object>>();
var e = (IEnumerable) target;
foreach (var item in e)
{
var objDictionary = item.ToObjectDictionary();
var row = new Dictionary<string, object>();
foreach (var key in objDictionary.Keys)
{
if (stringsSet.Contains(key))
row[key] = objDictionary[key];
}
to.Add(row);
}
return to;
}
}
[HandleUnknownValue]
public Task select(TemplateScopeContext scope, object target, object selectTemplate) => select(scope, target, selectTemplate, null);
[HandleUnknownValue]
public async Task select(TemplateScopeContext scope, object target, object selectTemplate, object scopeOptions)
{
if (isNull(target))
return;
var scopedParams = scope.GetParamsWithItemBinding(nameof(select), scopeOptions, out string itemBinding);
var template = JsonTypeSerializer.Unescape(selectTemplate.ToString(), removeQuotes:false);
var itemScope = scope.CreateScopedContext(template, scopedParams);
if (target is IEnumerable objs && !(target is IDictionary) && !(target is string))
{
var i = 0;
foreach (var item in objs)
{
itemScope.AddItemToScope(itemBinding, item, i++);
await itemScope.WritePageAsync();
}
}
else
{
itemScope.AddItemToScope(itemBinding, target);
await itemScope.WritePageAsync();
}
}
[HandleUnknownValue]
public Task selectPartial(TemplateScopeContext scope, object target, string pageName) => selectPartial(scope, target, pageName, null);
[HandleUnknownValue]
public async Task selectPartial(TemplateScopeContext scope, object target, string pageName, object scopedParams)
{
if (isNull(target))
return;
scope.TryGetPage(pageName, out TemplatePage page, out TemplateCodePage codePage);
if (page != null)
await page.Init();
var pageParams = scope.GetParamsWithItemBinding(nameof(selectPartial), page, scopedParams, out string itemBinding);
if (target is IEnumerable objs && !(target is IDictionary) && !(target is string))
{
var i = 0;
foreach (var item in objs)
{
scope.AddItemToScope(itemBinding, item, i++);
await scope.WritePageAsync(page, codePage, pageParams);
}
}
else
{
scope.AddItemToScope(itemBinding, target);
await scope.WritePageAsync(page, codePage, pageParams);
}
}
public object removeKeyFromDictionary(IDictionary dictionary, object keyToRemove)
{
var removeKeys = keyToRemove is IEnumerable e
? e.Map(x => x)
: null;
foreach (var key in dictionary.Keys)
{
if (removeKeys != null)
{
foreach (var removeKey in removeKeys)
{
if (Equals(key, removeKey))
dictionary.Remove(key);
}
}
else if (Equals(key, keyToRemove))
{
dictionary.Remove(key);
}
}
return dictionary;
}
public object remove(object target, object keysToRemove)
{
var removeKeys = keysToRemove is IEnumerable eKeys
? eKeys.Map(x => x)
: null;
var stringKey = keysToRemove as string;
var stringKeys = removeKeys?.OfType<string>().ToArray();
if (stringKeys.IsEmpty())
stringKeys = null;
if (target is IDictionary d)
return removeKeyFromDictionary(d, removeKeys);
if (target is IEnumerable e)
{
object first = null;
foreach (var item in e)
{
if (item == null)
continue;
first = item;
break;
}
if (first == null)
return target;
var itemType = first.GetType();
var props = TypeProperties.Get(itemType);
if (!(first is IDictionary))
throw new NotSupportedException(nameof(remove) + " removes keys from a IDictionary or [IDictionary]");
foreach (var item in e)
{
if (item == null)
continue;
if (item is IDictionary ed)
{
removeKeyFromDictionary(ed, removeKeys);