-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathModuleInternal.mm
More file actions
1971 lines (1730 loc) · 81.1 KB
/
Copy pathModuleInternal.mm
File metadata and controls
1971 lines (1730 loc) · 81.1 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
#include "ModuleInternal.h"
#import <Foundation/Foundation.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <cmath>
#include <cstring>
#include <string>
#include "BuiltinLoader.h"
#include "Caches.h"
#include "Helpers.h"
#include "HttpLoader.h"
#include "ModuleInternalCallbacks.h" // for ResolveModuleCallback
#include "NativeScriptException.h"
#include "NsBuiltinModules.h"
#include "Runtime.h"
#include "RuntimeConfig.h"
#include "napi/NapiModules.h"
using namespace v8;
namespace tns {
// Helper function to check if a file path is an ES module (.mjs) but not a source map (.mjs.map)
bool IsESModule(const std::string& path) {
return path.size() >= 4 && path.compare(path.size() - 4, 4, ".mjs") == 0 &&
!(path.size() >= 8 && path.compare(path.size() - 8, 8, ".mjs.map") == 0);
}
// A package-style specifier: neither a path nor a scheme, so it may be claimed
// by a registry rather than resolved on disk.
static bool IsBareSpecifier(const std::string& specifier) {
if (specifier.empty() || specifier[0] == '.' || specifier[0] == '/' ||
specifier[0] == '~') {
return false;
}
return specifier.find(':') == std::string::npos;
}
static std::string NormalizePath(const std::string& path);
// How an entry module's graph settles. For local modules the bound is a yield,
// not a timeout: only nestable V8 tasks can run while these JS frames are on
// the stack, so a TLA parked on a non-nestable foreground task can never settle
// in-pump — give it one short window, then return and let the real event loop
// finish it after the turn (the Node shape; EventLoopTests pins this). HTTP
// entries must settle in-pump — the dev client needs the rejection reason
// synchronously — so they get the full deadline and the runloop slices their
// transport needs.
static ModuleEvaluationOptions BootEntryEvaluationOptions(bool isHttpModule) {
ModuleEvaluationOptions options;
options.policy = ModuleEvaluationPolicy::kSyncPumping;
options.deadlineSeconds = isHttpModule ? kModuleEvaluateDeadlineSeconds : 1.0;
options.timeoutBehavior = isHttpModule ? ModuleEvaluationOptions::TimeoutBehavior::kThrow
: ModuleEvaluationOptions::TimeoutBehavior::kReturnPending;
options.pumpRunLoop = isHttpModule;
return options;
}
// How a graph reached through require() settles. A pumping require must settle
// or throw — handing back a half-initialized namespace is what the strict
// policy exists to prevent — so it gets the full deadline. It never slices the
// Cocoa runloop: outside boot the loop belongs to the app, and re-entering
// arbitrary runloop sources from the middle of a require would run UI callbacks
// underneath JS frames.
static ModuleEvaluationOptions RequireEvaluationOptions(ModuleEvaluationPolicy policy) {
ModuleEvaluationOptions options;
options.policy = policy;
if (policy == ModuleEvaluationPolicy::kSyncPumping) {
options.deadlineSeconds = kModuleEvaluateDeadlineSeconds;
options.timeoutBehavior = ModuleEvaluationOptions::TimeoutBehavior::kThrow;
options.pumpRunLoop = false;
}
return options;
}
static inline bool StartsWith(const std::string& value, const char* prefix) {
size_t n = strlen(prefix);
return value.size() >= n && value.compare(0, n, prefix) == 0;
}
static std::string NormalizeHttpModuleUrl(const std::string& path) {
if (path.empty()) {
return path;
}
std::string normalized = path;
if (StartsWith(normalized, "file://http://") || StartsWith(normalized, "file://https://")) {
normalized = normalized.substr(strlen("file://"));
}
if (normalized.rfind("http:/", 0) == 0 && normalized.rfind("http://", 0) != 0) {
normalized.insert(5, "/");
} else if (normalized.rfind("https:/", 0) == 0 && normalized.rfind("https://", 0) != 0) {
normalized.insert(6, "/");
}
return normalized;
}
static bool IsHttpModulePath(const std::string& path) {
std::string normalized = NormalizeHttpModuleUrl(path);
return StartsWith(normalized, "http://") || StartsWith(normalized, "https://");
}
static std::string CanonicalizeModulePath(const std::string& path) {
if (IsHttpModulePath(path)) {
return CanonicalizeHttpUrlKey(NormalizeHttpModuleUrl(path));
}
return NormalizePath(path);
}
// Normalize file system paths to a canonical representation so lookups in
// registry remain consistent regardless of how the path was provided.
static std::string NormalizePath(const std::string& path) {
if (path.empty()) {
return path;
}
NSString* nsPath = [NSString stringWithUTF8String:path.c_str()];
if (nsPath == nil) {
return path;
}
NSString* standardized = [nsPath stringByStandardizingPath];
if (standardized == nil) {
return path;
}
return std::string([standardized UTF8String]);
}
// Helper function to resolve main entry from package.json with proper extension handling
std::string ResolveMainEntryFromPackageJson(const std::string& baseDir) {
// Get the main value from package.json
id mainValue = Runtime::GetAppConfigValue("main");
NSString* mainEntry = nil;
if (mainValue && [mainValue isKindOfClass:[NSString class]]) {
mainEntry = (NSString*)mainValue;
} else {
// Fallback to "index" if no main field found
mainEntry = @"index";
}
// Try the main entry with different extensions
NSString* basePath =
[[NSString stringWithUTF8String:baseDir.c_str()] stringByAppendingPathComponent:mainEntry];
// Check if file exists as-is
if (tns::Exists([basePath fileSystemRepresentation])) {
return std::string([basePath UTF8String]);
}
// Try with .js extension
else if (tns::Exists(
[[basePath stringByAppendingPathExtension:@"js"] fileSystemRepresentation])) {
return std::string([[basePath stringByAppendingPathExtension:@"js"] UTF8String]);
}
// Try with .mjs extension
else if (tns::Exists(
[[basePath stringByAppendingPathExtension:@"mjs"] fileSystemRepresentation])) {
return std::string([[basePath stringByAppendingPathExtension:@"mjs"] UTF8String]);
} else {
// If none found, default to .js (let the loading system handle the error)
return std::string([[basePath stringByAppendingPathExtension:@"js"] UTF8String]);
}
}
ModuleInternal::ModuleInternal(Local<Context> context) {
Isolate* isolate = v8::Isolate::GetCurrent();
Local<Object> global = context->Global();
TryCatch tc(isolate);
Local<Value> result;
if (!BuiltinLoader::RunBuiltin(context, BuiltinId::kRequireFactory).ToLocal(&result)) {
if (tc.HasCaught()) {
tns::LogError(isolate, tc);
}
Log(@"FATAL: Failed to run require factory script");
return;
}
if (result.IsEmpty() || !result->IsFunction()) {
Log(@"FATAL: Require factory script did not return a function");
return;
}
this->requireFactoryFunction_ =
std::make_unique<Persistent<v8::Function>>(isolate, result.As<v8::Function>());
Local<FunctionTemplate> requireFuncTemplate = FunctionTemplate::New(
isolate, RequireCallback, External::New(isolate, this, v8::kExternalPointerTypeTagDefault));
this->requireFunction_ = std::make_unique<Persistent<v8::Function>>(
isolate, requireFuncTemplate->GetFunction(context).ToLocalChecked());
// Use shortened path for global require function to avoid V8 parsing issues
std::string globalRequirePath = "/app";
Local<v8::Function> globalRequire = GetRequireFunction(
isolate, globalRequirePath, RequireEvaluationOptions(ModuleEvaluationPolicy::kSyncStrict));
bool success =
global->Set(context, tns::ToV8String(isolate, "require"), globalRequire).FromMaybe(false);
if (!success) {
Log(@"FATAL: Failed to set global require function");
}
}
void ModuleInternal::RunModule(Isolate* isolate, std::string path) {
// The app entry arrives as "./"; resolve it before deciding how to run it so
// an ES module entry takes the module path instead of being require()d. A
// required entry would evaluate under the strict policy, which refuses a
// top-level-await graph outright — so this is what makes `import`/`export`,
// and a TLA entry, legal in an app's main module. Resolved with the same
// function the boot backstop's probe uses, so the evaluated module and the
// probe agree on the registry key. A CommonJS entry keeps "./" and the
// global-require route it has always taken.
if (path == "./") {
std::string mainEntry = ResolveMainEntryFromPackageJson(RuntimeConfig.ApplicationPath);
if (IsESModule(mainEntry) || IsHttpModulePath(mainEntry)) {
path = mainEntry;
}
}
std::shared_ptr<Caches> cache = Caches::Get(isolate);
Local<Context> context = cache->GetContext();
// The ES module branch compiles and links against isolate->GetCurrentContext(),
// and a caller that enters the isolate through a fresh Isolate::Scope
// (RunMainScript) has no current context: the one Runtime::Init entered was
// popped with Init's own scope. The require branch never needed this because
// Function::Call enters the context it is handed.
Context::Scope context_scope(context);
Local<Object> globalObject = context->Global();
bool isHttpModule = IsHttpModulePath(path);
// Ensure global.__dirname is defined so ESM/CommonJS shims relying on it work.
{
Local<Value> dirVal;
bool hasDir = globalObject->Get(context, ToV8String(isolate, "__dirname")).ToLocal(&dirVal);
if (!hasDir || dirVal->IsUndefined()) {
bool setDir = globalObject
->Set(context, ToV8String(isolate, "__dirname"),
ToV8String(isolate, RuntimeConfig.ApplicationPath))
.FromMaybe(false);
if (!setDir) {
Log(@"Warning: Failed to set __dirname on global object");
}
}
}
// ES module fast path
if (IsESModule(path) || isHttpModule) {
Local<Value> moduleNamespace;
if (isHttpModule) {
TNS_DEBUG(Esm, "run-module http-esm begin %s", NormalizeHttpModuleUrl(path).c_str());
}
try {
// The entry runs before this thread's event loop does, so its graph can
// only make progress from the pump inside LoadESModule.
moduleNamespace =
ModuleInternal::LoadESModule(isolate, path, BootEntryEvaluationOptions(isHttpModule));
} catch (const NativeScriptException& ex) {
if (RuntimeConfig.IsDebug) {
Log(@"***** JavaScript exception occurred *****");
Log(@"Error loading ES module: %s", path.c_str());
Log(@"Exception: %s", ex.getMessage().c_str());
}
throw;
}
if (moduleNamespace.IsEmpty()) {
// `LoadESModule` returned an empty value without throwing. Provide a
// directional hint; this is the only case with no actual reason text.
throw NativeScriptException(
std::string("ES module returned empty namespace for ") + path +
" — likely a top-level await that never settled; check the device "
"console for the matching [esm][evaluate][promise-timeout] entry.");
}
if (isHttpModule) {
TNS_DEBUG(Esm, "run-module http-esm ok %s", NormalizeHttpModuleUrl(path).c_str());
}
return;
}
// For CommonJS modules (.js), use the traditional require() approach
Local<Value> requireObj;
bool success = globalObject->Get(context, ToV8String(isolate, "require")).ToLocal(&requireObj);
if (!success || !requireObj->IsFunction()) {
throw NativeScriptException("require function unavailable on globalThis");
}
Local<v8::Function> requireFunc = requireObj.As<v8::Function>();
Local<Value> args[] = {ToV8String(isolate, path)};
Local<Value> result;
TryCatch tc(isolate);
success = requireFunc->Call(context, globalObject, 1, args).ToLocal(&result);
if (!success || tc.HasCaught()) {
if (RuntimeConfig.IsDebug) {
Log(@"***** JavaScript exception occurred *****");
Log(@"Error in require() call:");
Log(@" Requested module: '%s'", path.c_str());
Log(@" Called from: %s", RuntimeConfig.ApplicationPath.c_str());
if (tc.HasCaught()) {
tns::LogError(isolate, tc);
}
}
// The TryCatch form captures the V8 exception, so a worker boundary can
// re-arm it on the isolate (ReThrowToV8) and route it to worker.onerror.
if (tc.HasCaught()) {
throw NativeScriptException(isolate, tc, std::string("require() failed for module ") + path);
}
throw NativeScriptException(std::string("require() failed for module ") + path);
}
}
void ModuleInternal::CreateRequireCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
if (info.Length() < 1 || !info[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(
tns::ToV8String(isolate, "createRequire expects a base directory string")));
return;
}
Runtime* runtime = Runtime::GetRuntime(isolate);
ModuleInternal* moduleInternal = runtime != nullptr ? runtime->GetModuleInternal() : nullptr;
if (moduleInternal == nullptr) {
isolate->ThrowException(Exception::Error(tns::ToV8String(
isolate, "createRequire is unavailable: this isolate has no module loader")));
return;
}
std::string dirName = tns::ToString(isolate, info[0].As<v8::String>());
const bool pumping = info.Length() > 1 && info[1]->BooleanValue(isolate);
ModuleEvaluationOptions options = RequireEvaluationOptions(
pumping ? ModuleEvaluationPolicy::kSyncPumping : ModuleEvaluationPolicy::kSyncStrict);
// ns-module.js validates these at mint time and passes undefined for
// anything the caller left out, so each present value simply overrides its
// default. The numeric one is re-checked here regardless: this binding is a
// boundary of its own, and a NaN or infinite deadline makes every deadline
// comparison in the pump false, which is an unbounded pump rather than a
// long one.
if (info.Length() > 2 && info[2]->IsNumber()) {
const double deadlineSeconds = info[2].As<v8::Number>()->Value();
if (!std::isfinite(deadlineSeconds) || deadlineSeconds <= 0) {
isolate->ThrowException(Exception::TypeError(tns::ToV8String(
isolate, "createRequire: 'deadlineSeconds' must be a positive finite number")));
return;
}
options.deadlineSeconds = deadlineSeconds;
}
if (info.Length() > 3 && info[3]->IsBoolean()) {
options.timeoutBehavior = info[3]->BooleanValue(isolate)
? ModuleEvaluationOptions::TimeoutBehavior::kThrow
: ModuleEvaluationOptions::TimeoutBehavior::kReturnPending;
}
if (info.Length() > 4 && info[4]->IsBoolean()) {
options.pumpRunLoop = info[4]->BooleanValue(isolate);
}
info.GetReturnValue().Set(moduleInternal->GetRequireFunction(isolate, dirName, options));
}
bool ModuleInternal::InstallCreateRequireBinding(Local<Context> context, Local<Object> binding) {
Isolate* isolate = v8::Isolate::GetCurrent();
Local<v8::Function> fn;
if (!v8::Function::New(context, ModuleInternal::CreateRequireCallback).ToLocal(&fn)) {
return false;
}
fn->SetName(tns::ToV8String(isolate, "createRequire"));
return binding->CreateDataProperty(context, tns::ToV8String(isolate, "createRequire"), fn)
.FromMaybe(false);
}
Local<v8::Function> ModuleInternal::GetRequireFunction(Isolate* isolate, const std::string& dirName,
const ModuleEvaluationOptions& options) {
Local<v8::Function> requireFuncFactory = requireFactoryFunction_->Get(isolate);
Local<Context> context = isolate->GetCurrentContext();
Local<v8::Function> requireInternalFunc = this->requireFunction_->Get(isolate);
Local<Value> args[6]{
requireInternalFunc,
tns::ToV8String(isolate, dirName.c_str()),
Integer::New(isolate, static_cast<int>(options.policy)),
v8::Number::New(isolate, options.deadlineSeconds),
v8::Boolean::New(isolate,
options.timeoutBehavior == ModuleEvaluationOptions::TimeoutBehavior::kThrow),
v8::Boolean::New(isolate, options.pumpRunLoop)};
Local<Value> result;
Local<Object> thiz = Object::New(isolate);
TryCatch tc(isolate);
bool success = requireFuncFactory->Call(context, thiz, 6, args).ToLocal(&result);
if (!success || tc.HasCaught()) {
if (tc.HasCaught()) {
tns::LogError(isolate, tc);
}
Log(@"FATAL: Failed to call require factory function");
// A require that cannot exist must throw when called, in every build.
result = v8::Function::New(context, [](const v8::FunctionCallbackInfo<v8::Value>& info) {
info.GetIsolate()->ThrowException(v8::Exception::Error(
tns::ToV8String(info.GetIsolate(), "Require function unavailable")));
}).ToLocalChecked();
}
if (result.IsEmpty() || !result->IsFunction()) {
Log(@"FATAL: Require factory did not return a function");
result = v8::Function::New(context, [](const v8::FunctionCallbackInfo<v8::Value>& info) {
info.GetIsolate()->ThrowException(v8::Exception::Error(
tns::ToV8String(info.GetIsolate(), "Require function unavailable")));
}).ToLocalChecked();
}
return result.As<v8::Function>();
}
// Node's `determineSpecificType` (lib/internal/errors.js), so an
// ERR_INVALID_ARG_TYPE-shaped message reads the same here as it does there.
// Deliberately side-effect free: no getter, no user `toString`, no `inspect`.
static std::string DescribeValueForTypeError(Isolate* isolate, Local<Value> value) {
if (value.IsEmpty() || value->IsUndefined()) {
return "undefined";
}
if (value->IsNull()) {
return "null";
}
if (value->IsFunction()) {
std::string name = tns::ToString(isolate, value.As<v8::Function>()->GetName());
return name.empty() ? "an instance of Function" : "function " + name;
}
if (value->IsObject()) {
std::string ctorName = tns::ToString(isolate, value.As<Object>()->GetConstructorName());
return ctorName.empty() ? "an object" : "an instance of " + ctorName;
}
// A primitive: `type <typeof> (<value>)`.
const char* typeName = "object";
std::string rendered;
if (value->IsBoolean()) {
typeName = "boolean";
rendered = value->IsTrue() ? "true" : "false";
} else if (value->IsNumber()) {
typeName = "number";
double number = value.As<v8::Number>()->Value();
// String(-0) is "0", but Node renders the sign, and losing it here would
// hide exactly the distinction the message is meant to surface.
rendered = (number == 0 && std::signbit(number)) ? "-0" : tns::ToString(isolate, value);
} else if (value->IsBigInt()) {
typeName = "bigint";
rendered = tns::ToString(isolate, value) + "n";
} else if (value->IsSymbol()) {
typeName = "symbol";
Local<Value> description = value.As<v8::Symbol>()->Description(isolate);
rendered = "Symbol(" +
(description->IsUndefined() ? std::string() : tns::ToString(isolate, description)) +
")";
} else {
rendered = tns::ToString(isolate, value);
}
if (rendered.size() > 28) {
rendered = rendered.substr(0, 25) + "...";
}
return "type " + std::string(typeName) + " (" + rendered + ")";
}
void ModuleInternal::RequireCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
// Every path below assumes a string specifier — the builtin probe, the
// http(s) guard and the filesystem resolution all read it — so reject a
// non-string before any of them rather than casting one unchecked.
if (info.Length() < 1 || !info[0]->IsString()) {
Local<Value> received = info.Length() < 1 ? Local<Value>() : info[0];
isolate->ThrowException(Exception::TypeError(
tns::ToV8String(isolate, "The \"id\" argument must be of type string. Received " +
DescribeValueForTypeError(isolate, received))));
return;
}
// Builtin modules resolve before any path handling, so they can never be
// shadowed by a file or a package, and an unknown one fails as a missing
// builtin rather than as a missing file. Only prefixed specifiers get here:
// a bare `util` still resolves through npm.
{
std::string specifier = tns::ToString(isolate, info[0].As<v8::String>());
if (NsBuiltinModules::IsBuiltinScheme(specifier)) {
Local<Context> context = isolate->GetCurrentContext();
Local<Object> exports;
if (NsBuiltinModules::GetExports(context, specifier).ToLocal(&exports)) {
info.GetReturnValue().Set(exports);
} else if (!NsBuiltinModules::IsRegistered(specifier)) {
isolate->ThrowException(Exception::Error(
tns::ToV8String(isolate, NsBuiltinModules::NotFoundMessage(specifier))));
}
return;
}
// Node-API addons claim a bare name only, so a path can never be diverted
// into the addon registry, and builtins keep priority over both.
if (IsBareSpecifier(specifier) && NapiModules::IsRegistered(specifier)) {
Local<Context> context = isolate->GetCurrentContext();
Local<Object> exports;
if (NapiModules::GetExports(context, specifier).ToLocal(&exports)) {
info.GetReturnValue().Set(exports);
} else if (!isolate->HasPendingException()) {
// The addon is registered but failed to initialize. Returning
// undefined would hand the caller a module-shaped hole to trip over
// later; the failure belongs at the require() call.
isolate->ThrowException(Exception::Error(
tns::ToV8String(isolate, "Failed to initialize Node-API module '" + specifier + "'")));
}
return;
}
}
// Declare these outside try block so they're available in catch
std::string moduleName;
std::string callingModuleDirName;
NSString* fullPath = nil;
try {
// Guard: URL-based modules must be loaded via dynamic import() in dev HTTP ESM mode.
moduleName = tns::ToString(isolate, info[0]);
if (moduleName.rfind("http://", 0) == 0 || moduleName.rfind("https://", 0) == 0) {
std::string msg = std::string("NativeScript: require() of URL module is not supported: ") +
moduleName + ". Use dynamic import() instead.";
throw NativeScriptException(msg.c_str());
}
ModuleInternal* moduleInternal = static_cast<ModuleInternal*>(
info.Data().As<External>()->Value(v8::kExternalPointerTypeTagDefault));
moduleName = tns::ToString(isolate, info[0].As<v8::String>());
callingModuleDirName = tns::ToString(isolate, info[1].As<v8::String>());
// The require factory forwards the options its require was minted with;
// an absent policy is the strict default every ordinary require uses.
ModuleEvaluationPolicy policy = ModuleEvaluationPolicy::kSyncStrict;
if (info.Length() > 2 && info[2]->IsInt32() &&
info[2].As<Int32>()->Value() == static_cast<int>(ModuleEvaluationPolicy::kSyncPumping)) {
policy = ModuleEvaluationPolicy::kSyncPumping;
}
ModuleEvaluationOptions evaluationOptions = RequireEvaluationOptions(policy);
if (info.Length() > 3 && info[3]->IsNumber()) {
evaluationOptions.deadlineSeconds = info[3].As<v8::Number>()->Value();
}
if (info.Length() > 4 && info[4]->IsBoolean()) {
evaluationOptions.timeoutBehavior =
info[4]->BooleanValue(isolate) ? ModuleEvaluationOptions::TimeoutBehavior::kThrow
: ModuleEvaluationOptions::TimeoutBehavior::kReturnPending;
}
if (info.Length() > 5 && info[5]->IsBoolean()) {
evaluationOptions.pumpRunLoop = info[5]->BooleanValue(isolate);
}
// Expand shortened paths back to full paths for file resolution
if (callingModuleDirName.length() > 0 && callingModuleDirName.substr(0, 4) == "/app") {
std::string expandedPath = RuntimeConfig.ApplicationPath + callingModuleDirName.substr(4);
callingModuleDirName = expandedPath;
}
// Special handling for "./" - resolve to main entry point from package.json
if (moduleName == "./") {
std::string mainEntryPath = ResolveMainEntryFromPackageJson(RuntimeConfig.ApplicationPath);
fullPath = [NSString stringWithUTF8String:mainEntryPath.c_str()];
} else if (moduleName.length() > 0 && moduleName[0] != '/') {
if (moduleName[0] == '.') {
NSString* callingDirNS = [NSString stringWithUTF8String:callingModuleDirName.c_str()];
NSString* moduleNameNS = [NSString stringWithUTF8String:moduleName.c_str()];
fullPath =
[[callingDirNS stringByAppendingPathComponent:moduleNameNS] stringByStandardizingPath];
} else if (moduleName[0] == '~') {
// `~` is the app-root alias, so what follows it is a path relative to
// the app root whether or not the caller wrote the separator.
std::string relative = moduleName.substr(1);
size_t firstSegment = relative.find_first_not_of('/');
relative =
firstSegment == std::string::npos ? std::string() : relative.substr(firstSegment);
fullPath = [[NSString stringWithUTF8String:RuntimeConfig.ApplicationPath.c_str()]
stringByAppendingPathComponent:[NSString stringWithUTF8String:relative.c_str()]];
} else {
// Default: resolve in tns_modules (shared folder override removed)
NSString* tnsModulesPath =
[[NSString stringWithUTF8String:RuntimeConfig.ApplicationPath.c_str()]
stringByAppendingPathComponent:@"tns_modules"];
fullPath = [tnsModulesPath
stringByAppendingPathComponent:[NSString stringWithUTF8String:moduleName.c_str()]];
const char* path1 = [fullPath fileSystemRepresentation];
const char* path2 =
[[fullPath stringByAppendingPathExtension:@"js"] fileSystemRepresentation];
const char* path3 =
[[fullPath stringByAppendingPathExtension:@"mjs"] fileSystemRepresentation];
if (!tns::Exists(path1) && !tns::Exists(path2) && !tns::Exists(path3)) {
fullPath = [tnsModulesPath stringByAppendingPathComponent:@"tns-core-modules"];
fullPath = [fullPath
stringByAppendingPathComponent:[NSString stringWithUTF8String:moduleName.c_str()]];
}
}
} else {
fullPath = [NSString stringWithUTF8String:moduleName.c_str()];
}
NSString* fileNameOnly = [fullPath lastPathComponent];
NSString* pathOnly = [fullPath stringByDeletingLastPathComponent];
bool isData = false;
Local<Object> moduleObj = moduleInternal->LoadImpl(
isolate, [fileNameOnly UTF8String], [pathOnly UTF8String], isData, evaluationOptions);
if (moduleObj.IsEmpty()) {
return;
}
if (isData) {
// moduleObj is guaranteed to be non-empty here due to check above
info.GetReturnValue().Set(moduleObj);
} else {
Local<Context> context = isolate->GetCurrentContext();
Local<Value> exportsObj;
bool success =
moduleObj->Get(context, tns::ToV8String(isolate, "exports")).ToLocal(&exportsObj);
if (success) {
info.GetReturnValue().Set(exportsObj);
} else {
Log(@"Warning: Failed to get exports from module object");
}
}
} catch (NativeScriptException& ex) {
// Rethrown as-is. Wrapping it in a fresh Error erased the original's class
// and identity, so `catch (e) { e instanceof TypeError }` — and any
// reference comparison against a module's own exported error — silently
// stopped working for anything thrown through a require().
TNS_DEBUG(Esm, "[require][fail] module=%s from=%s resolved=%s: %s", moduleName.c_str(),
callingModuleDirName.c_str(),
fullPath != nil ? [fullPath UTF8String] : "<unresolved>", ex.getMessage().c_str());
ex.ReThrowToV8(isolate);
}
}
Local<Object> ModuleInternal::LoadImpl(Isolate* isolate, const std::string& moduleName,
const std::string& baseDir, bool& isData,
const ModuleEvaluationOptions& options) {
// The specifier goes into the key verbatim. Stripping its extension made
// './config.js' and './config.json' the same key, so whichever loaded first
// answered for both. Specifier spellings that differ but resolve to one file
// ('./x' and './x.js') still share a module: they meet again at the
// resolved-path lookup below, which is the identity that matters.
std::string cacheKey = baseDir + "*" + moduleName;
auto it = this->loadedModules_.find(cacheKey);
if (it != this->loadedModules_.end()) {
return it->second->Get(isolate);
}
Local<Object> moduleObj;
std::string path;
try {
path = this->ResolvePath(isolate, baseDir, moduleName);
} catch (NativeScriptException& ex) {
// Add context about the module resolution
std::string contextMsg = "Failed to resolve module: '" + moduleName + "'";
contextMsg += "\n Base directory: " + baseDir;
contextMsg += "\n Module name: " + moduleName;
contextMsg += "\n\nOriginal error:\n" + ex.getMessage();
throw NativeScriptException(isolate, contextMsg, "Error");
}
if (path.empty()) {
throw NativeScriptException(isolate, "Cannot find module '" + moduleName + "'", "Error");
}
NSString* pathStr = [NSString stringWithUTF8String:path.c_str()];
NSString* extension = [pathStr pathExtension];
if ([extension isEqualToString:@"json"]) {
isData = true;
}
auto it2 = this->loadedModules_.find(path);
if (it2 != this->loadedModules_.end()) {
return it2->second->Get(isolate);
}
if ([extension isEqualToString:@"mjs"] || [extension isEqualToString:@"js"]) {
moduleObj = this->LoadModule(isolate, path, cacheKey, options);
} else if ([extension isEqualToString:@"json"]) {
moduleObj = this->LoadData(isolate, path);
} else {
// Throw an error for unsupported file extension instead of crashing
std::string errorMsg = "Unsupported file extension: " + std::string([extension UTF8String]);
throw NativeScriptException(errorMsg);
}
return moduleObj;
}
static bool NamespaceHasOwn(Isolate* isolate, Local<Context> context, Local<Object> ns,
const char* name) {
return ns->HasOwnProperty(context, tns::ToV8String(isolate, name)).FromMaybe(false);
}
// The live compiled module behind a registry key, or empty.
static Local<Module> RegisteredModuleForPath(Isolate* isolate, const std::string& canonicalPath) {
auto* registryPtr = ModuleRegistryFor(isolate);
if (registryPtr == nullptr) {
return Local<Module>();
}
auto it = registryPtr->find(canonicalPath);
if (it == registryPtr->end()) {
return Local<Module>();
}
return it->second.Get(isolate);
}
// What `require()` of an ES module hands back, per Node's
// populateCJSExportsFromESM: an explicit `module.exports` export wins outright;
// a namespace with no default export, or one that already declares
// __esModule, passes through untouched; everything else gets the facade so
// transpiled consumers reading `_mod.__esModule ? _mod.default : _mod` find the
// default. Export names are arbitrary strings, hence the own-property probes.
static Local<Value> RequireExportsForNamespace(Isolate* isolate, Local<Context> context,
Local<Object> ns, const std::string& canonicalPath) {
TryCatch tc(isolate);
if (NamespaceHasOwn(isolate, context, ns, "module.exports")) {
Local<Value> moduleExports;
if (!ns->Get(context, tns::ToV8String(isolate, "module.exports")).ToLocal(&moduleExports)) {
throw NativeScriptException(isolate, tc,
"Cannot read the 'module.exports' export of " + canonicalPath);
}
return moduleExports;
}
bool hasDefault = NamespaceHasOwn(isolate, context, ns, "default");
bool hasEsModuleMarker = NamespaceHasOwn(isolate, context, ns, "__esModule");
if (!hasDefault || hasEsModuleMarker) {
return ns;
}
Local<Module> target = RegisteredModuleForPath(isolate, canonicalPath);
if (target.IsEmpty()) {
// The load that produced this namespace registered the module under this
// very key, so a miss means the registry and the namespace disagree —
// returning the bare namespace would drop __esModule and misroute every
// transpiled consumer downstream.
throw NativeScriptException(
"require() cannot build the exports facade for " + canonicalPath +
": the module evaluated but is absent from the registry under its canonical key");
}
Local<Module> facade;
if (!GetOrCreateRequireFacade(isolate, context, target, canonicalPath).ToLocal(&facade)) {
throw NativeScriptException("Cannot build the require() exports facade for " + canonicalPath);
}
return facade->GetModuleNamespace();
}
Local<Object> ModuleInternal::LoadModule(Isolate* isolate, const std::string& modulePath,
const std::string& cacheKey,
const ModuleEvaluationOptions& options) {
Local<Object> moduleObj = Object::New(isolate);
Local<Object> exportsObj = Object::New(isolate);
Local<Context> context = isolate->GetCurrentContext();
bool success =
moduleObj->Set(context, tns::ToV8String(isolate, "exports"), exportsObj).FromMaybe(false);
if (!success) {
Log(@"Warning: Failed to set exports property on module object");
}
const PropertyAttribute readOnlyFlags =
static_cast<PropertyAttribute>(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
Local<v8::String> fileName = tns::ToV8String(isolate, modulePath);
success =
moduleObj->DefineOwnProperty(context, tns::ToV8String(isolate, "id"), fileName, readOnlyFlags)
.FromMaybe(false);
if (!success) {
Log(@"Warning: Failed to set id property on module object");
}
std::shared_ptr<Persistent<Object>> poModuleObj =
std::make_shared<Persistent<Object>>(isolate, moduleObj);
TempModule tempModule(this, modulePath, cacheKey, poModuleObj);
// Compile/load the JavaScript/ESM source
Local<Value> scriptValue = LoadScript(isolate, modulePath, options);
if (scriptValue.IsEmpty()) {
throw NativeScriptException(isolate, "Script loading failed for " + modulePath);
}
// Check if this is an ES module
bool isESM = IsESModule(modulePath);
if (isESM) {
// For ES modules, the returned value is the namespace object
if (scriptValue.IsEmpty()) {
throw NativeScriptException(isolate, "ES module load returned empty value " + modulePath);
}
if (!scriptValue->IsObject()) {
throw NativeScriptException(isolate, "Failed to load ES module " + modulePath);
}
Local<Value> esmExports = RequireExportsForNamespace(isolate, context, scriptValue.As<Object>(),
CanonicalizeModulePath(modulePath));
bool succ =
moduleObj->Set(context, tns::ToV8String(isolate, "exports"), esmExports).FromMaybe(false);
if (!succ) {
Log(@"Warning: Failed to set exports property after module execution");
}
tempModule.SaveToCache();
return moduleObj;
}
// Check if this is the main application bundle (webpack-style IIFE)
std::string appPath = RuntimeConfig.ApplicationPath;
std::string bundlePath = appPath + "/bundle.js";
if (modulePath == bundlePath) {
// Main application bundle is a webpack-style IIFE that executes immediately
// It doesn't return a function, so we just create an empty exports object
tempModule.SaveToCache();
return moduleObj;
}
// Classic CommonJS path – expect a factory function.
if (!scriptValue->IsFunction()) {
throw NativeScriptException(isolate,
"Expected module factory to be a function for " + modulePath);
}
v8::Local<v8::Function> moduleFunc = scriptValue.As<v8::Function>();
{
TryCatch tc(isolate);
// moduleFunc = script->Run(context).ToLocalChecked().As<v8::Function>();
if (tc.HasCaught()) {
throw NativeScriptException(isolate, tc, "Error running script " + modulePath);
}
}
std::string parentDir = [[[NSString stringWithUTF8String:modulePath.c_str()]
stringByDeletingLastPathComponent] UTF8String];
// Shorten the parentDir for GetRequireFunction to avoid V8 parsing issues with long paths
std::string shortParentDir;
if (parentDir.length() >= RuntimeConfig.ApplicationPath.length() &&
parentDir.compare(0, RuntimeConfig.ApplicationPath.length(), RuntimeConfig.ApplicationPath) ==
0) {
shortParentDir = "/app" + parentDir.substr(RuntimeConfig.ApplicationPath.length());
} else {
// Fallback: use the entire path if it doesn't start with ApplicationPath
shortParentDir = parentDir;
}
// A module's own require inherits the options it was loaded under, so a
// pumping require stays pumping — with the same deadline and timeout
// behavior — all the way down its dependency tree.
Local<v8::Function> require = GetRequireFunction(isolate, shortParentDir, options);
// Use full paths for __filename and __dirname to match module.id
Local<Value> requireArgs[5]{moduleObj, exportsObj, require,
tns::ToV8String(isolate, modulePath.c_str()),
tns::ToV8String(isolate, parentDir.c_str())};
success = moduleObj->Set(context, tns::ToV8String(isolate, "require"), require).FromMaybe(false);
if (!success) {
Log(@"Warning: Failed to set require property on module object");
}
{
TryCatch tc(isolate);
Local<Value> result;
Local<Object> thiz = Object::New(isolate);
success =
moduleFunc->Call(context, thiz, sizeof(requireArgs) / sizeof(Local<Value>), requireArgs)
.ToLocal(&result);
if (!success || tc.HasCaught()) {
throw NativeScriptException(isolate, tc, "Error calling module function");
}
}
tempModule.SaveToCache();
return moduleObj;
}
Local<Object> ModuleInternal::LoadData(Isolate* isolate, const std::string& modulePath) {
Local<Object> json;
std::string jsonData = tns::ReadText(modulePath);
Local<v8::String> jsonStr = tns::ToV8String(isolate, jsonData);
Local<Context> context = isolate->GetCurrentContext();
TryCatch tc(isolate);
MaybeLocal<Value> maybeValue = JSON::Parse(context, jsonStr);
if (maybeValue.IsEmpty() || tc.HasCaught()) {
std::string errMsg = "Cannot parse JSON file " + modulePath;
throw NativeScriptException(isolate, tc, errMsg);
}
Local<Value> value = maybeValue.ToLocalChecked();
if (!value->IsObject()) {
std::string errMsg = "JSON is not valid, file=" + modulePath;
throw NativeScriptException(errMsg);
}
json = value.As<Object>();
this->loadedModules_.emplace(modulePath, std::make_shared<Persistent<Object>>(isolate, json));
return json;
}
Local<Value> ModuleInternal::LoadScript(Isolate* isolate, const std::string& path,
const ModuleEvaluationOptions& options) {
std::string canonicalPath = NormalizePath(path);
if (IsESModule(canonicalPath)) {
// Treat all .mjs files as standard ES modules. require()'s default route
// cannot wait: an async graph is refused rather than pumped.
return ModuleInternal::LoadESModule(isolate, canonicalPath, options);
}
Local<Script> script = ModuleInternal::LoadClassicScript(isolate, canonicalPath);
if (script.IsEmpty()) {
throw NativeScriptException(isolate, "Classic script compilation failed for " + canonicalPath);
}
// run it and return the value with proper exception handling
Local<Context> context = isolate->GetCurrentContext();
TryCatch tc(isolate);
Local<Value> result;
if (!script->Run(context).ToLocal(&result)) {
if (RuntimeConfig.IsDebug) {
Log(@"***** JavaScript exception occurred *****");
Log(@"Error executing script: %s", canonicalPath.c_str());
if (tc.HasCaught()) {
tns::LogError(isolate, tc);
}
}
if (tc.HasCaught()) {
throw NativeScriptException(isolate, tc, "Cannot execute script " + canonicalPath);
}
throw NativeScriptException(isolate, "Script execution failed for " + canonicalPath);
}
return result;
}
Local<Script> ModuleInternal::LoadClassicScript(Isolate* isolate, const std::string& path) {
std::string canonicalPath = NormalizePath(path);
// Ensure the resolved path maps to an actual regular file before attempting
// to read/compile it. This prevents `ReadModule` from aborting the process
// when given a directory or non-existent path.
struct stat st;
if (stat(canonicalPath.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) {
throw NativeScriptException("Cannot find module " + canonicalPath);
}
auto context = isolate->GetCurrentContext();
// build URL
std::string base = ReplaceAll(canonicalPath, RuntimeConfig.BaseDir, "");
std::string url = "file://" + base;
// wrap & cache lookup
Local<v8::String> sourceText = ModuleInternal::WrapModuleContent(isolate, canonicalPath);
auto* cacheData = ModuleInternal::LoadScriptCache(canonicalPath, ScriptCacheKind::kClassicScript);
// note: is_module=false here
Local<v8::String> urlString;
if (!v8::String::NewFromUtf8(isolate, url.c_str(), NewStringType::kNormal).ToLocal(&urlString)) {
throw NativeScriptException(isolate, "Failed to create URL string for script " + canonicalPath);
}
ScriptOrigin origin(urlString,
0, // line offset
0, // column offset
false, // shared_cross_origin
-1, // script_id
Local<Value>(),
false, // is_opaque
false, // is_wasm
false // is_module
);
ScriptCompiler::Source source(sourceText, origin, cacheData);
auto opts = cacheData ? ScriptCompiler::kConsumeCodeCache : ScriptCompiler::kNoCompileOptions;
TryCatch tc(isolate);
Local<Script> script;