blib/lib/JavaScript/V8/CommonJS.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« blib/lib/JavaScript/V8/CommonJS/Exception.pm ↑ Summary Build »
1 package JavaScript::V8::CommonJS;
2  
3 # use strictures 2;
4 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 4 ▶use JavaScript::V8;
Subroutine BEGIN: called CC=1 SCAR=2.6
7 use JavaScript::V8::CommonJS::Exception;
8 use File::ShareDir 'dist_dir';
9 use File::Basename 'dirname';
10 use File::Spec::Functions qw' rel2abs catdir catfile ';
11 use Cwd qw' getcwd realpath ';
12 use Data::Dumper;
13 use Data::Printer;
14 use Carp qw' croak confess ';
15  
16 our $VERSION = "0.06";
17  
18 my $scripts_dir = realpath catdir(dirname(rel2abs(__FILE__)), '../../../share');
19 $scripts_dir = catdir(dist_dir('JavaScript-V8-CommonJS'))
20 unless -d $scripts_dir;
21  
22 sub new {
23 my $class = shift;
24 my $args = @_ == 0 ? {}
25 : @_ > 1 ? {@_} : $_[0];
26  
27 croak "invalid arguments" unless ref $args eq 'HASH';
28  
29 bless my $self = {
30 paths => $args->{paths} || [getcwd()],
31 modules => $args->{modules} || {},
32 v8_params => $args->{v8_params},
33 }, $class;
34  
35 $self->{c} = $self->_build_ctx;
36 $self;
37 }
38  
39 sub c { shift->{c} }
40 sub modules { shift->{modules} }
41 sub paths { shift->{paths} }
42  
43  
44 sub _build_ctx {
45 my $self = shift;
46 my $c = JavaScript::V8::Context->new($self->{v8_params} ? %{$self->{v8_params}} : ());
47  
48 # global functions
49 for my $name (qw/ resolveModule requireNative evalModuleFile /) {
50  
51 $c->bind($name => sub {
52 $self->can("_$name")->($self, @_);
53 });
54 }
55  
56 $c->bind(
57 console => {
58 log => \&_log,
59 warn => \&_log,
60 error => \&_log,
61 info => \&_log,
62 }
63 );
64  
65 # require.js
66 my $require_js = catfile($scripts_dir, "require.js");
67 _eval($c, _slurp($require_js), $require_js);
68  
69 $c;
70 }
71  
72 sub add_module {
73 my ($self, $name, $module) = @_;
74 my $mods = $self->modules;
75 croak "add_module() error: '$name' already exists'" if exists $mods->{$name};
76 $mods->{$name} = $module;
77 }
78  
79  
80 sub _requireNative {
81 my ($self, $id) = @_;
82 $self->modules->{$id};
83 }
84  
85 sub _resolveModule {
86 my ($self, $id, $current_module_file) = @_;
87  
88 confess "Can't traverse up the module paths." if $id =~ /\.\./;
89  
90 # relative
91 if ($id =~ /^\.\//) {
92  
93 confess "Can't load relative module '$id' without current_module_file" unless $current_module_file;
94 my $dir = dirname($current_module_file);
95 my $file = catfile($dir, $id.'.js');
96 return -e $file ? $file : undef;
97 }
98  
99  
100 # convert absolute path into module id
101 $id =~ s/^\/+//g;
102  
103 # module id
104 foreach my $path (@{$self->paths}) {
105 for my $file (catfile($path, $id.".js"), catfile($path, $id.".json")) {
106 return $file if -f $file;
107 }
108 }
109  
110 return undef;
111 }
112  
113  
114 sub _readFile {
115 my ($self, $path) = @_;
116 return undef unless -f $path;
117 _slurp($path);
118 }
119  
120  
121 sub _log {
122 my (@lines) = @_;
123 @lines = map { defined $_ ? $_ : 'undef' } map { ref $_ ? Dumper($_) : $_ } @lines;
124 printf STDERR "# [console.log] @lines\n";
125 }
126  
127 sub eval_file {
128 my ($self, $file) = @_;
129 croak "do not exist: $file" unless -f $file;
130 $self->eval(_slurp($file), $file);
131 }
132  
133 sub _evalModuleFile {
134 my ($self, $file) = @_;
135 croak "module '$file' do not exist" unless -f $file;
136 my $module_code = _slurp($file);
137  
138 # JSON
139 if ($file =~ /\.json$/) {
140
141 # validate json
142 my $json = _slurp($file);
143  
144 # inject as module
145 my $rv = $self->c->eval(qq!
146  
147 require.__modules["$file"] = {
148 exports: null,
149 __filename: "$file"
150 };
151  
152 (function (module) { "use strict"; module.exports = $json; })(require.__modules["$file"]);
153  
154 !, $file);
155  
156 if (!defined $rv && $@) {
157 $@ =~ s/^Error: //;
158 die $@
159 }
160  
161 return;
162 }
163  
164 # js module
165 my $wrapper = qq!
166  
167 require.__modules["$file"] = {
168 exports: {},
169 __filename: "$file"
170 };
171  
172 try {
173 require.__callStack.push(require.__modules["$file"]);
174 (function (require, module, exports, __filename, __dirname) { "use strict"; \%s })(require, require.__modules["$file"], require.__modules["$file"].exports, "$file");
175 require.__modules["$file"].__is_compiled = true;
176 }
177 finally{
178 require.__callStack.pop();
179 if (require.__modules["$file"].__is_compiled) {
180 delete require.__modules["$file"].__is_compiled;
181 } else {
182 delete require.__modules["$file"];
183 }
184 }
185  
186 1;
187 !;
188  
189 # make oneline
190 $wrapper =~ s/\n//g;
191  
192 # eval
193 my $rv = $self->c->eval(sprintf($wrapper, $module_code), $file);
194  
195 if (!defined $rv && $@) {
196 $@ =~ s/^Error: //;
197 die $@
198 }
199  
200 $rv;
201 }
202  
203 sub eval {
204 my $self = shift;
205 _eval($self->c, @_);
206 };
207  
208 sub _eval {
209 my ($c, $code, $source) = @_;
210 local $@ = undef;
211 my $rv = $c->eval("try {$code} catch(e) {throw e.stack}", $source || ());
212 if (!defined $rv && $@) {
213 # warn "# eval error((($@)))";
214 my $exception = JavaScript::V8::CommonJS::Exception->new_from_string($@);
215 my $ourStackCall = $exception->stack->[-1];
216 $ourStackCall->{column} = $ourStackCall->{column} - 5 if ref $ourStackCall eq 'HASH'; # subtract "try {" length
217 die $exception;
218 }
219 $rv;
220 };
221  
222  
223  
224 sub _slurp {
225 my $path = shift;
226  
227 CORE::open my $file, '<:encoding(UTF-8)', $path or croak qq{Can't open file "$path": $!};
228 my $ret = my $content = '';
229 while ($ret = $file->sysread(my $buffer, 131072, 0)) { $content .= $buffer }
230 croak qq{Can't read from file "$path": $!} unless defined $ret;
231  
232 return $content;
233 }
234  
235 1;
236 __END__
« blib/lib/JavaScript/V8/CommonJS/Exception.pm ↑ Summary Build »