Repository navigation
Expand file tree
/
Copy pathModuleInternal.cpp
More file actions
1722 lines (1519 loc) · 74 KB
/
Copy pathModuleInternal.cpp
File metadata and controls
1722 lines (1519 loc) · 74 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
/*
* Module.cpp
*
* Created on: Jun 24, 2015
* Author: gatanasov
*/
#include "ModuleInternal.h"
#include "ModuleInternalCallbacks.h"
#include "BuiltinLoader.h"
#include "File.h"
#include "HttpLoader.h"
#include "JniLocalRef.h"
#include "ArgConverter.h"
#include "NativeScriptAssert.h"
#include "Constants.h"
#include "CrashBreadcrumbs.h"
#include "EventLoop.h"
#include "NativeScriptException.h"
#include "NsBuiltinModules.h"
#include "napi/NapiModules.h"
#include "Util.h"
#include "SimpleProfiler.h"
#include "CallbackHandlers.h"
#include "ManualInstrumentation.h"
#include "Runtime.h"
#include "TraceLog.h"
#include <sstream>
#include <libgen.h>
#include <dlfcn.h>
#include <sys/stat.h>
#include <time.h>
#include <utime.h>
#include <unistd.h>
#include <chrono>
#include <cmath>
#include <cstring>
using namespace v8;
using namespace std;
using namespace tns;
bool ModuleInternal::IsHttpModulePath(const std::string& path) {
const std::string normalized = NormalizeHttpModuleUrl(path);
return normalized.rfind("http://", 0) == 0 || normalized.rfind("https://", 0) == 0;
}
// What a rejected evaluation promise says about itself.
struct RejectionDetail {
// The reason's own text: an Error's `message`, or the reason stringified.
std::string message;
// A bounded rendering of the reason's `stack`, filled only when asked for.
std::string stackPreview;
};
// `detail`, when non-null, receives the reason's parts unjoined; reading the
// stack costs a property get plus a copy, so callers pass null unless a trace
// is actually going to be emitted.
static std::string PromiseRejectionMessage(Isolate* isolate, Local<Promise> promise,
const std::string& path,
RejectionDetail* detail = nullptr) {
std::string errorMessage = "Module evaluation promise rejected: " + path;
TryCatch tc(isolate);
Local<Value> reason = promise->Result();
if (reason.IsEmpty()) {
return errorMessage;
}
std::string reasonText;
Local<Context> context = isolate->GetCurrentContext();
if (reason->IsObject()) {
Local<Object> errorObj = reason.As<Object>();
Local<Value> messageVal;
if (errorObj->Get(context, ArgConverter::ConvertToV8String(isolate, "message"))
.ToLocal(&messageVal) &&
messageVal->IsString()) {
v8::String::Utf8Value messageUtf8(isolate, messageVal);
if (*messageUtf8) {
reasonText.assign(*messageUtf8);
}
}
Local<Value> stackVal;
if (detail != nullptr &&
errorObj->Get(context, ArgConverter::ConvertToV8String(isolate, "stack"))
.ToLocal(&stackVal) &&
stackVal->IsString()) {
v8::String::Utf8Value stackUtf8(isolate, stackVal);
if (*stackUtf8) {
std::string stack(*stackUtf8);
detail->stackPreview = stack.size() > 240 ? stack.substr(0, 240) + "…" : stack;
}
}
} else {
auto maybeReasonStr = reason->ToString(context);
if (!maybeReasonStr.IsEmpty()) {
v8::String::Utf8Value reasonUtf8(isolate, maybeReasonStr.ToLocalChecked());
if (*reasonUtf8) {
reasonText.assign(*reasonUtf8);
}
}
}
if (!reasonText.empty()) {
errorMessage.append(" — ");
errorMessage.append(reasonText);
}
if (detail != nullptr) {
detail->message = std::move(reasonText);
}
if (tc.HasCaught()) {
tc.Reset();
}
return errorMessage;
}
// 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 ModuleEvaluationOptions BootEntryEvaluationOptions(bool isHttpModule);
static ModuleEvaluationOptions RequireEvaluationOptions(ModuleEvaluationPolicy policy);
// Helper function to check if a file path is an ES module (.mjs) but not a source map (.mjs.map)
bool ModuleInternal::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);
}
ModuleInternal::ModuleInternal()
: m_isolate(nullptr), m_requireFunction(nullptr), m_requireFactoryFunction(nullptr) {
}
ModuleInternal::~ModuleInternal() {
delete this->m_requireFunction;
delete this->m_requireFactoryFunction;
for (const auto& pair: this->m_requireCache) {
delete pair.second;
}
this->m_requireCache.clear();
/*
* Runs after Isolate::Dispose, so the handles are freed with the isolate and
* only the wrappers are deleted -- v8::Persistent does not reset in its
* destructor, which is what makes that safe here.
*
* Deduplicated by pointer: a module is cached under both its resolved path
* and its cache key, and both entries hold the same Persistent.
*/
robin_hood::unordered_set<v8::Persistent<v8::Object>*> freed;
for (const auto& pair: this->m_loadedModules) {
if (freed.insert(pair.second.obj).second) {
delete pair.second.obj;
}
}
this->m_loadedModules.clear();
}
void ModuleInternal::Init(Isolate* isolate, const string& baseDir) {
JEnv env;
if (MODULE_CLASS == nullptr) {
MODULE_CLASS = env.FindClass("com/tns/Module");
NS_CHECK(MODULE_CLASS != nullptr);
RESOLVE_PATH_METHOD_ID = env.GetStaticMethodID(MODULE_CLASS, "resolvePath", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
NS_CHECK(RESOLVE_PATH_METHOD_ID != nullptr);
GET_APPLICATION_FILES_PATH_METHOD_ID = env.GetStaticMethodID(MODULE_CLASS, "getApplicationFilesPath", "()Ljava/lang/String;");
NS_CHECK(GET_APPLICATION_FILES_PATH_METHOD_ID != nullptr);
}
m_isolate = isolate;
auto context = isolate->GetCurrentContext();
auto global = context->Global();
Local<Value> result;
auto success = BuiltinLoader::RunBuiltin(context, BuiltinId::kRequireFactory).ToLocal(&result);
NS_CHECK(success && result->IsFunction());
auto requireFactoryFunction = result.As<Function>();
m_requireFactoryFunction = new Persistent<Function>(isolate, requireFactoryFunction);
auto external = External::New(isolate, this, v8::kExternalPointerTypeTagDefault);
// Only the require factory receives this one, so the evaluation options it
// forwards were validated at mint time.
auto requireFuncTemplate = FunctionTemplate::New(isolate, RequireCallback, external);
auto requireFunc = requireFuncTemplate->GetFunction(context).ToLocalChecked();
m_requireFunction = new Persistent<Function>(isolate, requireFunc);
// App code can reach this one, so it reads nothing but the specifier and the
// calling directory: a caller must not be able to hand itself a pumping
// policy, an unbounded deadline or a looper-slicing require.
auto publicRequireTemplate = FunctionTemplate::New(isolate, RequirePublicCallback, external);
global->Set(context, ArgConverter::ConvertToV8String(isolate, "__nativeRequire"),
publicRequireTemplate->GetFunction(context).ToLocalChecked());
// terminate() cannot reach this isolate yet - a worker's is published to its
// parent only once the runtime is up - so this mint is checked as hard as
// the factory's own load above.
Local<Function> globalRequire;
const bool minted = GetRequireFunction(
isolate, baseDir.empty() ? Constants::APP_ROOT_FOLDER_PATH : baseDir,
RequireEvaluationOptions(ModuleEvaluationPolicy::kSyncStrict)).ToLocal(&globalRequire);
NS_CHECK(minted);
global->Set(context, ArgConverter::ConvertToV8String(isolate, "require"), globalRequire);
}
// How an entry module's graph settles. For local modules the bound is a yield,
// not a timeout: the default pump runs only nestable V8 tasks while these JS
// frames are on the stack, so a TLA parked on anything else can never settle
// in-place — give it one short window, then return and let the real event
// loop (or the draining boot backstop) finish it after the turn. HTTP entries
// must settle in-pump — the dev client needs the rejection reason
// synchronously — so they get the full deadline and the looper-equivalent
// drain, the same split iOS makes with its runloop slice.
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. By default the
// pump runs nestable v8 tasks and microtasks only, matching iOS: running JS
// timers or loop posts in the middle of an arbitrary require is opt-in
// (pumpRunLoop), because those callbacks execute underneath the require's 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;
}
// The require cache is keyed by directory AND by the options the require was
// minted with: a pumping require for a directory must never be served from a
// strict require cached for the same directory, in either direction.
static std::string RequireCacheKey(const std::string& dirName,
const ModuleEvaluationOptions& options) {
std::string key = dirName;
key += '\x1f';
key += std::to_string(static_cast<int>(options.policy));
key += '\x1f';
key += std::to_string(options.deadlineSeconds);
key += '\x1f';
key += (options.timeoutBehavior == ModuleEvaluationOptions::TimeoutBehavior::kThrow) ? '1' : '0';
key += options.pumpRunLoop ? '1' : '0';
return key;
}
MaybeLocal<Function> ModuleInternal::GetRequireFunction(Isolate* isolate, const string& dirName,
const ModuleEvaluationOptions& options) {
TNSPERF();
Local<Function> requireFunc;
const std::string cacheKey = RequireCacheKey(dirName, options);
auto itFound = m_requireCache.find(cacheKey);
if (itFound != m_requireCache.end()) {
requireFunc = Local<Function>::New(isolate, *itFound->second);
} else {
auto requireFuncFactory = Local<Function>::New(isolate, *m_requireFactoryFunction);
auto context = isolate->GetCurrentContext();
auto requireInternalFunc = Local<Function>::New(isolate, *m_requireFunction);
Local<Value> args[6] {
requireInternalFunc,
ArgConverter::ConvertToV8String(isolate, dirName),
Integer::New(isolate, static_cast<int>(options.policy)),
Number::New(isolate, options.deadlineSeconds),
v8::Boolean::New(isolate, options.timeoutBehavior ==
ModuleEvaluationOptions::TimeoutBehavior::kThrow),
v8::Boolean::New(isolate, options.pumpRunLoop)
};
Local<Value> result;
auto thiz = Object::New(isolate);
// The factory cannot throw, but entering it is an interrupt check: a
// terminate() that reached this isolate since its last one surfaces
// here and stays pending for the caller to unwind with.
if (!requireFuncFactory->Call(context, thiz, 6, args).ToLocal(&result)) {
return MaybeLocal<Function>();
}
NS_CHECK(result->IsFunction());
requireFunc = result.As<Function>();
auto poFunc = new Persistent<Function>(isolate, requireFunc);
m_requireCache.emplace(cacheKey, poFunc);
}
return requireFunc;
}
void ModuleInternal::CreateRequireCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.Length() < 1 || !args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(ArgConverter::ConvertToV8String(
isolate, "createRequire expects a base directory string")));
return;
}
Runtime* runtime = Runtime::TryGetRuntime(isolate);
ModuleInternal* moduleInternal = runtime != nullptr ? runtime->GetModuleInternal() : nullptr;
if (moduleInternal == nullptr) {
isolate->ThrowException(Exception::Error(ArgConverter::ConvertToV8String(
isolate, "createRequire is unavailable: this isolate has no module loader")));
return;
}
string dirName = ArgConverter::ConvertToString(args[0].As<String>());
const bool pumping = args.Length() > 1 && args[1]->BooleanValue(isolate);
ModuleEvaluationOptions options = RequireEvaluationOptions(
pumping ? ModuleEvaluationPolicy::kSyncPumping : ModuleEvaluationPolicy::kSyncStrict);
// ns-module.js has already validated these and passes undefined for anything
// the caller left out, so each present value simply overrides its default.
if (args.Length() > 2 && args[2]->IsNumber()) {
double deadlineSeconds = args[2].As<Number>()->Value();
// A NaN or infinite window makes the pump's deadline arithmetic
// undefined, and a non-positive one is no window at all.
if (std::isfinite(deadlineSeconds) && deadlineSeconds > 0.0) {
options.deadlineSeconds = deadlineSeconds;
}
}
if (args.Length() > 3 && args[3]->IsBoolean()) {
options.timeoutBehavior = args[3]->BooleanValue(isolate)
? ModuleEvaluationOptions::TimeoutBehavior::kThrow
: ModuleEvaluationOptions::TimeoutBehavior::kReturnPending;
}
if (args.Length() > 4 && args[4]->IsBoolean()) {
options.pumpRunLoop = args[4]->BooleanValue(isolate);
}
Local<Function> require;
if (moduleInternal->GetRequireFunction(isolate, dirName, options).ToLocal(&require)) {
args.GetReturnValue().Set(require);
}
}
bool ModuleInternal::InstallCreateRequireBinding(Local<Context> context, Local<Object> binding) {
Isolate* isolate = v8::Isolate::GetCurrent();
Local<Function> fn;
if (!Function::New(context, ModuleInternal::CreateRequireCallback).ToLocal(&fn)) {
return false;
}
fn->SetName(ArgConverter::ConvertToV8String(isolate, "createRequire"));
return binding->CreateDataProperty(context,
ArgConverter::ConvertToV8String(isolate, "createRequire"),
fn)
.FromMaybe(false);
}
// 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 = ArgConverter::ToString(isolate, value.As<v8::Function>()->GetName());
return name.empty() ? "an instance of Function" : "function " + name;
}
if (value->IsObject()) {
std::string ctorName = ArgConverter::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"
: ArgConverter::ToString(isolate, value);
} else if (value->IsBigInt()) {
typeName = "bigint";
rendered = ArgConverter::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()
: ArgConverter::ToString(isolate, description)) +
")";
} else {
rendered = ArgConverter::ToString(isolate, value);
}
if (rendered.size() > 28) {
rendered = rendered.substr(0, 25) + "...";
}
return "type " + std::string(typeName) + " (" + rendered + ")";
}
void ModuleInternal::DispatchRequire(const v8::FunctionCallbackInfo<v8::Value>& args,
bool honorEvaluationOptions) {
auto isolate = args.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 (args.Length() < 1 || !args[0]->IsString()) {
Local<Value> received = args.Length() < 1 ? Local<Value>() : args[0];
isolate->ThrowException(Exception::TypeError(ArgConverter::ConvertToV8String(
isolate, "The \"id\" argument must be of type string. Received " +
DescribeValueForTypeError(isolate, received))));
return;
}
try {
auto thiz = static_cast<ModuleInternal*>(args.Data().As<External>()->Value(v8::kExternalPointerTypeTagDefault));
thiz->RequireCallbackImpl(args, honorEvaluationOptions);
} catch (NativeScriptException& e) {
e.ReThrowToV8();
} catch (std::exception e) {
stringstream ss;
ss << "Error: c++ exception: " << e.what() << endl;
NativeScriptException nsEx(ss.str());
nsEx.ReThrowToV8();
} catch (...) {
NativeScriptException nsEx(std::string("Error: c++ exception!"));
nsEx.ReThrowToV8();
}
}
void ModuleInternal::RequireCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
DispatchRequire(args, true /* honorEvaluationOptions */);
}
void ModuleInternal::RequirePublicCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
DispatchRequire(args, false /* honorEvaluationOptions */);
}
void ModuleInternal::RequireCallbackImpl(const v8::FunctionCallbackInfo<v8::Value>& args,
bool honorEvaluationOptions) {
auto isolate = args.GetIsolate();
if (args.Length() < 2) {
throw NativeScriptException(string("require should be called with at least two parameters"));
}
if (!args[0]->IsString()) {
throw NativeScriptException(string("require's first parameter should be string"));
}
if (!args[1]->IsString()) {
throw NativeScriptException(string("require's second parameter should be string"));
}
string moduleName = ArgConverter::ConvertToString(args[0].As<String>());
// 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.
if (NsBuiltinModules::IsBuiltinScheme(moduleName)) {
auto context = isolate->GetCurrentContext();
Local<Object> exports;
if (NsBuiltinModules::GetExports(context, moduleName).ToLocal(&exports)) {
args.GetReturnValue().Set(exports);
} else if (!NsBuiltinModules::IsRegistered(moduleName)) {
isolate->ThrowException(Exception::Error(ArgConverter::ConvertToV8String(
isolate, NsBuiltinModules::NotFoundMessage(moduleName))));
}
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(moduleName) && NapiModules::IsRegistered(moduleName)) {
auto context = isolate->GetCurrentContext();
Local<Object> exports;
if (NapiModules::GetExports(context, moduleName).ToLocal(&exports)) {
args.GetReturnValue().Set(exports);
} else if (!isolate->HasPendingException()) {
isolate->ThrowException(Exception::Error(ArgConverter::ConvertToV8String(
isolate, "Node-API module '" + moduleName + "' failed to initialize")));
}
return;
}
// URL-based modules must be loaded via dynamic import().
if (moduleName.rfind("http://", 0) == 0 || moduleName.rfind("https://", 0) == 0) {
throw NativeScriptException("NativeScript: require() of URL module is not supported: " +
moduleName + ". Use dynamic import() instead.");
}
tns::instrumentation::Frame frame("RequireCallback " + moduleName);
string callingModuleDirName = ArgConverter::ConvertToString(args[1].As<String>());
auto isData = false;
ModuleEvaluationOptions evaluationOptions =
RequireEvaluationOptions(ModuleEvaluationPolicy::kSyncStrict);
if (honorEvaluationOptions) {
// 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 (args.Length() > 2 && args[2]->IsInt32() &&
args[2].As<Int32>()->Value() ==
static_cast<int>(ModuleEvaluationPolicy::kSyncPumping)) {
policy = ModuleEvaluationPolicy::kSyncPumping;
}
evaluationOptions = RequireEvaluationOptions(policy);
if (args.Length() > 3 && args[3]->IsNumber()) {
double deadlineSeconds = args[3].As<Number>()->Value();
// A NaN or infinite window makes the pump's deadline arithmetic
// undefined, and a non-positive one is no window at all.
if (std::isfinite(deadlineSeconds) && deadlineSeconds > 0.0) {
evaluationOptions.deadlineSeconds = deadlineSeconds;
}
}
if (args.Length() > 4 && args[4]->IsBoolean()) {
evaluationOptions.timeoutBehavior =
args[4]->BooleanValue(isolate)
? ModuleEvaluationOptions::TimeoutBehavior::kThrow
: ModuleEvaluationOptions::TimeoutBehavior::kReturnPending;
}
if (args.Length() > 5 && args[5]->IsBoolean()) {
evaluationOptions.pumpRunLoop = args[5]->BooleanValue(isolate);
}
}
auto moduleObj = LoadImpl(isolate, moduleName, callingModuleDirName, isData, evaluationOptions);
if (isData) {
NS_DCHECK(!moduleObj.IsEmpty());
args.GetReturnValue().Set(moduleObj);
} else {
auto context = isolate->GetCurrentContext();
Local<Value> exportsVal;
moduleObj->Get(context, ArgConverter::ConvertToV8String(isolate, "exports")).ToLocal(&exportsVal);
NS_DCHECK(!exportsVal.IsEmpty());
auto exportsObj = exportsVal.As<Object>();
args.GetReturnValue().Set(exportsObj);
}
}
void ModuleInternal::RequireNativeCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
TNSPERF();
auto ext = args.Data().As<External>();
auto funcPtr = reinterpret_cast<FunctionCallback>(ext->Value(v8::kExternalPointerTypeTagDefault));
funcPtr(args);
}
void ModuleInternal::Load(Local<Context> context, const string& path) {
TNSPERF();
auto isolate = m_isolate;
// The ES module branch compiles and links against
// isolate->GetCurrentContext(); a caller that enters the isolate through a
// fresh Isolate::Scope has no current context, and CompileModule would
// dereference a null native context. The require branch never needed this
// because Function::Call enters the context it is handed.
Context::Scope context_scope(context);
const bool isHttpModule = IsHttpModulePath(path);
if (isHttpModule || IsESModule(path)) {
if (isHttpModule) {
TNS_DEBUG(Esm, "run-module http-esm begin %s", NormalizeHttpModuleUrl(path).c_str());
}
// The entry runs before this thread's event loop does, so its graph can
// only make progress from the pump inside LoadESModule.
LoadESModule(isolate, path, BootEntryEvaluationOptions(isHttpModule));
if (isHttpModule) {
TNS_DEBUG(Esm, "run-module http-esm ok %s", NormalizeHttpModuleUrl(path).c_str());
}
return;
}
auto globalObject = context->Global();
auto require = globalObject->Get(context, ArgConverter::ConvertToV8String(isolate, "require")).ToLocalChecked().As<Function>();
Local<Value> args[] = { ArgConverter::ConvertToV8String(isolate, path) };
// A failed entry must throw through this boundary in every build — the
// caller (boot, or a worker's onerror routing) owns the report, and the
// boot backstop must never pump with an exception pending on the isolate.
TryCatch tc(isolate);
Local<Value> result;
const bool ok = require->Call(context, globalObject, 1, args).ToLocal(&result);
if (!ok || tc.HasCaught()) {
throw NativeScriptException(tc, "require() failed for module " + path);
}
}
void ModuleInternal::LoadWorker(Local<Context> context, const string& path) {
TNSPERF();
auto isolate = m_isolate;
TryCatch tc(isolate);
try {
Load(context, path);
} catch (NativeScriptException& e) {
e.ReThrowToV8();
}
if (tc.HasCaught()) {
// This will handle any errors that occur when first loading a script (new worker)
// exceptions include: syntax errors, throw statements, access of properties of undefined objects
// Check if `onerror` handle is implemented
// Web behaviour - if onerror handle comes before exception throw - execute it, else - bubble up to main's worker object
CallbackHandlers::CallWorkerScopeOnErrorHandle(isolate, tc);
}
}
std::string ModuleInternal::CheckFileExists(Isolate* isolate, const std::string& path, const std::string& baseDir) {
JEnv env;
JniLocalRef jsModulename(env.NewStringUTF(path.c_str()));
JniLocalRef jsBaseDir(env.NewStringUTF(baseDir.c_str()));
// Throws a NativeScriptException (through JEnv's pending-exception check)
// when nothing resolves, so the conversion below only ever sees a hit.
JniLocalRef jsModulePath(env.CallStaticObjectMethod(MODULE_CLASS, RESOLVE_PATH_METHOD_ID,
(jstring) jsModulename,
(jstring) jsBaseDir));
return ArgConverter::jstringToString((jstring) jsModulePath);
}
// The trailing extension without its dot, or an empty string when the last
// segment has none. A leading dot names a hidden file, not an extension.
static std::string PathExtension(const std::string& path) {
size_t dot = path.find_last_of('.');
if (dot == std::string::npos || dot + 1 >= path.size()) {
return std::string();
}
size_t slash = path.find_last_of('/');
if (slash != std::string::npos && (dot < slash || dot == slash + 1)) {
return std::string();
}
return path.substr(dot + 1);
}
Local<Object> ModuleInternal::LoadImpl(Isolate* isolate, const string& moduleName,
const string& baseDir, bool& isData,
const ModuleEvaluationOptions& options) {
auto pathKind = GetModulePathKind(moduleName);
auto cachePathKey = (pathKind == ModulePathKind::Global) ? moduleName : (baseDir + "*" + moduleName);
Local<Object> result;
DEBUG_WRITE(">>LoadImpl cachePathKey=%s", cachePathKey.c_str());
auto it = m_loadedModules.find(cachePathKey);
if (it == m_loadedModules.end()) {
std::string path;
// Search App System libs
std::string sys_lib("system_lib://");
if (moduleName.rfind(sys_lib, 0) == 0) {
auto pos = moduleName.find(sys_lib);
path = std::string(moduleName);
path.replace(pos, sys_lib.length(), "");
} else {
// Handle tilde path resolution before calling Java path resolution
std::string resolvedModuleName = moduleName;
if (!moduleName.empty() && moduleName[0] == '~') {
// Convert ~/path to ApplicationPath/path
std::string tail = moduleName.size() >= 2 && moduleName[1] == '/' ? moduleName.substr(2) : moduleName.substr(1);
resolvedModuleName = Constants::APP_ROOT_FOLDER_PATH + "/" + tail;
// For .mjs files with tilde paths, use resolved path directly
if (Util::EndsWith(resolvedModuleName, ".mjs")) {
path = resolvedModuleName;
} else {
// For non-.mjs files, still use Java resolution with the resolved name
JEnv env;
JniLocalRef jsModulename(env.NewStringUTF(resolvedModuleName.c_str()));
JniLocalRef jsBaseDir(env.NewStringUTF(baseDir.c_str()));
JniLocalRef jsModulePath(
env.CallStaticObjectMethod(MODULE_CLASS, RESOLVE_PATH_METHOD_ID,
(jstring) jsModulename, (jstring) jsBaseDir));
path = ArgConverter::jstringToString((jstring) jsModulePath);
}
} else {
JEnv env;
JniLocalRef jsModulename(env.NewStringUTF(moduleName.c_str()));
JniLocalRef jsBaseDir(env.NewStringUTF(baseDir.c_str()));
JniLocalRef jsModulePath(
env.CallStaticObjectMethod(MODULE_CLASS, RESOLVE_PATH_METHOD_ID,
(jstring) jsModulename, (jstring) jsBaseDir));
path = ArgConverter::jstringToString((jstring) jsModulePath);
}
}
auto it2 = m_loadedModules.find(path);
if (it2 == m_loadedModules.end()) {
if (Util::EndsWith(path, ".js") || Util::EndsWith(path, ".mjs") || Util::EndsWith(path, ".so")) {
isData = false;
result = LoadModule(isolate, path, cachePathKey, options);
} else if (Util::EndsWith(path, ".json")) {
isData = true;
result = LoadData(isolate, path);
} else {
string errMsg = "Unsupported file extension: " + PathExtension(path);
throw NativeScriptException(errMsg);
}
} else {
auto& cacheEntry = it2->second;
isData = cacheEntry.isData;
result = Local<Object>::New(isolate, *cacheEntry.obj);
}
} else {
auto& cacheEntry = it->second;
isData = cacheEntry.isData;
result = Local<Object>::New(isolate, *cacheEntry.obj);
}
return result;
}
static bool NamespaceHasOwn(Isolate* isolate, Local<Context> context, Local<Object> ns,
const char* name) {
return ns->HasOwnProperty(context, ArgConverter::ConvertToV8String(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, ArgConverter::ConvertToV8String(isolate, "module.exports"))
.ToLocal(&moduleExports)) {
throw NativeScriptException(
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 string& modulePath,
const string& moduleCacheKey,
const ModuleEvaluationOptions& options) {
string frameName("LoadModule " + modulePath);
tns::instrumentation::Frame frame(frameName);
CrashBreadcrumbs::ModuleScope moduleBreadcrumb(modulePath.c_str());
Local<Object> result;
auto context = isolate->GetCurrentContext();
auto moduleObj = Object::New(isolate);
auto exportsObj = Object::New(isolate);
auto exportsPropName = ArgConverter::ConvertToV8String(isolate, "exports");
moduleObj->Set(context, exportsPropName, exportsObj);
auto fullRequiredModulePath = ArgConverter::ConvertToV8String(isolate, modulePath);
moduleObj->Set(context, ArgConverter::ConvertToV8String(isolate, "filename"), fullRequiredModulePath);
auto poModuleObj = new Persistent<Object>(isolate, moduleObj);
TempModule tempModule(this, modulePath, moduleCacheKey, poModuleObj);
TryCatch tc(isolate);
// Check if this is an ES module (.mjs)
if (Util::EndsWith(modulePath, ".mjs")) {
// require()'s route into the ES module system, which cannot wait: an
// async graph is refused rather than pumped.
Local<Value> moduleNamespace = LoadESModule(isolate, modulePath, options);
// A load that produced no namespace produced no module either — an
// isolate torn down mid-load, or a graph that never settled. Caching the
// empty exports object would intern that failure for the process.
if (moduleNamespace.IsEmpty()) {
throw NativeScriptException("ES module load returned empty value " + modulePath);
}
if (!moduleNamespace->IsObject()) {
throw NativeScriptException("Failed to load ES module " + modulePath);
}
// `module.exports` is what Node's populateCJSExportsFromESM produces for
// this namespace, not the namespace itself.
Local<Value> esmExports = RequireExportsForNamespace(isolate, context,
moduleNamespace.As<Object>(),
CanonicalizeRegistryKey(modulePath));
moduleObj->Set(context, ArgConverter::ConvertToV8String(isolate, "exports"), esmExports);
tempModule.SaveToCache();
result = moduleObj;
return result;
}
Local<Function> moduleFunc;
if (Util::EndsWith(modulePath, ".js")) {
auto script = LoadScript(isolate, modulePath, fullRequiredModulePath);
Local<Value> moduleFuncValue;
if (!script->Run(context).ToLocal(&moduleFuncValue) || tc.HasCaught()) {
throw NativeScriptException(tc, "Error running script " + modulePath);
}
moduleFunc = moduleFuncValue.As<Function>();
} else if (Util::EndsWith(modulePath, ".so")) {
// Registrations from libraries this loader did not dlopen (statically
// linked addons whose constructors ran at app start) must not be
// attributed to whatever `.so` happens to load next.
NapiModules::ClaimPendingModule();
auto handle = dlopen(modulePath.c_str(), RTLD_LAZY);
if (handle == nullptr) {
auto error = dlerror();
string errMsg(error != nullptr ? error : "dlopen failed for " + modulePath);
throw NativeScriptException(errMsg);
}
// A library whose constructors registered a Node-API module is a
// Node-API addon: its exports come from the addon registry (Node's
// dlopen consumes `modpending` the same way). A library carrying the
// NAPI_MODULE / node-addon-api registration symbol instead is
// initialized through it — this is also the path a *re*-dlopen of an
// already-loaded addon takes, since constructors only run on first
// load. NSMain remains the protocol for plain native modules.
string napiModuleName = NapiModules::ClaimPendingModule();
void* napiInitSymbol = napiModuleName.empty()
? dlsym(handle, "napi_register_module_v1")
: nullptr;
if (!napiModuleName.empty() || napiInitSymbol != nullptr) {
Local<Object> napiExports;
bool initialized = napiModuleName.empty()
? NapiModules::InitAddonFromSymbol(context, napiInitSymbol, modulePath).ToLocal(&napiExports)
: NapiModules::GetExports(context, napiModuleName).ToLocal(&napiExports);
if (!initialized || tc.HasCaught()) {
throw NativeScriptException(tc, "Error initializing Node-API module " +
(napiModuleName.empty() ? modulePath : napiModuleName));
}
moduleObj->Set(context, exportsPropName, napiExports);
tempModule.SaveToCache();
result = moduleObj;
return result;
}
auto func = dlsym(handle, "NSMain");
if (func == nullptr) {
string errMsg("Cannot find 'NSMain' in " + modulePath);
throw NativeScriptException(errMsg);
}
auto extFunc = External::New(isolate, func, v8::kExternalPointerTypeTagDefault);
auto ft = FunctionTemplate::New(isolate, RequireNativeCallback, extFunc);
auto maybeFunc = ft->GetFunction(context);
if (maybeFunc.IsEmpty() || tc.HasCaught()) {
throw NativeScriptException(tc, "Cannot create native module function callback");
}
moduleFunc = maybeFunc.ToLocalChecked();
} else {
string errMsg = "Unsupported file extension: " + PathExtension(modulePath);
throw NativeScriptException(errMsg);
}
SET_PROFILER_FRAME();
auto fileName = ArgConverter::ConvertToV8String(isolate, modulePath);
// dirname() semantics without its fixed-size copy: module paths can
// exceed any stack buffer (PATH_MAX is 4096 and node_modules nests).
const size_t lastSlash = modulePath.find_last_of('/');
string strDirName = lastSlash == string::npos ? "."
: lastSlash == 0 ? "/"
: modulePath.substr(0, lastSlash);
auto dirName = ArgConverter::ConvertToV8String(isolate, strDirName);
// A module's own require inherits the options it was loaded under, so a
// pumping require's whole dependency tree keeps pumping.
Local<Function> require;
if (!GetRequireFunction(isolate, strDirName, options).ToLocal(&require)) {
throw NativeScriptException(tc, "Cannot create the require function for " + modulePath);
}
Local<Value> requireArgs[5] {
moduleObj, exportsObj, require, fileName, dirName
};
moduleObj->Set(context, ArgConverter::ConvertToV8String(isolate, "require"), require);
auto moduleIdProp = ArgConverter::ConvertToV8String(isolate, "id");
const auto readOnlyFlags = static_cast<PropertyAttribute>(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
Maybe<bool> success = moduleObj->DefineOwnProperty(isolate->GetCurrentContext(), moduleIdProp, fileName, readOnlyFlags);
if (success.IsNothing()) {
throw NativeScriptException(string("Couldn't execute method 'DefineOwnProperty' on 'moduleObj' in 'Module::LoadModule'."));
}
auto thiz = Object::New(isolate);
auto extendsName = ArgConverter::ConvertToV8String(isolate, "__extends");
Local<Value> extendsFunc;
if (!context->Global()->Get(context, extendsName).ToLocal(&extendsFunc) || tc.HasCaught()) {
throw NativeScriptException(tc, "Cannot read '__extends' while loading " + modulePath);
}
thiz->Set(context, extendsName, extendsFunc);
moduleFunc->Call(context, thiz, sizeof(requireArgs) / sizeof(Local<Value> ), requireArgs);
if (tc.HasCaught()) {
throw NativeScriptException(tc, "Error calling module function ");
}
tempModule.SaveToCache();
result = moduleObj;
return result;
}
Local<Script> ModuleInternal::LoadScript(Isolate* isolate, const string& path, const Local<String>& fullRequiredModulePath) {
string frameName("LoadScript " + path);
tns::instrumentation::Frame frame(frameName);
Local<Script> script;
TryCatch tc(isolate);
auto scriptText = ModuleInternal::WrapModuleContent(path);
DEBUG_WRITE("Compiling script (module %s)", path.c_str());
//
auto cacheData = TryLoadScriptCache(path, ScriptCacheKind::Classic);
auto fullRequiredModulePathWithSchema = ArgConverter::ConvertToV8String(isolate, "file://" + path);
ScriptOrigin origin(fullRequiredModulePathWithSchema);
ScriptCompiler::Source source(scriptText, origin, cacheData);
ScriptCompiler::CompileOptions option = ScriptCompiler::kNoCompileOptions;
if (cacheData != nullptr) {
tns::instrumentation::Frame frame("Compile, cached");
option = ScriptCompiler::kConsumeCodeCache;
auto maybeScript = ScriptCompiler::Compile(isolate->GetCurrentContext(), &source, option);
if (maybeScript.IsEmpty() || tc.HasCaught()) {
throw NativeScriptException(tc, "Cannot compile " + path);
}