forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProtectedScripts.cs
More file actions
1750 lines (1499 loc) · 73.4 KB
/
Copy pathProtectedScripts.cs
File metadata and controls
1750 lines (1499 loc) · 73.4 KB
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.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using ServiceStack.DataAnnotations;
using ServiceStack.IO;
using ServiceStack.Script;
using ServiceStack.Text;
namespace ServiceStack.Script
{
// ReSharper disable InconsistentNaming
public class ProtectedScripts : ScriptMethods
{
public static readonly ProtectedScripts Instance = new ProtectedScripts();
public object resolve(ScriptScopeContext scope, object type)
{
if (type == null)
return null;
var t = type as Type ?? (type is string s
? @typeof(s)
: throw new NotSupportedException($"{nameof(resolve)} requires a Type or Type Name, received '{type.GetType().Name}'"));
var instance = scope.Context.Container.Resolve(t);
return instance;
}
public object @default(string typeName)
{
var type = assertTypeOf(typeName);
return type.GetDefaultValue();
}
public object @new(string typeName)
{
var type = @typeof(typeName);
return type != null
? createInstance(type)
: null;
}
public object @new(string typeName, List<object> constructorArgs)
{
var type = @typeof(typeName);
return type != null
? createInstance(type, constructorArgs)
: null;
}
public object set(object instance, Dictionary<string, object> args)
{
args.PopulateInstance(instance);
return instance;
}
private Type[] typeGenericTypes(string typeName)
{
return typeGenericTypes(typeGenericArgs(typeName));
}
private Type[] typeGenericTypes(List<string> genericArgs)
{
var genericTypes = new List<Type>();
foreach (var genericArg in genericArgs)
{
var genericType = @typeof(genericArg);
genericTypes.Add(genericType);
}
return genericTypes.ToArray();
}
private static List<string> typeGenericArgs(string typeName)
{
var argList = typeName.RightPart('<');
argList = argList.Substring(0, argList.Length - 1);
var splitArgs = StringUtils.SplitGenericArgs(argList);
return splitArgs;
}
public object createInstance(Type type) => AssertCanCreateType(type).CreateInstance();
public object createInstance(Type type, List<object> constructorArgs)
{
var key = callKey(AssertCanCreateType(type), "<new>", constructorArgs);
var activator = (ObjectActivator) Context.Cache.GetOrAdd(key, k => {
var args = constructorArgs;
var argTypes = args?.Select(x => x?.GetType()).ToArray() ?? TypeConstants.EmptyTypeArray;
var ctorInfo = ResolveConstructor(type, argTypes);
return ctorInfo.GetActivator();
});
return activator(constructorArgs?.ToArray() ?? TypeConstants.EmptyObjectArray);
}
private Type AssertCanCreateType(Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (!type.IsPublic && !Context.AllowScriptingOfAllTypes)
throw new NotSupportedException(
"Can only create instances of non public Types when AllowScriptingOfAllTypes=true");
return type;
}
private ConstructorInfo ResolveConstructor(Type type, Type[] argTypes)
{
var argsCount = argTypes.Length;
var ctors = type.GetConstructors()
.Where(x => x.GetParameters().Length == argsCount).ToArray();
if (ctors.Length == 0)
{
var argTypesList = string.Join(",", argTypes.Select(x => x?.Name ?? "null"));
throw new NotSupportedException(
$"Constructor {typeQualifiedName(type)}({argTypesList}) does not exist");
}
ConstructorInfo targetCtor = null;
if (ctors.Length > 1)
{
var candidates = 0;
foreach (var ctor in ctors)
{
var match = true;
var ctorParams = ctor.GetParameters();
for (var i = 0; i < argTypes.Length; i++)
{
var argType = argTypes[i];
if (argType == null)
continue;
match = ctorParams[i].ParameterType == argType;
if (!match)
break;
}
if (match)
{
targetCtor = ctor;
candidates++;
}
}
if (targetCtor == null || candidates != 1)
{
var argTypesList = string.Join(",", argTypes.Select(x => x?.Name ?? "null"));
throw new NotSupportedException(
$"Could not resolve ambiguous constructor {typeQualifiedName(type)}({argTypesList})");
}
}
else targetCtor = ctors[0];
return targetCtor;
}
public Type getType(object instance) => instance?.GetType();
public string typeQualifiedName(Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
var sb = StringBuilderCache.Allocate();
sb.Append(type.Namespace).Append('.');
if (type.GenericTypeArguments.Length > 0)
{
sb.Append(type.Name.LeftPart('`'))
.Append('<');
var i = 0;
foreach (var arg in type.GenericTypeArguments)
{
if (i++ > 0)
sb.Append(',');
sb.Append(typeQualifiedName(arg));
}
sb.Append('>');
}
else
{
sb.Append(type.Name);
}
return StringBuilderCache.ReturnAndFree(sb);
}
public static string TypeNotFoundErrorMessage(string typeName) => $"Could not resolve Type '{typeName}'. " +
$"Use ScriptContext.ScriptAssemblies or ScriptContext.AllowScriptingOfAllTypes + ScriptNamespaces to increase Type resolution";
public Type assertTypeOf(string name)
{
var type = @typeof(name);
if (type == null)
throw new NotSupportedException(TypeNotFoundErrorMessage(name));
return type;
}
/// <summary>
/// Returns Type from type name syntax of .NET's typeof()
/// </summary>
public Type @typeof(string typeName)
{
typeName = typeName?.Trim();
if (string.IsNullOrEmpty(typeName))
return null;
var key = "type:" + typeName;
Type cookType(Type type, List<string> genericArgs, bool isArray, bool isNullable)
{
if (type.IsGenericType)
{
var isGenericDefinition = genericArgs != null && genericArgs.All(x => x == "");
if (!isGenericDefinition)
{
var genericTypes = typeGenericTypes(genericArgs);
type = type.MakeGenericType(genericTypes);
}
}
if (isArray)
{
type = type.MakeArrayType();
}
return isNullable
? typeof(Nullable<>).MakeGenericType(type)
: type;
}
Type onlyTypeOf(string _typeName)
{
var isArray = _typeName.EndsWith("[]");
if (isArray)
{
_typeName = _typeName.Substring(0, _typeName.Length - 2);
}
var isGeneric = _typeName.IndexOf('<') >= 0;
List<string> genericArgs = null;
if (isGeneric)
{
genericArgs = typeGenericArgs(_typeName);
_typeName = _typeName.LeftPart('<') + '`' + Math.Max(genericArgs.Count, 1);
}
var isNullable = _typeName.EndsWith("?");
if (isNullable)
_typeName = _typeName.Substring(0, _typeName.Length - 1);
if (_typeName.IndexOf('.') >= 0)
{
if (Context.ScriptTypeQualifiedNameMap.TryGetValue(_typeName, out var type))
return cookType(type, genericArgs, isArray, isNullable);
if (Context.AllowScriptingOfAllTypes)
{
type = AssemblyUtils.FindType(_typeName);
if (type != null)
return cookType(type, genericArgs, isArray, isNullable);
}
}
else
{
var ret = _typeName switch {
"int" => !isArray ? typeof(int) : typeof(int[]),
"long" => !isArray ? typeof(long) : typeof(long[]),
"bool" => !isArray ? typeof(bool) : typeof(bool[]),
"char" => !isArray ? typeof(char) : typeof(char[]),
"double" => !isArray ? typeof(double) : typeof(double[]),
"float" => !isArray ? typeof(float) : typeof(float[]),
"decimal" => !isArray ? typeof(decimal) : typeof(decimal[]),
"byte" => !isArray ? typeof(byte) : typeof(byte[]),
"sbyte" => !isArray ? typeof(sbyte) : typeof(sbyte[]),
"uint" => !isArray ? typeof(uint) : typeof(uint[]),
"ulong" => !isArray ? typeof(ulong) : typeof(ulong[]),
"object" => !isArray ? typeof(object) : typeof(object[]),
"short" => !isArray ? typeof(short) : typeof(short[]),
"ushort" => !isArray ? typeof(ushort) : typeof(ushort[]),
"string" => !isArray ? typeof(string) : typeof(string[]),
"Guid" => !isArray ? typeof(Guid) : typeof(Guid[]),
"TimeSpan" => !isArray ? typeof(TimeSpan) : typeof(TimeSpan[]),
"DateTime" => !isArray ? typeof(DateTime) : typeof(DateTime[]),
"DateTimeOffset" => !isArray ? typeof(DateTimeOffset) : typeof(DateTimeOffset[]),
_ => null,
};
if (ret != null)
{
return isNullable
? typeof(Nullable<>).MakeGenericType(ret)
: ret;
}
if (Context.ScriptTypeNameMap.TryGetValue(_typeName, out var type))
return cookType(type, genericArgs, isArray, isNullable);
}
foreach (var ns in Context.ScriptNamespaces)
{
var lookupType = ns + "." + _typeName;
if (Context.ScriptTypeQualifiedNameMap.TryGetValue(lookupType, out var type))
return cookType(type, genericArgs, isArray, isNullable);
if (Context.AllowScriptingOfAllTypes)
{
type = AssemblyUtils.FindType(lookupType);
if (type != null)
return cookType(type, genericArgs, isArray, isNullable);
}
}
return null;
}
var resolvedType = (Type) Context.Cache.GetOrAdd(key, k => {
var type = onlyTypeOf(typeName);
if (type != null)
return type;
var parts = typeName.Split('.');
if (parts.Length > 1)
{
var nameBuilder = "";
for (var i = 0; i < parts.Length; i++)
{
try
{
if (i > 0)
nameBuilder += '.';
nameBuilder += parts[i];
var parentType = onlyTypeOf(nameBuilder);
if (parentType != null)
{
var nestedTypeName = parts[++i];
var nestedType = parentType.GetNestedType(nestedTypeName);
i++;
while (i < parts.Length)
{
nestedTypeName = parts[i++];
nestedType = nestedType.GetNestedType(nestedTypeName);
}
return nestedType;
}
}
catch { }
}
}
return null;
});
return resolvedType;
}
public Type typeofProgId(string name) => Env.IsWindows
? Type.GetTypeFromProgID(name) // .NET Core throws TargetInvocationException CoreCLR_REMOVED -- Unmanaged activation removed
: null;
public object call(object instance, string name) => call(instance, name, null);
internal string callKey(Type type, string name, List<object> args)
{
var sb = StringBuilderCache.Allocate()
.Append("call:")
.Append(type.Namespace)
.Append('.')
.Append(type.Name)
.Append('.')
.Append(name);
if (type.GenericTypeArguments.Length > 0)
{
sb.Append('<');
for (var i = 0; i < type.GenericTypeArguments.Length; i++)
{
if (i > 0)
sb.Append(',');
var genericArg = type.GenericTypeArguments[i];
sb.Append(typeQualifiedName(genericArg));
}
sb.Append('>');
}
appendArgTypes(sb, args);
return StringBuilderCache.ReturnAndFree(sb);
}
static string argTypesString(List<object> args)
{
var sb = StringBuilderCache.Allocate();
appendArgTypes(sb, args);
return StringBuilderCache.ReturnAndFree(sb);
}
private static void appendArgTypes(StringBuilder sb, List<object> args)
{
sb.Append('(');
if (args != null)
{
for (var i = 0; i < args.Count; i++)
{
if (i > 0)
sb.Append(',');
var argType = args[i]?.GetType();
sb.Append(argType == null ? "null" : argType.Namespace + '.' + argType.Name);
}
}
sb.Append(')');
}
public object call(object instance, string name, List<object> args)
{
if (instance == null)
throw new ArgumentNullException(nameof(instance));
if (name == null)
throw new ArgumentNullException(nameof(name));
var type = instance.GetType();
var key = callKey(type, name, args);
var invoker = (Delegate)Context.Cache.GetOrAdd(key, k => {
var argTypes = args?.Select(x => x?.GetType()).ToArray();
var targetMethod = ResolveMethod(type, name, argTypes, argTypes?.Length ?? 0, out var fn);
if (targetMethod != null && targetMethod.IsStatic)
throw new NotSupportedException($"Cannot call static method {instance.GetType().Name}.{targetMethod.Name}");
return fn ?? targetMethod.GetInvokerDelegate();
});
if (invoker is MethodInvoker methodInvoker)
{
var ret = methodInvoker(instance, args?.ToArray() ?? TypeConstants.EmptyObjectArray);
return ret;
}
if (invoker is ActionInvoker actionInvoker)
{
actionInvoker(instance, args?.ToArray() ?? TypeConstants.EmptyObjectArray);
return IgnoreResult.Value;
}
throw new NotSupportedException($"Cannot call {invoker.GetType().Name} methods");
}
private MethodInfo ResolveMethod(Type type, string methodName, Type[] argTypes, int? argsCount, out Delegate invokerDelegate)
{
invokerDelegate = null;
var isGeneric = methodName.IndexOf('<') >= 0;
var name = isGeneric ? methodName.LeftPart('<') : methodName;
var genericArgs = isGeneric
? typeGenericArgs(methodName)
: TypeConstants.EmptyStringList;
var genericArgsCount = genericArgs.Count;
var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
.Where(x => x.Name == name && (argsCount == null || x.GetParameters().Length == argsCount.Value)
&& ((genericArgs.Count == 0 && !x.IsGenericMethod) || (x.IsGenericMethod && x.GetGenericArguments().Length == genericArgsCount)))
.ToArray();
MethodInfo targetMethod = null;
if (methods.Length == 0)
{
if ((argTypes?.Length ?? 0) == 0)
{
var prop = type.GetProperty(name,BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
if (prop != null)
{
targetMethod = prop.GetMethod;
if (targetMethod == null)
{
throw new NotSupportedException(
$"Property {typeQualifiedName(type)}.{name} does not have a getter");
}
}
else
{
var field = type.GetField(name,BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
if (field != null)
{
if (field.IsStatic)
{
invokerDelegate = (StaticMethodInvoker) ((args) => field.GetValue(null));
return null;
}
else
{
invokerDelegate = (MethodInvoker) ((instance, args) => field.GetValue(instance));
return null;
}
}
}
}
if (targetMethod == null)
{
throw new NotSupportedException(
$"Method {typeQualifiedName(type)}.{name} does not exist");
}
}
if (targetMethod == null)
{
if (methods.Length > 1)
{
var candidates = 0;
foreach (var method in methods)
{
var match = true;
var methodParams = method.GetParameters();
if (argTypes != null)
{
for (var i = 0; i < argTypes.Length; i++)
{
var argType = argTypes[i];
if (argType == null)
continue;
match = methodParams[i].ParameterType == argType;
if (!match)
break;
}
}
if (match)
{
targetMethod = method;
candidates++;
}
}
if (targetMethod == null || candidates != 1)
{
var argTypesList = argTypes != null ? string.Join(",", argTypes.Select(x => x?.Name ?? "null")) : "";
throw new NotSupportedException(
$"Could not resolve ambiguous method {typeQualifiedName(type)}.{name}({argTypesList})");
}
}
else targetMethod = methods[0];
}
if (targetMethod.IsGenericMethod)
{
var genericTypes = typeGenericTypes(methodName);
targetMethod = targetMethod.MakeGenericMethod(genericTypes);
}
if (targetMethod == null)
throw new NotSupportedException(MethodNotExists($"{type.Name}.{name}"));
return targetMethod;
}
/// <summary>
/// Qualified Constructor Name Examples:
/// - Type()
/// - Type(string)
/// - GenericType<string<(System.Int32)
/// - Namespace.Type()
/// </summary>
public ObjectActivator Constructor(string qualifiedConstructorName)
{
if (qualifiedConstructorName.IndexOf('(') == -1)
throw new NotSupportedException($"Invalid Constructor Name '{qualifiedConstructorName}', " +
$"format: <type>(<arg-types>), e.g. Uri(String), see: https://sharpscript.net/docs/script-net");
var name = qualifiedConstructorName;
var activator = (ObjectActivator) Context.Cache.GetOrAdd(nameof(Constructor) + ":" + name, k => {
var argList = name.LastRightPart('(');
argList = argList?.Substring(0, argList.Length - 1);
var argTypes = typeGenericTypes(StringUtils.SplitGenericArgs(argList));
name = name.LastLeftPart('(');
var type = assertTypeOf(name);
var ctor = ResolveConstructor(type, argTypes);
return ctor.GetActivator();
});
return activator;
}
/// <summary>
/// Shorter Alias for Constructor
/// </summary>
/// <returns></returns>
public Delegate C(string qualifiedMethodName) => Constructor(qualifiedMethodName);
/// <summary>
/// Shorter Alias for Function
/// </summary>
/// <returns></returns>
public Delegate F(string qualifiedMethodName) => Function(qualifiedMethodName);
/// <summary>
/// Shorter Alias for Function(name,args)
/// </summary>
/// <returns></returns>
public Delegate F(string qualifiedMethodName, List<object> args) => Function(qualifiedMethodName, args);
/// <summary>
/// Qualified Method Name Examples:
/// - Console.WriteLine(string)
/// - Type.StaticMethod
/// - Type.InstanceMethod
/// - GenericType<string<.Method
/// - GenericType<string<.GenericMethod<System.Int32<
/// - Namespace.Type.Method
/// </summary>
public Delegate Function(string qualifiedMethodName)
{
if (qualifiedMethodName.IndexOf('.') == -1)
throw new NotSupportedException($"Invalid Function Name '{qualifiedMethodName}', " +
$"format: <type>.<method>(<arg-types>), e.g. Console.WriteLine(string), see: https://sharpscript.net/docs/script-net");
var invoker = (Delegate) Context.Cache.GetOrAdd(nameof(Function) + ":" + qualifiedMethodName, k =>
ResolveFunction(qualifiedMethodName));
return invoker;
}
/// <summary>
/// Resolve Function from qualified type name, when args Type list are unspecified fallback to use args to resolve ambiguous methods
///
/// Qualified Method Name Examples:
/// - Console.WriteLine ['string']
/// - Type.StaticMethod
/// - Type.InstanceMethod
/// - GenericType<string<.Method
/// - GenericType<string<.GenericMethod<System.Int32<
/// - Namespace.Type.Method
/// </summary>
public Delegate Function(string qualifiedMethodName, List<object> args)
{
if (qualifiedMethodName.IndexOf('.') == -1)
throw new NotSupportedException($"Invalid Function Name '{qualifiedMethodName}', " +
$"format: <type>.<method>(<arg-types>), e.g. Console.WriteLine(string), see: https://sharpscript.net/docs/script-net");
var key = nameof(Function) + ":" + qualifiedMethodName + argTypesString(args);
var invoker = (Delegate)Context.Cache.GetOrAdd(key, k =>
ResolveFunction(qualifiedMethodName, args?.Select(x => x?.GetType()).ToArray()));
return invoker;
}
private Delegate ResolveFunction(string name, Type[] argTypes=null)
{
var hasArgsList = name.IndexOf('(') >= 0;
var argList = hasArgsList
? name.LastRightPart('(')
: null;
argList = argList?.Substring(0, argList.Length - 1);
name = name.LastLeftPart('(');
var lastGenericPos = name.LastIndexOf('>');
var lastSepPos = name.LastIndexOf('.');
int pos = -1;
if (lastSepPos > lastGenericPos)
{
pos = lastSepPos;
}
else
{
var genericPos = name.IndexOf('<');
pos = genericPos >= 0
? name.LastIndexOf('.', genericPos)
: name.LastIndexOf('.');
if (pos == -1)
pos = name.IndexOf(">.", StringComparison.Ordinal) + 1;
}
if (pos == -1)
throw new NotSupportedException($"Could not parse Function Name '{name}', " +
$"format: <type>.<method>(<arg-types>), e.g. Console.WriteLine(string)");
var typeName = name.Substring(0, pos);
var methodName = name.Substring(pos + 1);
if (hasArgsList)
{
var splitArgs = StringUtils.SplitGenericArgs(argList);
argTypes = typeGenericTypes(splitArgs);
for (var i = 0; i < argTypes.Length; i++)
{
if (argTypes[i] == null)
throw new NotSupportedException($"Could not resolve Argument Type '{splitArgs[i]}' for '{name}'");
}
}
var type = assertTypeOf(typeName);
var method = ResolveMethod(type, methodName, argTypes, argTypes?.Length, out var fn);
return fn ?? method.GetInvokerDelegate();
}
static string MethodNotExists(string methodName) => $"Method {methodName} does not exist";
public MemoryVirtualFiles vfsMemory() => new();
public FileSystemVirtualFiles vfsFileSystem(string dirPath) => new(dirPath);
public GistVirtualFiles vfsGist(string gistId) => new(gistId);
public GistVirtualFiles vfsGist(string gistId, string accessToken) => new(gistId, accessToken);
public string osPaths(string path) => Env.IsWindows
? path.Replace('/', '\\')
: path.Replace('\\', '/');
public IVirtualFile resolveFile(ScriptScopeContext scope, string virtualPath) =>
ResolveFile(scope.Context.VirtualFiles, scope.PageResult.VirtualPath, virtualPath);
public IVirtualFile ResolveFile(string filterName, ScriptScopeContext scope, string virtualPath)
{
var file = ResolveFile(scope.Context.VirtualFiles, scope.PageResult.VirtualPath, virtualPath);
if (file == null)
throw new FileNotFoundException($"{filterName} '{virtualPath}' in page '{scope.Page.VirtualPath}' was not found");
return file;
}
public IVirtualFile ResolveFile(IVirtualPathProvider virtualFiles, string fromVirtualPath, string virtualPath)
{
IVirtualFile file = null;
var pathMapKey = nameof(ResolveFile) + ">" + fromVirtualPath;
var pathMapping = Context.GetPathMapping(pathMapKey, virtualPath);
if (pathMapping != null)
{
file = virtualFiles.GetFile(pathMapping);
if (file != null)
return file;
Context.RemovePathMapping(pathMapKey, pathMapping);
}
var tryExactMatch = virtualPath.IndexOf('/') >= 0; //if nested path specified, look for an exact match first
if (tryExactMatch)
{
file = virtualFiles.GetFile(virtualPath);
if (file != null)
{
Context.SetPathMapping(pathMapKey, virtualPath, virtualPath);
return file;
}
}
var parentPath = fromVirtualPath.IndexOf('/') >= 0
? fromVirtualPath.LastLeftPart('/')
: "";
do
{
var seekPath = parentPath.CombineWith(virtualPath);
file = virtualFiles.GetFile(seekPath);
if (file != null)
{
Context.SetPathMapping(pathMapKey, virtualPath, seekPath);
return file;
}
if (parentPath == "")
break;
parentPath = parentPath.IndexOf('/') >= 0
? parentPath.LastLeftPart('/')
: "";
} while (true);
return null;
}
public async Task includeFile(ScriptScopeContext scope, string virtualPath)
{
var file = ResolveFile(nameof(includeFile), scope, virtualPath);
using var reader = file.OpenRead();
await reader.CopyToAsync(scope.OutputStream).ConfigAwait();
}
public async Task ifDebugIncludeScript(ScriptScopeContext scope, string virtualPath)
{
if (scope.Context.DebugMode)
{
await scope.OutputStream.WriteAsync("<script>").ConfigAwait();
await includeFile(scope, virtualPath).ConfigAwait();
await scope.OutputStream.WriteAsync("</script>").ConfigAwait();
}
}
IVirtualPathProvider VirtualFiles => Context.VirtualFiles;
// Old Aliases for Backwards compatibility
[Alias("allFiles")]
public IEnumerable<IVirtualFile> vfsAllFiles() => allFiles(VirtualFiles);
[Alias("allRootFiles")]
public IEnumerable<IVirtualFile> vfsAllRootFiles() => allRootFiles(VirtualFiles);
[Alias("allRootDirectories")]
public IEnumerable<IVirtualDirectory> vfsAllRootDirectories() => allRootDirectories(VirtualFiles);
[Alias("combinePath")]
public string vfsCombinePath(string basePath, string relativePath) => combinePath(VirtualFiles, basePath, relativePath);
[Alias("findFilesInDirectory")]
public IEnumerable<IVirtualFile> dirFilesFind(string dirPath, string globPattern) => findFilesInDirectory(VirtualFiles,dirPath,globPattern);
[Alias("findFiles")]
public IEnumerable<IVirtualFile> filesFind(string globPattern) => findFiles(VirtualFiles,globPattern);
[Alias("writeFile")]
public string fileWrite(string virtualPath, object contents) => writeFile(VirtualFiles, virtualPath, contents);
[Alias("appendToFile")]
public string fileAppend(string virtualPath, object contents) => appendToFile(VirtualFiles, virtualPath, contents);
[Alias("deleteFile")]
public string fileDelete(string virtualPath) => deleteFile(VirtualFiles, virtualPath);
[Alias("deleteFile")]
public string dirDelete(string virtualPath) => deleteFile(VirtualFiles, virtualPath);
[Alias("fileTextContents")]
public string fileReadAll(string virtualPath) => fileTextContents(VirtualFiles,virtualPath);
[Alias("fileBytesContent")]
public byte[] fileReadAllBytes(string virtualPath) => fileBytesContent(VirtualFiles, virtualPath);
public IEnumerable<IVirtualFile> allFiles() => allFiles(VirtualFiles);
public IEnumerable<IVirtualFile> allFiles(IVirtualPathProvider vfs) => vfs.GetAllFiles();
public IEnumerable<IVirtualFile> allRootFiles() => allRootFiles(VirtualFiles);
public IEnumerable<IVirtualFile> allRootFiles(IVirtualPathProvider vfs) => vfs.GetRootFiles();
public IEnumerable<IVirtualDirectory> allRootDirectories() => allRootDirectories(VirtualFiles);
public IEnumerable<IVirtualDirectory> allRootDirectories(IVirtualPathProvider vfs) => vfs.GetRootDirectories();
public string combinePath(string basePath, string relativePath) => combinePath(VirtualFiles, basePath, relativePath);
public string combinePath(IVirtualPathProvider vfs, string basePath, string relativePath) => vfs.CombineVirtualPath(basePath, relativePath);
public IVirtualDirectory dir(string virtualPath) => dir(VirtualFiles,virtualPath);
public IVirtualDirectory dir(IVirtualPathProvider vfs, string virtualPath) => vfs.GetDirectory(virtualPath);
public bool dirExists(string virtualPath) => VirtualFiles.DirectoryExists(virtualPath);
public bool dirExists(IVirtualPathProvider vfs, string virtualPath) => vfs.DirectoryExists(virtualPath);
public IVirtualFile dirFile(string dirPath, string fileName) => dirFile(VirtualFiles,dirPath,fileName);
public IVirtualFile dirFile(IVirtualPathProvider vfs, string dirPath, string fileName) => vfs.GetDirectory(dirPath)?.GetFile(fileName);
public IEnumerable<IVirtualFile> dirFiles(string dirPath) => dirFiles(VirtualFiles,dirPath);
public IEnumerable<IVirtualFile> dirFiles(IVirtualPathProvider vfs, string dirPath) => vfs.GetDirectory(dirPath)?.GetFiles() ?? new List<IVirtualFile>();
public IVirtualDirectory dirDirectory(string dirPath, string dirName) => dirDirectory(VirtualFiles,dirPath,dirName);
public IVirtualDirectory dirDirectory(IVirtualPathProvider vfs, string dirPath, string dirName) => vfs.GetDirectory(dirPath)?.GetDirectory(dirName);
public IEnumerable<IVirtualDirectory> dirDirectories(string dirPath) => dirDirectories(VirtualFiles,dirPath);
public IEnumerable<IVirtualDirectory> dirDirectories(IVirtualPathProvider vfs, string dirPath) => vfs.GetDirectory(dirPath)?.GetDirectories() ?? new List<IVirtualDirectory>();
public IEnumerable<IVirtualFile> findFilesInDirectory(string dirPath, string globPattern) => findFilesInDirectory(VirtualFiles,dirPath,globPattern);
public IEnumerable<IVirtualFile> findFilesInDirectory(IVirtualPathProvider vfs, string dirPath, string globPattern) => vfs.GetDirectory(dirPath)?.GetAllMatchingFiles(globPattern);
public IEnumerable<IVirtualFile> findFiles(string globPattern) => findFiles(VirtualFiles,globPattern);
public IEnumerable<IVirtualFile> dirFindFiles(IVirtualDirectory dir, string globPattern) => dir.GetAllMatchingFiles(globPattern);
public IEnumerable<IVirtualFile> dirFindFiles(IVirtualDirectory dir, string globPattern, int maxDepth) => dir.GetAllMatchingFiles(globPattern, maxDepth);
public IEnumerable<IVirtualFile> findFiles(IVirtualPathProvider vfs, string globPattern) => vfs.GetAllMatchingFiles(globPattern);
public IEnumerable<IVirtualFile> findFiles(IVirtualPathProvider vfs, string globPattern, int maxDepth) => vfs.GetAllMatchingFiles(globPattern, maxDepth);
public bool fileExists(string virtualPath) => fileExists(VirtualFiles,virtualPath);
public bool fileExists(IVirtualPathProvider vfs, string virtualPath) => vfs.FileExists(virtualPath);
public IVirtualFile file(string virtualPath) => file(VirtualFiles,virtualPath);
public IVirtualFile file(IVirtualPathProvider vfs, string virtualPath) => vfs.GetFile(virtualPath);
public string writeFile(string virtualPath, object contents) => writeFile(VirtualFiles, virtualPath, contents);
public string writeFile(IVirtualPathProvider vfs, string virtualPath, object contents)
{
vfs.WriteFile(virtualPath, contents);
return virtualPath;
}
public object writeFiles(IVirtualPathProvider vfs, Dictionary<string,object> files)
{
vfs.WriteFiles(files);
return IgnoreResult.Value;
}
public object writeTextFiles(IVirtualPathProvider vfs, Dictionary<string,string> textFiles)
{
vfs.WriteFiles(textFiles);
return IgnoreResult.Value;
}
public string appendToFile(string virtualPath, object contents) => appendToFile(VirtualFiles, virtualPath, contents);
public string appendToFile(IVirtualPathProvider vfs, string virtualPath, object contents)
{
vfs.AppendFile(virtualPath, contents);
return virtualPath;
}
public string deleteFile(string virtualPath) => deleteFile(VirtualFiles, virtualPath);
public string deleteFile(IVirtualPathProvider vfs, string virtualPath)
{
vfs.DeleteFile(virtualPath);
return virtualPath;
}
public string deleteDirectory(string virtualPath) => deleteFile(VirtualFiles, virtualPath);
public string deleteDirectory(IVirtualPathProvider vfs, string virtualPath)
{
vfs.DeleteFolder(virtualPath);
return virtualPath;
}
public string fileTextContents(string virtualPath) => fileTextContents(VirtualFiles,virtualPath);
public string fileTextContents(IVirtualPathProvider vfs, string virtualPath) => vfs.GetFile(virtualPath)?.ReadAllText();
public object fileContents(IVirtualPathProvider vfs, string virtualPath) =>
vfs.GetFile(virtualPath).GetContents();
// string virtual filePath or IVirtualFile
public object fileContents(object file) => file is null
? null
: file is string path
? fileContents(VirtualFiles, path)
: file is IVirtualFile ifile
? ifile.GetContents()
: throw new NotSupportedException(nameof(fileContents) + " expects string virtualPath or IVirtualFile but was " + file.GetType().Name);
public string textContents(IVirtualFile file) => file?.ReadAllText();
public byte[] fileBytesContent(string virtualPath) => fileBytesContent(VirtualFiles, virtualPath);
public byte[] fileBytesContent(IVirtualPathProvider vfs, string virtualPath) => vfs.GetFile(virtualPath)?.ReadAllBytes();
public byte[] bytesContent(IVirtualFile file) => file?.ReadAllBytes();
public string fileHash(string virtualPath) => fileHash(VirtualFiles,virtualPath);
public string fileHash(IVirtualPathProvider vfs, string virtualPath) => vfs.GetFileHash(virtualPath);
public string fileHash(IVirtualFile file) => file?.GetFileHash();
public bool fileIsBinary(IVirtualFile file) => MimeTypes.IsBinary(MimeTypes.GetMimeType(file.Extension));
public string fileContentType(IVirtualFile file) => MimeTypes.GetMimeType(file.Extension);
//alias
public Task urlContents(ScriptScopeContext scope, string url) => includeurl(scope, url, null);
public Task urlContents(ScriptScopeContext scope, string url, object options) => includeurl(scope, url, options);
public Task includeurl(ScriptScopeContext scope, string url) => includeurl(scope, url, null);
public async Task includeurl(ScriptScopeContext scope, string url, object options)
{
var scopedParams = scope.AssertOptions(nameof(includeUrl), options);
var webReq = initWebRequest(url, scopedParams);
if (scopedParams.TryRemove("data", out object data))
{
if (webReq.ContentType == null)
webReq.ContentType = MimeTypes.FormUrlEncoded;
var body = ConvertDataToString(data, webReq.ContentType);
using var stream = await webReq.GetRequestStreamAsync();
await stream.WriteAsync(body);
}
using var webRes = await webReq.GetResponseAsync();
{
using var stream = webRes.GetResponseStream();
await stream.CopyToAsync(scope.OutputStream);
}
}
private static HttpWebRequest initWebRequest(string url, Dictionary<string, object> scopedParams)
{
var webReq = (HttpWebRequest) WebRequest.Create(url);
var dataType = scopedParams.TryGetValue("dataType", out object value)
? ConvertDataTypeToContentType((string) value)
: null;
if (scopedParams.TryGetValue("method", out value))
webReq.Method = (string) value;
if (scopedParams.TryGetValue("contentType", out value) || dataType != null)
webReq.ContentType = (string) value ?? dataType;
if (scopedParams.TryGetValue("accept", out value) || dataType != null)
webReq.Accept = (string) value ?? dataType;
if (scopedParams.TryGetValue("userAgent", out value))
PclExport.Instance.SetUserAgent(webReq, (string) value);
return webReq;
}
private static HttpWebRequest postWebRequestSync(string url, Dictionary<string, object> scopedParams)
{
var webReq = initWebRequest(url, scopedParams);