/
KrollBridge.m
1445 lines (1249 loc) Β· 48.2 KB
/
KrollBridge.m
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
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2018 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#import "KrollBridge.h"
#import "APSAnalytics.h"
#import "KrollCallback.h"
#import "TiApp.h"
#import "TiConsole.h"
#import "TiExceptionHandler.h"
#import "TiHost.h"
#import "TiSharedConfig.h"
#import "TiUtils.h"
#import "TopTiModule.h"
#ifndef TI_USE_NATIVE
#define TI_USE_NATIVE 0
#endif
NSString *TitaniumModuleRequireFormat = @"(function(exports){"
"var __OXP=exports;var module={'exports':exports};var __dirname=\"%@\";var __filename=\"%@\";%@;\n"
"if(module.exports !== __OXP){return module.exports;}"
"return exports;})({})";
//Defined private method inside TiBindingRunLoop.m (Perhaps to move to .c?)
void TiBindingRunLoopAnnounceStart(TiBindingRunLoop runLoop);
typedef NS_ENUM(NSInteger, FileStatus) {
FileStatusDoesntExist,
FileStatusExistsOnDisk,
FileStatusExistsEncrypted
};
typedef NS_ENUM(NSInteger, ModuleType) {
Native,
JS,
JSON,
NativeJS
};
@interface ResolvedModule : NSObject {
@public
ModuleType type;
NSString *path;
}
- (id)initWithType:(ModuleType)modType andPath:(NSString *)modPath;
@end
@implementation ResolvedModule
- (id)initWithType:(ModuleType)modType andPath:(NSString *)modPath
{
if ((self = [super init])) {
type = modType;
path = [modPath retain];
}
return self;
}
- (void)dealloc
{
[path release];
[super dealloc];
}
@end
OSSpinLock krollBridgeRegistryLock = OS_SPINLOCK_INIT;
CFMutableSetRef krollBridgeRegistry = nil;
@implementation KrollBridge
+ (void)initialize
{
if (krollBridgeRegistry == nil) {
CFSetCallBacks doNotRetain = kCFTypeSetCallBacks;
doNotRetain.retain = NULL;
doNotRetain.release = NULL;
krollBridgeRegistry = CFSetCreateMutable(NULL, 3, &doNotRetain);
}
}
@synthesize currentURL;
- (void)registerForMemoryWarning
{
WARN_IF_BACKGROUND_THREAD_OBJ; //NSNotificationCenter is not threadsafe!
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didReceiveMemoryWarning:)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
}
- (void)unregisterForMemoryWarning
{
WARN_IF_BACKGROUND_THREAD_OBJ; //NSNotificationCenter is not threadsafe!
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
}
- (id)init
{
if (self = [super init]) {
#if KROLLBRIDGE_MEMORY_DEBUG == 1
NSLog(@"[DEBUG] INIT: %@", self);
#endif
modules = [[NSMutableDictionary alloc] init];
packageJSONMainCache = [[NSMutableDictionary alloc] init];
proxyLock = OS_SPINLOCK_INIT;
OSSpinLockLock(&krollBridgeRegistryLock);
CFSetAddValue(krollBridgeRegistry, self);
OSSpinLockUnlock(&krollBridgeRegistryLock);
TiThreadPerformOnMainThread(^{
[self registerForMemoryWarning];
},
NO);
}
return self;
}
- (void)didReceiveMemoryWarning:(NSNotification *)notification
{
OSSpinLockLock(&proxyLock);
if (registeredProxies == NULL) {
OSSpinLockUnlock(&proxyLock);
[self gc];
return;
}
BOOL keepWarning = YES;
signed long proxiesCount = CFDictionaryGetCount(registeredProxies);
OSSpinLockUnlock(&proxyLock);
// During a memory panic, we may not get the chance to copy proxies.
while (keepWarning) {
keepWarning = NO;
for (id proxy in [(NSDictionary *)registeredProxies allKeys]) {
[proxy didReceiveMemoryWarning:notification];
OSSpinLockLock(&proxyLock);
if (registeredProxies == NULL) {
OSSpinLockUnlock(&proxyLock);
break;
}
signed long newCount = CFDictionaryGetCount(registeredProxies);
OSSpinLockUnlock(&proxyLock);
if (newCount != proxiesCount) {
proxiesCount = newCount;
keepWarning = YES;
break;
}
}
}
[self gc];
}
#if KROLLBRIDGE_MEMORY_DEBUG == 1
- (id)retain
{
NSLog(@"[MEMORY DEBUG] RETAIN: %@ (%d)", self, [self retainCount] + 1);
return [super retain];
}
- (oneway void)release
{
NSLog(@"[MEMORY DEBUG] RELEASE: %@ (%d)", self, [self retainCount] - 1);
[super release];
}
#endif
- (void)removeProxies
{
OSSpinLockLock(&proxyLock);
CFDictionaryRef oldProxies = registeredProxies;
registeredProxies = NULL;
OSSpinLockUnlock(&proxyLock);
for (id thisProxy in (NSDictionary *)oldProxies) {
KrollObject *thisKrollObject = (id)CFDictionaryGetValue(oldProxies, thisProxy);
[thisProxy contextShutdown:self];
[thisKrollObject unprotectJsobject];
}
if (oldProxies != NULL) {
CFRelease(oldProxies);
}
for (NSString *thisModuleKey in modules) {
id thisModule = [modules objectForKey:thisModuleKey];
if ([thisModule respondsToSelector:@selector(unprotectJsobject)]) {
[thisModule unprotectJsobject];
}
}
RELEASE_TO_NIL(modules);
}
- (void)dealloc
{
#if KROLLBRIDGE_MEMORY_DEBUG == 1
NSLog(@"[MEMORY DEBUG] DEALLOC: %@", self);
#endif
[self removeProxies];
RELEASE_TO_NIL(preload);
RELEASE_TO_NIL(context);
OSSpinLockLock(&krollBridgeRegistryLock);
CFSetRemoveValue(krollBridgeRegistry, self);
OSSpinLockUnlock(&krollBridgeRegistryLock);
[super dealloc];
}
- (TiHost *)host
{
return host;
}
- (KrollContext *)krollContext
{
return context;
}
- (id)preloadForKey:(id)key name:(id)name
{
if (preload != nil) {
NSDictionary *dict = [preload objectForKey:name];
if (dict != nil) {
return [dict objectForKey:key];
}
}
return nil;
}
- (void)boot:(id)callback url:(NSURL *)url_ preload:(NSDictionary *)preload_
{
preload = [preload_ retain];
[super boot:callback url:url_ preload:preload_];
context = [[KrollContext alloc] init];
context.delegate = self;
[context start];
}
- (void)evalJSWithoutResult:(NSString *)code
{
[context evalJS:code];
}
// NOTE: this must only be called on the JS thread or an exception will be raised
- (id)evalJSAndWait:(NSString *)code
{
return [context evalJSAndWait:code];
}
- (BOOL)evaluationError
{
return evaluationError;
}
- (void)evalFileOnThread:(NSString *)path context:(KrollContext *)context_
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSError *error = nil;
JSValueRef exception = NULL;
JSContextRef jsContext = [context_ context];
NSURL *url_ = [path hasPrefix:@"file:"] ? [NSURL URLWithString:path] : [NSURL fileURLWithPath:path];
if (![path hasPrefix:@"/"] && ![path hasPrefix:@"file:"]) {
url_ = [NSURL URLWithString:path relativeToURL:url];
}
NSString *jcode = nil;
if ([url_ isFileURL]) {
NSData *data = [TiUtils loadAppResource:url_];
if (data == nil) {
jcode = [NSString stringWithContentsOfFile:[url_ path] encoding:NSUTF8StringEncoding error:&error];
} else {
jcode = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
}
} else {
jcode = [NSString stringWithContentsOfURL:url_ encoding:NSUTF8StringEncoding error:&error];
}
if (error != nil) {
NSLog(@"[ERROR] Error loading path: %@, %@", path, error);
evaluationError = YES;
TiScriptError *scriptError = nil;
// check for file not found a give a friendlier message
if ([error code] == 260 && [error domain] == NSCocoaErrorDomain) {
scriptError = [[TiScriptError alloc] initWithMessage:[NSString stringWithFormat:@"Could not find the file %@", [path lastPathComponent]] sourceURL:nil lineNo:0];
} else {
scriptError = [[TiScriptError alloc] initWithMessage:[NSString stringWithFormat:@"Error loading script %@. %@", [path lastPathComponent], [error description]] sourceURL:nil lineNo:0];
}
[[TiExceptionHandler defaultExceptionHandler] reportScriptError:scriptError];
[scriptError release];
return;
}
const char *urlCString = [[url_ absoluteString] UTF8String];
JSStringRef jsCode = JSStringCreateWithCFString((CFStringRef)jcode);
JSStringRef jsURL = JSStringCreateWithUTF8CString(urlCString);
if (exception == NULL) {
JSEvaluateScript(jsContext, jsCode, NULL, jsURL, 1, &exception);
if (exception == NULL) {
evaluationError = NO;
} else {
evaluationError = YES;
}
}
if (exception != NULL) {
id excm = [KrollObject toID:context value:exception];
evaluationError = YES;
[[TiExceptionHandler defaultExceptionHandler] reportScriptError:[TiUtils scriptErrorValue:excm]];
}
JSStringRelease(jsCode);
JSStringRelease(jsURL);
[pool release];
}
- (void)evalFile:(NSString *)path callback:(id)callback selector:(SEL)selector
{
[context invokeOnThread:self method:@selector(evalFileOnThread:context:) withObject:path callback:callback selector:selector];
}
- (void)evalFile:(NSString *)file
{
[context invokeOnThread:self method:@selector(evalFileOnThread:context:) withObject:file condition:nil];
}
- (void)fireEvent:(id)listener withObject:(id)obj remove:(BOOL)yn thisObject:(TiProxy *)thisObject_
{
if (![listener isKindOfClass:[KrollCallback class]]) {
DebugLog(@"[ERROR] Listener callback is of a non-supported type: %@", [listener class]);
return;
}
KrollEvent *event = [[KrollEvent alloc] initWithCallback:listener eventObject:obj thisObject:thisObject_];
[context enqueue:event];
[event release];
}
- (void)enqueueEvent:(NSString *)type forProxy:(TiProxy *)proxy withObject:(id)obj
{
KrollObject *eventKrollObject = [self krollObjectForProxy:proxy];
KrollEvent *newEvent = [[KrollEvent alloc]
initWithType:type
ForKrollObject:eventKrollObject
eventObject:obj
thisObject:eventKrollObject];
[context enqueue:newEvent];
[newEvent release];
}
- (void)shutdown:(NSCondition *)condition
{
#if KROLLBRIDGE_MEMORY_DEBUG == 1
NSLog(@"[MEMORY DEBUG] DESTROY: %@", self);
#endif
if (!shutdown) {
shutdownCondition = [condition retain];
shutdown = YES;
// fire a notification event to our listeners
WARN_IF_BACKGROUND_THREAD_OBJ; //NSNotificationCenter is not threadsafe!
NSNotification *notification = [NSNotification notificationWithName:kTiContextShutdownNotification object:self];
[[NSNotificationCenter defaultCenter] postNotification:notification];
[context stop];
} else {
[condition lock];
[condition signal];
[condition unlock];
}
}
- (void)gc
{
[context gc];
}
#pragma mark Delegate
- (void)willStartNewContext:(KrollContext *)kroll
{
if (TiUtils.isHyperloopAvailable) {
Class cls = NSClassFromString(@"Hyperloop");
[cls performSelector:@selector(willStartNewContext:bridge:) withObject:kroll withObject:self];
}
[self retain]; // Hold onto ourselves as long as the context needs us
}
- (void)didStartNewContext:(KrollContext *)kroll
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
JSGlobalContextRef jsContext = [kroll context];
JSContext *objcJSContext = [JSContext contextWithJSGlobalContextRef:jsContext];
JSValue *global = [objcJSContext globalObject];
// Make the global object itself available under the name "global"
[global defineProperty:@"global"
descriptor:@{
JSPropertyDescriptorEnumerableKey : @NO,
JSPropertyDescriptorWritableKey : @NO,
JSPropertyDescriptorConfigurableKey : @NO,
JSPropertyDescriptorValueKey : global
}];
// Set the __dirname and __filename for the app.js.
// For other files, it will be injected via the `TitaniumModuleRequireFormat` property
[global defineProperty:@"__dirname"
descriptor:@{
JSPropertyDescriptorEnumerableKey : @NO,
JSPropertyDescriptorWritableKey : @NO,
JSPropertyDescriptorConfigurableKey : @NO,
JSPropertyDescriptorValueKey : @"/"
}];
[global defineProperty:@"__filename"
descriptor:@{
JSPropertyDescriptorEnumerableKey : @NO,
JSPropertyDescriptorWritableKey : @NO,
JSPropertyDescriptorConfigurableKey : @NO,
JSPropertyDescriptorValueKey : @"/app.js"
}];
// Now define "Ti" and "Titanium" on the global
TopTiModule *module = [[TopTiModule alloc] init];
JSValue *titanium = [JSValue valueWithObject:module inContext:objcJSContext];
NSDictionary *dictionary = @{
JSPropertyDescriptorEnumerableKey : @NO,
JSPropertyDescriptorWritableKey : @YES,
JSPropertyDescriptorConfigurableKey : @NO,
JSPropertyDescriptorValueKey : titanium
};
[global defineProperty:@"Titanium" descriptor:dictionary];
[global defineProperty:@"Ti" descriptor:dictionary];
// Hack the old-school way of doing a module here
NSArray *legacyModuleNames = @[ @"App",
@"Contacts",
@"Media",
@"Network",
@"Stream",
@"UI",
@"XML" ];
for (NSString *name in legacyModuleNames) {
// We must generate the block and copy it to put it into heap or else every instance of the block shares
// the same "name" value. See https://stackoverflow.com/questions/7750907/blocks-loops-and-local-variables
JSValue * (^lazyLoad)() = ^() {
JSValue *result;
TiModule *mod = [host moduleNamed:name context:self];
if (mod != nil) {
KrollObject *ko = [self registerProxy:mod];
result = [JSValue valueWithJSValueRef:[ko jsobject] inContext:[JSContext currentContext]];
} else {
result = [JSValue valueWithUndefinedInContext:[JSContext currentContext]];
}
[[JSContext currentThis] defineProperty:name
descriptor:@{
JSPropertyDescriptorValueKey : result,
JSPropertyDescriptorWritableKey : @NO,
JSPropertyDescriptorEnumerableKey : @NO,
JSPropertyDescriptorConfigurableKey : @NO
}];
return result;
};
[titanium defineProperty:name
descriptor:@{
JSPropertyDescriptorConfigurableKey : @YES,
JSPropertyDescriptorGetKey : [[lazyLoad copy] autorelease]
}];
}
// New JSExport based modules
// Basically a whitelist of Ti.* modules to load lazily
NSArray *moduleNames = @[ @"Accelerometer", @"Analytics", @"API", @"Calendar", @"Codec", @"Database", @"Filesystem", @"Geolocation", @"Gesture", @"Locale", @"Platform", @"Utils" ];
for (NSString *name in moduleNames) {
// We must generate the block and copy it to put it into heap or else every instance of the block shares
// the same "name" value. See https://stackoverflow.com/questions/7750907/blocks-loops-and-local-variables
JSValue * (^lazyLoad)() = ^() {
JSValue *result;
Class moduleClass = NSClassFromString([NSString stringWithFormat:@"%@Module", name]);
if (moduleClass != nil) {
result = [JSValue valueWithObject:[[moduleClass alloc] init] inContext:[JSContext currentContext]];
} else {
result = [JSValue valueWithUndefinedInContext:[JSContext currentContext]];
}
[[JSContext currentThis] defineProperty:name
descriptor:@{
JSPropertyDescriptorValueKey : result,
JSPropertyDescriptorWritableKey : @NO,
JSPropertyDescriptorEnumerableKey : @NO,
JSPropertyDescriptorConfigurableKey : @NO
}];
return result;
};
[titanium defineProperty:name
descriptor:@{
JSPropertyDescriptorConfigurableKey : @YES,
JSPropertyDescriptorGetKey : [[lazyLoad copy] autorelease]
}];
}
// FIXME Re-enable analytics setters here
if ([[TiSharedConfig defaultConfig] isAnalyticsEnabled]) {
APSAnalytics *sharedAnalytics = [APSAnalytics sharedInstance];
NSString *buildType = [[TiSharedConfig defaultConfig] applicationBuildType];
NSString *deployType = [[TiSharedConfig defaultConfig] applicationDeployType];
NSString *guid = [[TiSharedConfig defaultConfig] applicationGUID];
if (buildType != nil || buildType.length > 0) {
[sharedAnalytics performSelector:@selector(setBuildType:) withObject:buildType];
}
[sharedAnalytics performSelector:@selector(setSDKVersion:) withObject:[module performSelector:@selector(version)]];
[sharedAnalytics enableWithAppKey:guid andDeployType:deployType];
}
// Load the "console" object into the global scope
objcJSContext[@"console"] = [[TiConsole alloc] init];
//if we have a preload dictionary, register those static key/values into our namespace
if (preload != nil) {
for (NSString *name in preload) {
JSValue *moduleJSObject = titanium[name];
KrollObject *ti = (KrollObject *)JSObjectGetPrivate([moduleJSObject JSValueRef]);
NSDictionary *values = preload[name];
for (id key in values) {
id target = values[key];
KrollObject *ko = [self krollObjectForProxy:target];
if (ko == nil) {
ko = [self registerProxy:target];
}
[ti noteKrollObject:ko forKey:key];
[ti setStaticValue:ko forKey:key purgable:NO];
}
}
// We need to run this before the app.js, which means it has to be here.
TiBindingRunLoopAnnounceStart(kroll);
[self evalFile:[url path] callback:self selector:@selector(booted)];
} else {
// now load the app.js file and get started
NSURL *startURL = [host startURL];
// We need to run this before the app.js, which means it has to be here.
TiBindingRunLoopAnnounceStart(kroll);
[self evalFile:[startURL absoluteString] callback:self selector:@selector(booted)];
}
if (TiUtils.isHyperloopAvailable) {
Class cls = NSClassFromString(@"Hyperloop");
[cls performSelector:@selector(didStartNewContext:bridge:) withObject:kroll withObject:self];
}
[pool release];
}
- (void)willStopNewContext:(KrollContext *)kroll
{
if (TiUtils.isHyperloopAvailable) {
Class cls = NSClassFromString(@"Hyperloop");
[cls performSelector:@selector(willStopNewContext:bridge:) withObject:kroll withObject:self];
}
if (!shutdown) {
shutdown = YES;
// fire a notification event to our listeners
WARN_IF_BACKGROUND_THREAD_OBJ; //NSNotificationCenter is not threadsafe!
NSNotification *notification = [NSNotification notificationWithName:kTiContextShutdownNotification object:self];
[[NSNotificationCenter defaultCenter] postNotification:notification];
}
if (shutdownCondition) {
[shutdownCondition lock];
[shutdownCondition signal];
[shutdownCondition unlock];
RELEASE_TO_NIL(shutdownCondition);
}
}
- (void)didStopNewContext:(KrollContext *)kroll
{
TiThreadPerformOnMainThread(^{
[self unregisterForMemoryWarning];
},
NO);
[self removeProxies];
RELEASE_TO_NIL(console);
RELEASE_TO_NIL(context);
RELEASE_TO_NIL(preload);
if (TiUtils.isHyperloopAvailable) {
Class cls = NSClassFromString(@"Hyperloop");
[cls performSelector:@selector(didStopNewContext:bridge:) withObject:kroll withObject:self];
}
[self autorelease]; // Safe to release now that the context is done
}
- (void)registerProxy:(id)proxy krollObject:(KrollObject *)ourKrollObject
{
OSSpinLockLock(&proxyLock);
if (registeredProxies == NULL) {
registeredProxies = CFDictionaryCreateMutable(NULL, 10, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
}
//NOTE: Do NOT treat registeredProxies like a mutableDictionary; mutable dictionaries copy keys,
//CFMutableDictionaryRefs only retain keys, which lets them work with proxies properly.
CFDictionaryAddValue(registeredProxies, proxy, ourKrollObject);
OSSpinLockUnlock(&proxyLock);
[proxy boundBridge:self withKrollObject:ourKrollObject];
}
- (id)registerProxy:(id)proxy
{
KrollObject *ourKrollObject = [self krollObjectForProxy:proxy];
if (ourKrollObject != nil) {
return ourKrollObject;
}
if (![context isKJSThread]) {
return nil;
}
ourKrollObject = [[KrollObject alloc] initWithTarget:proxy context:context];
[ourKrollObject applyGarbageCollectionSafeguard];
[self registerProxy:proxy
krollObject:ourKrollObject];
return [ourKrollObject autorelease];
}
- (void)unregisterProxy:(id)proxy
{
OSSpinLockLock(&proxyLock);
if (registeredProxies != NULL) {
CFDictionaryRemoveValue(registeredProxies, proxy);
//Don't bother with removing the empty registry. It's small and leaves on dealloc anyways.
}
OSSpinLockUnlock(&proxyLock);
[proxy unboundBridge:self];
}
- (BOOL)usesProxy:(id)proxy
{
if (proxy == nil) {
return NO;
}
BOOL result = NO;
OSSpinLockLock(&proxyLock);
if (registeredProxies != NULL) {
result = (CFDictionaryGetCountOfKey(registeredProxies, proxy) != 0);
}
OSSpinLockUnlock(&proxyLock);
return result;
}
- (id)krollObjectForProxy:(id)proxy
{
id result = nil;
OSSpinLockLock(&proxyLock);
if (registeredProxies != NULL) {
result = (id)CFDictionaryGetValue(registeredProxies, proxy);
}
OSSpinLockUnlock(&proxyLock);
return result;
}
- (KrollWrapper *)loadCommonJSModule:(NSString *)code withSourceURL:(NSURL *)sourceURL
{
// FIXME: Can we skip all of this now? Doesn't we already properly resolve paths?
// This takes care of resolving paths like `../../foo.js`
sourceURL = [NSURL fileURLWithPath:[[sourceURL path] stringByStandardizingPath]];
// Get the relative path to the Resources directory
NSString *filename = [[sourceURL path] stringByReplacingOccurrencesOfString:[[[NSBundle mainBundle] resourceURL] path] withString:@""];
NSString *dirname = [filename stringByDeletingLastPathComponent];
NSString *js = [[NSString alloc] initWithFormat:TitaniumModuleRequireFormat, dirname, filename, code];
/* This most likely should be integrated with normal code flow, but to
* minimize impact until a in-depth reconsideration of KrollContext can be
* done, we should have as little footprint
*/
KrollEval *eval = [[KrollEval alloc] initWithCode:js sourceURL:sourceURL startingLineNo:1];
JSValueRef exception = NULL;
JSValueRef resultRef = [eval jsInvokeInContext:context exception:&exception];
[js release];
[eval release];
if (exception != NULL) {
id excm = [KrollObject toID:context value:exception];
[[TiExceptionHandler defaultExceptionHandler] reportScriptError:[TiUtils scriptErrorValue:excm]];
return nil;
}
/*
* In order to work around the underlying issue of TIMOB-2392, we must
* use KrollWrapper as a JS wrapper instead of converting it to a proxy
*/
KrollWrapper *result = [[KrollWrapper alloc] init];
[result setBridge:self];
[result setJsobject:(JSObjectRef)resultRef];
[result protectJsobject];
return [result autorelease];
}
- (NSString *)pathToModuleClassName:(NSString *)path
{
//TODO: switch to use ApplicationMods
NSArray *tokens = [path componentsSeparatedByString:@"."];
NSMutableString *modulename = [NSMutableString string];
for (NSString *token in tokens) {
[modulename appendFormat:@"%@%@", [[token substringToIndex:1] uppercaseString], [token substringFromIndex:1]];
}
[modulename appendString:@"Module"];
return modulename;
}
- (TiModule *)loadCoreModule:(NSString *)moduleID withContext:(KrollContext *)kroll
{
NSString *moduleClassName = [self pathToModuleClassName:moduleID];
Class moduleClass = NSClassFromString(moduleClassName);
// If no such module exists, bail out!
if (moduleClass == nil) {
return nil;
}
// If there is a JS file that collides with the given path,
// warn the user of the collision, but prefer the native/core module
NSURL *jsPath = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@.js", [[NSURL fileURLWithPath:[TiHost resourcePath] isDirectory:YES] path], moduleID]];
if ([[NSFileManager defaultManager] fileExistsAtPath:[jsPath absoluteString]]) {
NSLog(@"[WARN] The requested path '%@' has a collison between a native Ti%@um API/module and a JS file.", moduleID, @"tani");
NSLog(@"[WARN] The native Ti%@um API/module will be loaded in preference.", @"tani");
NSLog(@"[WARN] If you intended to address the JS file, please require the path using a prefixed string such as require('./%@') or require('/%@') instead.", moduleID, moduleID);
}
// Ok, we have a native module, make sure instantiate and cache it
TiModule *module = [modules objectForKey:moduleID];
if (module == nil) {
module = [[moduleClass alloc] _initWithPageContext:self];
[module setHost:host];
[module _setName:moduleClassName];
[modules setObject:module forKey:moduleID];
[module autorelease];
}
// does it have JS? No, then nothing else to do...
if (![module isJSModule]) {
return module;
}
NSData *data = [module moduleJS];
if (data == nil) {
// Uh oh, no actual data. Let's just punt and return the native module as-is
return module;
}
NSString *contents = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
NSURL *url_ = [TiHost resourceBasedURL:moduleID baseURL:NULL];
KrollWrapper *wrapper = [self loadCommonJSModule:contents withSourceURL:url_];
// For right now, we need to mix any compiled JS on top of a compiled module, so that both components
// are accessible. We store the exports object and then put references to its properties on the toplevel
// object.
JSContextRef jsContext = [[self krollContext] context];
JSObjectRef jsObject = [wrapper jsobject];
KrollObject *moduleObject = [module krollObjectForContext:[self krollContext]];
[moduleObject noteObject:jsObject forTiString:kTiStringExportsKey context:jsContext];
JSPropertyNameArrayRef properties = JSObjectCopyPropertyNames(jsContext, jsObject);
size_t count = JSPropertyNameArrayGetCount(properties);
for (size_t i = 0; i < count; i++) {
// Mixin the property onto the module JS object if it's not already there
JSStringRef propertyName = JSPropertyNameArrayGetNameAtIndex(properties, i);
if (!JSObjectHasProperty(jsContext, [moduleObject jsobject], propertyName)) {
JSValueRef property = JSObjectGetProperty(jsContext, jsObject, propertyName, NULL);
JSObjectSetProperty([[self krollContext] context], [moduleObject jsobject], propertyName, property, kJSPropertyAttributeReadOnly, NULL);
}
}
JSPropertyNameArrayRelease(properties);
return module;
}
- (KrollWrapper *)loadCoreModuleAsset:(NSString *)path withContext:(KrollContext *)kroll
{
NSArray<NSString *> *pathComponents = [path pathComponents];
NSString *moduleID = [pathComponents objectAtIndex:0];
NSRange separatorLocation = [path rangeOfString:@"/"];
// check rest of path FIXME: Just rejoin pathComponents?
NSString *assetPath = [path substringFromIndex:separatorLocation.location + 1];
TiModule *module = [self loadCoreModule:moduleID withContext:kroll];
// Try to load the file as module asset!
NSString *filepath = [assetPath stringByAppendingString:@".js"];
NSData *data = [module loadModuleAsset:filepath];
// does it exist in module?
if (data == nil) {
return nil;
}
NSString *contents = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
// This is an asset inside the native module. Load it like a "normal" common js file
return [self loadJavascriptText:contents fromFile:filepath withContext:kroll];
}
- (NSString *)loadFile:(NSString *)path
{
// check if file exists by using cheat index.json which tells us if on disk or encrypted.
FileStatus status = [self fileStatus:path];
NSURL *url_ = [NSURL URLWithString:path relativeToURL:[[self host] baseURL]];
NSData *data;
switch (status) {
case FileStatusExistsOnDisk:
data = [NSData dataWithContentsOfURL:url_]; // load from disk
break;
case FileStatusExistsEncrypted:
data = [TiUtils loadAppResource:url_]; // try to load encrypted file
break;
case FileStatusDoesntExist:
default:
return nil;
}
if (data != nil) {
return [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
}
return nil;
}
- (KrollWrapper *)loadJavascriptObject:(NSString *)data fromFile:(NSString *)filename withContext:(KrollContext *)kroll
{
NSError *jsonParseError = nil;
// 1. Parse JSON
__unused NSDictionary *parsedJSON = [TiUtils jsonParse:data error:&jsonParseError];
// 2. Validate parsed JSON
if (jsonParseError != nil) {
DebugLog(@"[ERROR] Unable to parse JSON input!");
return nil;
}
// 3. Assign valid JSON to module.exports
data = [NSString stringWithFormat:@"module.exports = %@;", data];
return [self loadJavascriptText:data fromFile:filename withContext:kroll];
}
- (KrollWrapper *)loadJavascriptText:(NSString *)data fromFile:(NSString *)filename withContext:(KrollContext *)kroll
{
NSURL *url_ = [TiHost resourceBasedURL:filename baseURL:NULL];
KrollWrapper *module = [self loadCommonJSModule:data withSourceURL:url_];
if (![module respondsToSelector:@selector(replaceValue:forKey:notification:)]) {
@throw [NSException exceptionWithName:@"org.appcelerator.kroll"
reason:[NSString stringWithFormat:@"Module \"%@\" failed to leave a valid exports object", filename]
userInfo:nil];
}
if (filename != nil && module != nil) {
// uri is optional but we point it to where we loaded it
[module replaceValue:[NSString stringWithFormat:@"app://%@", filename] forKey:@"uri" notification:NO];
[module replaceValue:filename forKey:@"id" notification:NO]; // set id to full path, originally this was the path from require call
}
return module;
}
- (KrollWrapper *)loadAsFile:(NSString *)path withContext:(KrollContext *)kroll
{
NSString *filename = path;
NSString *data;
// 1. If X is a file, load X as JavaScript text. STOP
// Note: I modified the algorithm here to handle .json files as JSON, everything else as JS
NSString *ext = [filename pathExtension];
BOOL json = (ext != nil && [ext isEqual:@"json"]);
data = [self loadFile:filename];
if (data != nil) {
if (json) {
return [self loadJavascriptObject:data fromFile:filename withContext:context];
} else {
return [self loadJavascriptText:data fromFile:filename withContext:context];
}
}
// 2. If X.js is a file, load X.js as JavaScript text. STOP
filename = [path stringByAppendingString:@".js"];
data = [self loadFile:filename];
if (data != nil) {
return [self loadJavascriptText:data fromFile:filename withContext:context];
}
// 3. If X.json is a file, parse X.json to a JavaScript Object. STOP
filename = [path stringByAppendingString:@".json"];
data = [self loadFile:filename];
if (data != nil) {
return [self loadJavascriptObject:data fromFile:filename withContext:context];
}
// failed to load anything!
return nil;
}
/* changes current URL to keep track when requiring to know our working path to resolve from */
- (void)updateCurrentURLFromPath:(NSString *)path
{
[self setCurrentURL:[NSURL URLWithString:[path stringByDeletingLastPathComponent] relativeToURL:[[self host] baseURL]]];
}
/* returns full path to main file declared in given package json, only if it exists! */
- (NSString *)packageJSONMain:(NSString *)packageJsonPath
{
// check special package.json cache
NSString *m = packageJSONMainCache[packageJsonPath];
if (m != nil) {
return m;
}
NSString *data = [self loadFile:packageJsonPath];
if (data == nil) {
return nil;
}
// a. Parse X/package.json, and look for "main" field.
// Just cheat and use TiUtils.jsonParse here, rather than loading the package.json as a JS object...
NSDictionary *json = [TiUtils jsonParse:data];
if (json == nil) {
return nil;
}
id main = [json objectForKey:@"main"];
if ([main isKindOfClass:[NSString class]]) {
NSString *mainString = (NSString *)main;
NSString *x = [packageJsonPath stringByDeletingLastPathComponent]; // parent dir of package.json
// b. let M = X + (json main field)
m = [x stringByAppendingPathComponent:mainString];
m = [self pathByStandarizingPath:m];
ResolvedModule *resolved = [self tryFileOrDirectory:m];
if (resolved) {
packageJSONMainCache[packageJsonPath] = resolved->path; // cache from package.json to main value
return resolved->path;
}
}
return nil;
}
- (KrollWrapper *)loadAsDirectory:(NSString *)path withContext:(KrollContext *)kroll
{
// 1. If X/package.json is a file,
NSString *filename = [path stringByAppendingPathComponent:@"package.json"];
NSString *resolvedFile = [self packageJSONMain:filename];
if (resolvedFile != nil) {
// c. LOAD_AS_FILE(M)
return [self loadAsFile:resolvedFile withContext:context];
}
NSString *data;
// 2. If X/index.js is a file, load X/index.js as JavaScript text. STOP
filename = [path stringByAppendingPathComponent:@"index.js"];
data = [self loadFile:filename];
if (data != nil) {
return [self loadJavascriptText:data fromFile:filename withContext:context];
}
// 3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
filename = [path stringByAppendingPathComponent:@"index.json"];
data = [self loadFile:filename];
if (data != nil) {
return [self loadJavascriptObject:data fromFile:filename withContext:context];
}
return nil;
}
- (KrollWrapper *)loadAsFileOrDirectory:(NSString *)path withContext:(KrollContext *)kroll
{
// a. LOAD_AS_FILE(Y + X)
KrollWrapper *module = [self loadAsFile:path withContext:context];
if (module) {
return module;
}
// b. LOAD_AS_DIRECTORY(Y + X)
return [self loadAsDirectory:path withContext:context];
}