lib/BarefootJS.pm

filter: Statementstmt 73.3% 641 / 874 Branchbran 64.2% 407 / 634 Conditioncond 50.5% 142 / 281 MC/DCmcdc 35.7% 59 / 165 Subroutinesub 71.4% 130 / 182 Podpod 0.0% 0 / 116 totaltotal 61.2% 1379 / 2252 CC 484 SCAR 39.3
CC
484
Cov
67%
_has_unsafe_style_value
756.0
reduce
306.0
date
132.0
CRAP 51.1
↑ Summary lib/BarefootJS/Evaluator.pm »
1 package BarefootJS;
2 17 our $VERSION = "0.41.3";
3 17 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 17 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 17 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 17 ▶use feature 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 17 ▶no warnings 'experimental::signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 17 ▶use B ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 17 ▶use JSON::PP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 17 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 17 ▶use Time::Local ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 17 ▶use Scalar::Util qw(looks_like_number refaddr weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 17 ▶use BarefootJS::Undefined ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 17 ▶use BarefootJS::Evaluator ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 # JS `undefined` (BarefootJS/Undefined.pm); Perl's `undef` is JS `null`. A
18 # props hashref has JS's four states for a prop: the key left out (absent),
19 # `$BarefootJS::UNDEF` (present `undefined`), `undef` (`null`) and a value.
20 # `UNDEF` is `defined` in Perl's sense and `//` keeps it, so every nullish
21 # test in this runtime goes through `_nullish` (`is_nullish`), never
22 # `defined` / `//`.
23 17 our $UNDEF = $BarefootJS::Undefined::UNDEF;
24 437 ▶sub _undef_p { BarefootJS::Undefined::is_undefined($_[0]) }
Subroutine _undef_p: called CC=1 SCAR=0.0
25 205 ▶sub _nullish { BarefootJS::Undefined::is_nullish($_[0]) }
Subroutine _nullish: called CC=1 SCAR=0.0
26  
27 # The default of a helper's optional argument: the call passed none. JS
28 # reads an omitted argument as `undefined`, so `_omitted` accepts `UNDEF`
29 # too; an explicit `undef` is JS `null`, which each helper coerces like any
30 # other value (`[1, 2].slice(0, null)` is `[]`).
31 17 my $OMITTED = \'omitted';
32 178 ▶sub _omitted { return (ref $_[0] && refaddr($_[0]) == refaddr($OMITTED)) || _undef_p($_[0]) ? 1 : 0 }
Subroutine _omitted: called CC=4 SCAR=13.9
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] && builtin::refaddr($_[0]) == builtin::refaddr($OMITTED) || _undef_p($_[0]) ? : 52 126 178
Condition100%6/6
ref $_[0] and builtin::refaddr($_[0]) == builtin::refaddr($OMITTED) or _undef_p($_[0])
l!l&&r!l&&!r
3616126
ref $_[0] and builtin::refaddr($_[0]) == builtin::refaddr($OMITTED)
!ll&&!rl&&r
1261636
MC/DC33%1/3
ref $_[0] and builtin::refaddr($_[0]) == builtin::refaddr($OMITTED) or _undef_p($_[0])
ref $_[0] builtin::refaddr($_[0]) == builtin::refaddr($OMITTED) _undef_p($_[0])
Truth table60%3/5
A and B or C
A= ref $_[0]B= builtin::refaddr($_[0]) == builtin::refaddr($OMITTED)C= _undef_p($_[0])
ABCresult
11X1
0X11
1011
0X00
1000
33  
34 # JS ToString / ToNumber for a helper argument (a needle, a separator, a
35 # count), which spell `null` / `undefined` as JS does (`"null"` / 0,
36 # `"undefined"` / NaN); `string` / `number` are the display helpers.
37 98 ▶sub _js_string { BarefootJS::Evaluator::_to_string($_[0]) }
Subroutine _js_string: called CC=1 SCAR=0.0
38 180 ▶sub _js_number { BarefootJS::Evaluator::_to_number($_[0]) }
Subroutine _js_number: called CC=1 SCAR=0.0
39  
40 # NOTE: This runtime is template-engine-agnostic AND framework-agnostic by
41 # design, so it can ship as a standalone CPAN distribution. It depends only on
42 # core Perl (subroutine signatures + the hand-rolled minimal accessor base
43 # below — no Mojo::Base, no Class::Tiny). Every operation that depends on *how*
44 # a template is rendered — JSON marshalling, raw-string marking, JSX-children
45 # materialisation, and named-template rendering — is delegated to a pluggable
46 # `backend` (see BarefootJS::Backend::Mojo for the reference Mojolicious
47 # implementation), which is the only component that pulls in the Mojo
48 # distribution, and only when it is actually used.
49  
50 # ---------------------------------------------------------------------------
51 # Minimal accessor base (no Mojo::Base / Class::Tiny dependency)
52 # ---------------------------------------------------------------------------
53 #
54 # Generates read/write accessors with optional lazy defaults so the runtime
55 # stays free of any non-core OO base. Semantics mirror the Mojo::Base `has`
56 # this class used to inherit: a getter returns the stored value (building it
57 # from the default on first access if unset); a setter stores the value and
58 # returns $self for chaining. A default is either a plain scalar or a coderef
59 # invoked as `$default->($self)` (for per-instance refs like `[]` / `{}` and
60 # the lazily-required Mojo backend).
61 my %ATTR_DEFAULT = (
62 6 ▶ _scripts => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
63 6 ▶ _script_seen => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
64 6 ▶ _preloads => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
65 6 ▶ _preload_seen => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
66 6 ▶ _portal_elements => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
67 10 ▶ _child_renderers => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
68 _is_child => 0,
69 # Lazily fall back to the Mojo reference backend so a bare-blessed
70 # instance (the pure-function unit tests) and the historical
71 # `BarefootJS->new($c, ...)` callers keep working unchanged. A non-Mojo
72 # host injects its own backend via `BarefootJS->new($c, { backend => $b })`
73 # and never triggers this require — keeping the core load Mojo-free.
74 0 ▶ backend => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
75 0 require BarefootJS::Backend::Mojo;
76 0 return BarefootJS::Backend::Mojo->new;
77 },
78 17 );
79  
80 # c — Mojolicious controller (kept for back-compat accessors)
81 # config — plugin / instance config
82 # backend — the template-engine seam (#engine-abstraction)
83 # _scope_id — addressable scope id
84 # _bf_parent / _bf_mount — slot identity when this scope is slot-attached
85 # _props — props serialised into bf-p / the scope comment
86 # _data_key — keyed-loop-item key, emitted as data-key on the scope root
87 17 for my $attr (qw(
88 c config backend
89 _scripts _script_seen _preloads _preload_seen _portal_elements _scope_id _is_child _bf_parent _bf_mount _props
90 _data_key _child_renderers
91 )) {
92 17 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
93 255 ▶ *{"BarefootJS::$attr"} = sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
94 363 my $self = shift;
95 363 ▶ if (@_) { $self->{$attr} = shift; return $self; }
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 101 262 363
96 262 ▶ if (!exists $self->{$attr} && exists $ATTR_DEFAULT{$attr}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not exists $self->{$attr} and exists $ATTR_DEFAULT{$attr}) 40 222 262
Condition100%3/3
not exists $self->{$attr} and exists $ATTR_DEFAULT{$attr}
!ll&&!rl&&r
2081440
MC/DC100%2/2
not exists $self->{$attr} and exists $ATTR_DEFAULT{$attr}
not exists $self->{$attr} exists $ATTR_DEFAULT{$attr}
Truth table100%3/3
not(A) and B
A= not exists $self->{$attr}B= exists $ATTR_DEFAULT{$attr}
ABresult
0X0
100
111
97 40 my $d = $ATTR_DEFAULT{$attr};
98 40 ▶ $self->{$attr} = ref($d) eq 'CODE' ? $d->($self) : $d;
Branch: 1 branch
BranchTrueFalseTotal
ref $d eq 'CODE' ? : 40 0 40
99 }
100 262 return $self->{$attr};
101 255 };
102 }
103  
104 29 ▶sub new ($class, $c, $config = {}) {
Subroutine new: called CC=5 SCAR=18.1
Pod undocumented
105 # Build (or accept an injected) rendering backend. The default Mojo
106 # backend wraps the controller and honours an optional `json_encoder`
107 # override so a host can swap in a faster XS JSON implementation
108 # without subclassing. A caller targeting another template engine
109 # passes its own backend via `$config->{backend}`.
110 29 my $backend = $config->{backend};
111 29 ▶ unless ($backend) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($backend) 0 29 29
112 0 require BarefootJS::Backend::Mojo;
113 $backend = BarefootJS::Backend::Mojo->new(
114 c => $c,
115 ($config->{json_encoder}
116 ? (json_encoder => $config->{json_encoder})
117 0 ▶ : ()),
Branch: 1 branch
BranchTrueFalseTotal
$config->{'json_encoder'} ? : 0 0 0
118 );
119 }
120 29 my $self = bless {
121 c => $c,
122 config => $config,
123 backend => $backend,
124 }, $class;
125 # Hold the controller weakly. Mojolicious stashes this bf instance under
126 # `$c->stash->{'bf.instance'}`, so a strong bf -> controller back-reference
127 # closes a per-request cycle ($c -> stash -> bf -> $c) that Perl's
128 # refcount GC cannot reclaim, leaking one controller + bf + child-renderer
129 # closures per request. The controller owns (outlives) the per-request bf,
130 # so the weak ref stays valid for the whole render. Callers that need the
131 # controller to outlive the bf instance independently must keep their own
132 # strong reference (the normal Mojo request scope already does).
133 29 ▶ weaken($self->{c}) if defined $c;
Branch: 1 branch
BranchTrueFalseTotal
if defined $c 1 28 29
134 29 return $self;
135 }
136  
137 # search_params($query = '')
138 #
139 # Build a request-scoped reader for the reactive searchParams() environment
140 # signal (router v0.5, #1922) from a raw query string. Callable as a class or
141 # instance method — the invocant is unused.
142 #
143 # The `require` lives here so consumers (the Mojo plugin, the Xslate host, the
144 # test harness, generated render scripts) reach BarefootJS::SearchParams through
145 # the BarefootJS object they already hold, never `use`-ing it directly — the
146 # same lazy-load seam the Mojo backend uses above. The compiled template reads
147 # the returned object via `$searchParams->get('key')`.
148 9 ▶sub search_params ($invocant, $query = '') {
Subroutine search_params: called CC=2 SCAR=6.9
Pod undocumented
149 9 require BarefootJS::SearchParams;
150 9 return BarefootJS::SearchParams->new($query);
151 }
152  
153 # ---------------------------------------------------------------------------
154 # Scope & Props
155 # ---------------------------------------------------------------------------
156  
157 0 ▶sub scope_attr ($self) {
Subroutine scope_attr: not called CC=2 SCAR=17.9
Pod undocumented
158 # bf-s is the addressable scope id only (#1249).
159 0 ▶ return $self->_scope_id // '';
Condition0%0/2
$self->_scope_id // ""
l!l
00
MC/DC0%0/1
$self->_scope_id // ""
$self->_scope_id
Truth table0%0/2
A
A= $self->_scope_id
Aresult
11
00
160 }
161  
162 # Emits `bf-h="<host>" bf-m="<slot>" bf-r=""` conditionally.
163 # See spec/compiler.md "Slot identity".
164 0 ▶sub hydration_attrs ($self) {
Subroutine hydration_attrs: not called CC=6 SCAR=37.4
Pod undocumented
165 0 my @parts;
166 0 my $host = $self->_bf_parent;
167 0 my $mount = $self->_bf_mount;
168 0 ▶ if (defined $host && length $host) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $host and CORE::length $host) 0 0 0
Condition0%0/3
defined $host and CORE::length $host
!ll&&!rl&&r
000
MC/DC0%0/2
defined $host and CORE::length $host
defined $host CORE::length $host
Truth table0%0/3
A and B
A= defined $hostB= CORE::length $host
ABresult
0X0
100
111
169 0 my $h = $host =~ s/"/&quot;/gr;
170 0 push @parts, qq{bf-h="$h"};
171 }
172 0 ▶ if (defined $mount && length $mount) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $mount and CORE::length $mount) 0 0 0
Condition0%0/3
defined $mount and CORE::length $mount
!ll&&!rl&&r
000
MC/DC0%0/2
defined $mount and CORE::length $mount
defined $mount CORE::length $mount
Truth table0%0/3
A and B
A= defined $mountB= CORE::length $mount
ABresult
0X0
100
111
173 0 my $m = $mount =~ s/"/&quot;/gr;
174 0 push @parts, qq{bf-m="$m"};
175 }
176 0 ▶ unless ($self->_is_child) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_is_child) 0 0 0
177 0 push @parts, q{bf-r=""};
178 }
179 0 return join(' ', @parts);
180 }
181  
182 # Emits ` data-key="<key>"` for a keyed loop item, else ''. The client
183 # runtime uses data-key for list reconciliation; SSR must match the Hono
184 # reference, which stamps it on each loop item's scope root. The value is set
185 # on the child instance by the child renderer (`register_child_renderer` /
186 # `register_components_from_manifest`) from the JSX `key` prop — a reserved
187 # prop, never a real template variable. The key prints as JS `String(key)`
188 # does (`string`): a JSON boolean row is `true` / `false`, not `1` / `0`.
189 0 ▶sub data_key_attr ($self) {
Subroutine data_key_attr: not called CC=2 SCAR=17.9
Pod undocumented
190 0 my $k = $self->_data_key;
191 0 ▶ return '' if _nullish($k);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($k) 0 0 0
192 0 $k = $self->string($k);
193 0 $k =~ s/&/&amp;/g;
194 0 $k =~ s/"/&quot;/g;
195 0 return qq{ data-key="$k"};
196 }
197  
198 4 ▶sub props_attr ($self) {
Subroutine props_attr: called CC=3 SCAR=11.0
Pod undocumented
199 4 my $props = $self->_props;
200 4 ▶ return '' unless $props && %$props;
Branch: 1 branch
BranchTrueFalseTotal
unless $props and %$props 2 2 4
Condition100%3/3
$props and %$props
!ll&&!rl&&r
112
MC/DC100%2/2
$props and %$props
$props %$props
Truth table100%3/3
A and B
A= $propsB= %$props
ABresult
0X0
100
111
201 # encode_json returns a character string (not bytes) for safe embedding
202 # in templates (the Mojo backend uses Mojo::JSON::to_json).
203 # The JSON must then be attribute-escaped: a raw `'` inside a string
204 # value (e.g. a blog paragraph) terminates the single-quoted attribute
205 # and truncates the hydration payload. The browser entity-decodes the
206 # attribute value, so the client's JSON.parse sees the original text.
207 2 my $json = _html_escape($self->backend->encode_json(_json_ready($props)));
208 2 return qq{ bf-p='$json'};
209 }
210  
211 # ---------------------------------------------------------------------------
212 # Context (SSR mirror of the client `provideContext` / `useContext`)
213 # ---------------------------------------------------------------------------
214 #
215 # A `<Ctx.Provider value>` seeds a value that descendant `useContext(Ctx)`
216 # consumers read during the same render. Dynamic scoping mirrors the client:
217 # the provider pushes the value before rendering its children and pops it
218 # after, and `use_context` reads the innermost active value (or the
219 # `createContext` default when none is active).
220 #
221 # The value stacks live in a package-level store rather than per-instance or
222 # on `$c->stash`: a parent template and the child templates it renders via
223 # `render_child` are separate bf instances that don't reliably share a
224 # controller (the Xslate backend runs with `c => undef`) nor a backend (the
225 # Mojo path lazily builds one per instance). SSR rendering is synchronous —
226 # nothing awaits between a provider's push and its matching pop — and the
227 # push/pop are perfectly balanced, so the per-name stack always unwinds to
228 # empty at the end of each provider subtree, keeping concurrent root renders
229 # isolated. provide/revoke return '' so they drop cleanly into an inline
230 # `<: … :>` (Kolon) or `% … ;` (EP) emit.
231  
232 17 my %CONTEXT_STACKS;
233  
234 0 ▶sub provide_context ($self, $name, $value) {
Subroutine provide_context: not called CC=2 SCAR=17.9
Pod undocumented
235 0 ▶ push @{ $CONTEXT_STACKS{$name} //= [] }, $value;
Condition0%0/2
$CONTEXT_STACKS{$name} //= []
l!l
00
MC/DC0%0/1
$CONTEXT_STACKS{$name} //= []
$CONTEXT_STACKS{$name}
Truth table0%0/2
A
A= $CONTEXT_STACKS{$name}
Aresult
11
00
236 0 return '';
237 }
238  
239 0 ▶sub revoke_context ($self, $name) {
Subroutine revoke_context: not called CC=3 SCAR=24.8
Pod undocumented
240 0 ▶ pop @{ $CONTEXT_STACKS{$name} } if $CONTEXT_STACKS{$name} && @{ $CONTEXT_STACKS{$name} };
Branch: 1 branch
BranchTrueFalseTotal
if $CONTEXT_STACKS{$name} and @{$CONTEXT_STACKS{$name};} 0 0 0
Condition0%0/3
$CONTEXT_STACKS{$name} and @{$CONTEXT_STACKS{$name};}
!ll&&!rl&&r
000
MC/DC0%0/2
$CONTEXT_STACKS{$name} and @{$CONTEXT_STACKS{$name};}
$CONTEXT_STACKS{$name} @{$CONTEXT_STACKS{$name};}
Truth table0%0/3
A and B
A= $CONTEXT_STACKS{$name}B= @{$CONTEXT_STACKS{$name};}
ABresult
0X0
100
111
241 0 return '';
242 }
243  
244 0 ▶sub use_context ($self, $name, $default = $UNDEF) {
Subroutine use_context: not called CC=4 SCAR=30.0
Pod undocumented
245 0 my $stack = $CONTEXT_STACKS{$name};
246 0 ▶ return $default unless $stack && @$stack;
Branch: 1 branch
BranchTrueFalseTotal
unless $stack and @$stack 0 0 0
Condition0%0/3
$stack and @$stack
!ll&&!rl&&r
000
MC/DC0%0/2
$stack and @$stack
$stack @$stack
Truth table0%0/3
A and B
A= $stackB= @$stack
ABresult
0X0
100
111
247 0 return $stack->[-1];
248 }
249  
250 # ---------------------------------------------------------------------------
251 # Comment Markers
252 # ---------------------------------------------------------------------------
253  
254 0 ▶sub comment ($self, $text) {
Subroutine comment: not called CC=1 SCAR=6.9
Pod undocumented
255 0 return "<!--bf-$text-->";
256 }
257  
258 # Neutralize a value for splicing into comment()'s HTML comment content
259 # (#2795 follow-up). comment() itself does no escaping -- fine for every
260 # other caller (marker IDs like "cond-start:s0", "loop:l0", ...), which are
261 # entirely compiler-generated, but the whole-item-conditional loop's
262 # "loop-i:<key>" anchor carries a user-controlled key. Standard HTML
263 # escaping doesn't help inside a comment -- only the literal sequence "-->"
264 # terminates it early, and &/</>/"/' are not special there. The key's exact
265 # text doesn't need to round-trip (the client's mapArrayAnchored matches
266 # items positionally and by its own JS-computed key, never by re-parsing
267 # the anchor Comment.nodeValue), so replacing every "-" with the
268 # visually-similar U+2010 is sufficient and needs no decoding.
269 0 ▶sub escape_comment_key ($self, $value) {
Subroutine escape_comment_key: not called CC=1 SCAR=6.9
Pod undocumented
270 0 my $s = $self->string($value);
271 0 $s =~ s/-/‐/g;
272 0 return $s;
273 }
274  
275 # ---------------------------------------------------------------------------
276 # JS-equivalent value stringification
277 # ---------------------------------------------------------------------------
278  
279 # Map a Perl boolean-shaped value to the JS `String(bool)` form.
280 # Used by the Mojo adapter when emitting reactive attribute bindings
281 # whose JS source `isBooleanResultExpr` classified as boolean —
282 # a comparison (`count() > 0`), a logical negation (`!ok()`), or a
283 # literal `true` / `false`. Perl's auto-stringification of those
284 # expressions yields `''` / `1`; Hono and Go emit `'false'` / `'true'`.
285 # Centralising the bool → string mapping here keeps the contract
286 # testable and the template-emit syntax tidy
287 # (`<%= bf->bool_str(...) %>` vs an inline ternary).
288 #
289 # Contract is boolean-only: callers must have classified the
290 # expression as boolean-result before routing through this helper.
291 # Non-boolean values reaching here will be Perl-truthy-coerced to
292 # 'true' / 'false', which is generally wrong — non-boolean attribute
293 # bindings stay on the plain `<%= expr %>` emit path and never reach
294 # this function.
295 3 ▶sub bool_str ($self, $value) {
Subroutine bool_str: called CC=6 SCAR=19.0
Pod undocumented
296 # An already-stringified JS boolean (`String(flag)`, which `string`
297 # prints as `true` / `false`, #3440) keeps its text: the string
298 # `'false'` is truthy in Perl.
299 3 ▶ return $value if defined $value && !ref($value) && ($value eq 'true' || $value eq 'false');
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and not ref $value and $value eq "true" || $value eq "false" 2 1 3
Condition66%6/9
defined $value and not ref $value and $value eq "true" || $value eq "false"
!ll&&!rl&&r
012
defined $value and not ref $value
!ll&&!rl&&r
003
$value eq "true" or $value eq "false"
l!l&&r!l&&!r
111
MC/DC50%2/4
defined $value and not ref $value and $value eq "true" || $value eq "false"
defined $value not ref $value $value eq "true" $value eq "false"
Truth table60%3/5
A and not(B) and C or D
A= defined $valueB= not ref $valueC= $value eq "true"D= $value eq "false"
ABCDresult
0XXX0
10XX0
11000
111X1
11011
300 1 ▶ return $value ? 'true' : 'false';
Branch: 1 branch
BranchTrueFalseTotal
$value ? : 0 1 1
301 }
302  
303 0 ▶sub text_start ($self, $slot_id) {
Subroutine text_start: not called CC=1 SCAR=6.9
Pod undocumented
304 0 return "<!--bf:$slot_id-->";
305 }
306  
307 0 ▶sub text_end ($self) {
Subroutine text_end: not called CC=1 SCAR=6.9
Pod undocumented
308 0 return "<!--/-->";
309 }
310  
311 # See spec/compiler.md "Slot identity" for the comment-scope wire format.
312 5 ▶sub scope_comment ($self) {
Subroutine scope_comment: called CC=7 SCAR=19.6
Pod undocumented
313 5 ▶ my $scope_id = $self->_scope_id // '';
Condition100%2/2
$self->_scope_id // ""
l!l
41
MC/DC100%1/1
$self->_scope_id // ""
$self->_scope_id
Truth table100%2/2
A
A= $self->_scope_id
Aresult
11
00
314 5 my $host_segment = '';
315 5 my $host = $self->_bf_parent;
316 5 my $mount = $self->_bf_mount;
317 5 ▶ if (defined $host && length $host) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $host and CORE::length $host) 2 3 5
Condition66%2/3
defined $host and CORE::length $host
!ll&&!rl&&r
302
MC/DC50%1/2
defined $host and CORE::length $host
defined $host CORE::length $host
Truth table66%2/3
A and B
A= defined $hostB= CORE::length $host
ABresult
0X0
100
111
318 2 ▶ $host_segment = "|h=$host|m=" . ($mount // '');
Condition50%1/2
$mount // ""
l!l
20
MC/DC0%0/1
$mount // ""
$mount
Truth table50%1/2
A
A= $mount
Aresult
11
00
319 }
320 5 my $props_json = '';
321 5 ▶ if ($self->_props && %{$self->_props}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_props and %{$self->_props;}) 3 2 5
Condition66%2/3
$self->_props and %{$self->_props;}
!ll&&!rl&&r
203
MC/DC50%1/2
$self->_props and %{$self->_props;}
$self->_props %{$self->_props;}
Truth table66%2/3
A and B
A= $self->_propsB= %{$self->_props;}
ABresult
0X0
100
111
322 3 $props_json = '|' . $self->backend->encode_json(_json_ready($self->_props));
323 }
324 5 return "<!--bf-scope:$scope_id$host_segment$props_json-->";
325 }
326  
327 # Paired end marker for scope_comment above. Bounds the scope's sibling
328 # range so client-side queries from a fragment-rooted scope don't leak
329 # onto later siblings owned by the parent (#2289). No `|h=`/`|m=`/props
330 # segments — the client only needs the scope id to find the matching end.
331 3 ▶sub scope_comment_end ($self) {
Subroutine scope_comment_end: called CC=2 SCAR=6.9
Pod undocumented
332 3 ▶ my $scope_id = $self->_scope_id // '';
Condition100%2/2
$self->_scope_id // ""
l!l
21
MC/DC100%1/1
$self->_scope_id // ""
$self->_scope_id
Truth table100%2/2
A
A= $self->_scope_id
Aresult
11
00
333 3 return "<!--bf-/scope:$scope_id-->";
334 }
335  
336 # ---------------------------------------------------------------------------
337 # Script Registration
338 # ---------------------------------------------------------------------------
339  
340 0 ▶sub register_script ($self, $path) {
Subroutine register_script: not called CC=2 SCAR=17.9
Pod undocumented
341 0 ▶ return if $self->_script_seen->{$path};
Branch: 1 branch
BranchTrueFalseTotal
if $self->_script_seen->{$path} 0 0 0
342 0 $self->_script_seen->{$path} = 1;
343 0 push @{$self->_scripts}, $path;
344 }
345  
346 # Register a `<link rel="modulepreload">` hint — mirrors register_script
347 # exactly: same dedup-by-path hash, same insertion-order arrayref, same
348 # lifetime/reset (child-propagation) semantics, same no-output-string
349 # return so a template's `<: $bf->register_preload(...) :>` /
350 # `% $bf->register_preload(...);` emits no bytes where it sits. The
351 # `<link>` tag itself is only ever produced by `scripts` below, never
352 # here — a preload registration must never inject a node into a
353 # component's own template output.
354 0 ▶sub register_preload ($self, $path) {
Subroutine register_preload: not called CC=2 SCAR=17.9
Pod undocumented
355 0 ▶ return if $self->_preload_seen->{$path};
Branch: 1 branch
BranchTrueFalseTotal
if $self->_preload_seen->{$path} 0 0 0
356 0 $self->_preload_seen->{$path} = 1;
357 0 push @{$self->_preloads}, $path;
358 }
359  
360 # ---------------------------------------------------------------------------
361 # SSR Portal Element Registration (#3119)
362 # ---------------------------------------------------------------------------
363  
364 # Collects an `ssrPortalOwnerScope`-flagged element's already-rendered,
365 # fully-evaluated markup so it can be emitted at the `portals` outlet near
366 # `</body>` instead of at its source position — the `ref`-callback
367 # SSR-portal pattern the dialog-style primitives use
368 # (`DialogOverlay`/`DialogContent`, `DropdownMenuContent`,
369 # `PopoverContent`, the explicit `<Portal>` component). `$content` already
370 # carries its own `bf-po` attribute (stamped directly on its own tag by the
371 # compiler, matching exactly what the client
372 # `createPortal(el, document.body, { ownerScope })` stamps onto the SAME
373 # element at hydrate time), so unlike a hypothetical "wrap arbitrary
374 # children" collector this appends `$content` UNWRAPPED — no extra
375 # `bf-pi`/`bf-po` container element, which would diverge from what the
376 # client stamps directly onto the element itself. Returns nothing — every
377 # call site sinks the return value (a template's `% $bf->register_portal_
378 # element(...);` statement tag / Kolon `: $bf.register_portal_element(...)
379 # ;`, never an output tag), so nothing prints at the source position.
380 0 ▶sub register_portal_element ($self, $content) {
Subroutine register_portal_element: not called CC=1 SCAR=6.9
Pod undocumented
381 0 push @{$self->_portal_elements}, $content;
382 0 return;
383 }
384  
385 # Emits every collected SSR-portal element, in registration order. Place
386 # `<%= $bf->portals %>` (Mojo) / `: $bf.portals()` (Kolon) once near
387 # `</body>` in the app's own layout — mirrors `scripts` above (same
388 # "collect during render, emit at a single outlet" shape) and the Hono
389 # reference adapter's `<BfPortals />`.
390 0 ▶sub portals ($self) {
Subroutine portals: not called CC=1 SCAR=6.9
Pod undocumented
391 0 return join "\n", @{$self->_portal_elements};
392 }
393  
394 # ---------------------------------------------------------------------------
395 # Child Component Rendering
396 # ---------------------------------------------------------------------------
397 # (`_child_renderers` accessor is generated by the minimal accessor base above.)
398  
399 # Register a renderer for `render_child($name, ...)`. The renderer is
400 # invoked as `$renderer->($props_hashref, $invoking_bf)` — unpack `@_`
401 # (`my ($props, $caller) = @_;`) instead of declaring a one-argument
402 # subroutine signature, which would enforce arity and die on the second
403 # argument.
404 26 ▶sub register_child_renderer ($self, $name, $renderer) {
Subroutine register_child_renderer: called CC=1 SCAR=0.0
Pod undocumented
405 26 $self->_child_renderers->{$name} = $renderer;
406 }
407  
408 # The keys the innermost `render_child` call passed (see `passed`); undef
409 # outside one, i.e. while the root renders.
410 17 our $CALLER_KEYS;
411  
412 # Whether this component's caller passed the prop `$name`, even as undef
413 # (`null`) or `UNDEF`: JS's `name in props`, which a template can't ask of its
414 # stash (every declared prop is seeded, so an omitted one reads as its default
415 # or `UNDEF`, as a present `undefined` one does). A `{...props}` spread onto a
416 # child carries a param only when this is true. The keys are those
417 # `render_child` recorded for a child and `_props` for the root; with neither
418 # recorded (a root rendered without `_props`), `$fallback`, the template's own
419 # "not undefined" test, decides.
420 11 ▶sub passed ($self, $name, $fallback = undef) {
Subroutine passed: called CC=7 SCAR=19.5
Pod undocumented
421 11 ▶ return exists $CALLER_KEYS->{$name} ? 1 : 0 if $CALLER_KEYS;
Branch: 2 branches
BranchTrueFalseTotal
if $BarefootJS::CALLER_KEYS 3 8 11
exists $BarefootJS::CALLER_KEYS->{$name} ? : 2 1 3
422 8 my $props = $self->_props;
423 8 ▶ return exists $props->{$name} ? 1 : 0 if ref $props eq 'HASH';
Branch: 2 branches
BranchTrueFalseTotal
if ref $props eq "HASH" 5 3 8
exists $props->{$name} ? : 3 2 5
424 3 ▶ return $fallback ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$fallback ? : 1 2 3
425 }
426  
427 16 ▶sub render_child ($self, $name, @args) {
Subroutine render_child: called CC=5 SCAR=16.1
Pod undocumented
428 16 my $renderer = $self->_child_renderers->{$name};
429 16 ▶ die "No renderer registered for child component '$name'" unless $renderer;
Branch: 1 branch
BranchTrueFalseTotal
unless $renderer 1 15 16
430 # Accept both the Mojo list form — `bf->render_child($name, k => v, ...)`
431 # — and the single-hashref form — `$bf.render_child($name, { k => v })`.
432 # Template languages whose method calls can't splat a hash into positional
433 # args (Text::Xslate Kolon, Template Toolkit) pass one hashref instead.
434 15 ▶ my %props = (@args == 1 && ref $args[0] eq 'HASH') ? %{ $args[0] } : @args;
Branch: 1 branch
BranchTrueFalseTotal
@args == 1 && ref $args[0] eq 'HASH' ? : 2 13 15
Condition66%2/3
@args == 1 and ref $args[0] eq "HASH"
!ll&&!rl&&r
1302
MC/DC50%1/2
@args == 1 and ref $args[0] eq "HASH"
@args == 1 ref $args[0] eq "HASH"
Truth table66%2/3
A and B
A= @args == 1B= ref $args[0] eq "HASH"
ABresult
0X0
100
111
435 # JSX children AND any other named JSX-valued slot (`header={<strong/>}`,
436 # #2168 jsx-element-prop) come in via the engine's children-capture
437 # mechanism (Mojo's `begin %>...<% end`, which produces a CODE ref
438 # returning a Mojo::ByteStream). Materialize every prop value through
439 # the backend before handing the props to the child renderer, so the
440 # child template sees each slot as already-rendered HTML rather than a
441 # bare CODE ref — `materialize` is a no-op for a value that isn't a
442 # CODE ref (see e.g. `BarefootJS::Backend::Mojo::materialize`), so this
443 # is safe to apply unconditionally rather than naming `children`
444 # specifically.
445 15 $props{$_} = $self->backend->materialize($props{$_}) for keys %props;
446 # Record the keys this call passes for the child's `passed` while its
447 # template renders. The renderer builds the child's own instance, so the
448 # record is dynamically scoped (`local`) rather than stored on that
449 # object; rendering is synchronous, so it always holds the keys of the
450 # component whose template is running.
451 15 local $CALLER_KEYS = { map { $_ => 1 } keys %props };
452 # Renderer contract (#1897): the renderer is invoked with TWO
453 # arguments — the props hashref and the INVOKING instance. A renderer
454 # registered on the root may be called from a nested child render
455 # (AccordionTrigger -> ChevronDownIcon), and the grandchild's scope /
456 # slot identity must chain off the CALLER's scope id, not the
457 # registrant's. Renderers unpack `@_` (`my ($props, $caller) = @_;`)
458 # rather than enforcing arity with a one-arg subroutine signature —
459 # see `register_child_renderer`.
460 15 return $renderer->(\%props, $self);
461 }
462  
463 # ---------------------------------------------------------------------------
464 # Bulk registration from build manifest
465 # ---------------------------------------------------------------------------
466 #
467 # `vite build` (via `@barefootjs/mojolicious/vite`'s `barefoot()` plugin)
468 # emits dist/templates/manifest.json describing every component the page
469 # might invoke (Counter, ui/button/index, ...).
470 # This helper walks that manifest and registers one child renderer per
471 # UI registry entry — the path shape `ui/<name>/index` maps to the
472 # `<name>` slot key Counter.html.ep and friends use via
473 # `<%= bf->render_child('<name>', ...) %>`.
474 #
475 # Each manifest entry carries an `ssrDefaults` hash derived statically
476 # from the component's JSX (prop destructure defaults + signal /
477 # memo initial values, see packages/jsx/src/ssr-defaults.ts). The
478 # child renderer seeds every template variable from that hash,
479 # preferring the caller's matching prop where one exists. This
480 # replaces the per-component `signal_init` callback that every
481 # scaffold's `app.pl` used to hand-roll for items 1/3 of issue #1416.
482 #
483 # `signal_init` remains as an opt-in override for cases the static
484 # extractor can't see through (e.g. signal initial values that
485 # reference imported helpers). When supplied for a given slot key
486 # it takes precedence over the manifest's `ssrDefaults` for that
487 # child, allowing callers to mix manual overrides with auto-derived
488 # defaults for siblings.
489 #
490 # Multi-component modules (#2132): a registry module exporting several
491 # components from one file (`ui/toast/index.tsx` → ToastProvider, Toast,
492 # ToastTitle, ...) compiles to one template PER component, listed in the
493 # entry's `components` map (`{ ToastProvider => { markedTemplate,
494 # ssrDefaults }, ... }`). Compiled parent templates invoke each one under
495 # its snake_cased component name (`render_child('toast_provider')`), so a
496 # renderer is registered per component. These run AFTER the directory-name
497 # registration and win on collision — for `ui/toast/index` the key `toast`
498 # must resolve to Toast's own template, not the module's first template
499 # (ToastProvider), which is all the bare `markedTemplate` carries.
500 7 ▶sub register_components_from_manifest ($self, $manifest, %opts) {
Subroutine register_components_from_manifest: called CC=8 SCAR=20.9
Pod undocumented
501 7 ▶ my $signal_inits = $opts{signal_init} // {};
Condition100%2/2
$opts{"signal_init"} // {}
l!l
16
MC/DC100%1/1
$opts{"signal_init"} // {}
$opts{"signal_init"}
Truth table100%2/2
A
A= $opts{"signal_init"}
Aresult
11
00
502  
503 7 for my $entry_name (keys %$manifest) {
504 # `__barefoot__` is the runtime entry, not a component.
505 7 ▶ next if $entry_name eq '__barefoot__';
Branch: 1 branch
BranchTrueFalseTotal
if $entry_name eq "__barefoot__" 0 7 7
506 # Only UI registry components (path shape `ui/<name>/index`)
507 # become child renderers; top-level page components are the
508 # render target rather than a child.
509 7 ▶ next unless $entry_name =~ m{^ui/([^/]+)/index$};
Branch: 1 branch
BranchTrueFalseTotal
unless $entry_name =~ m[^ui/([^/]+)/index$] 0 7 7
510 7 my $slot_key = $1;
511 7 my $entry = $manifest->{$entry_name};
512  
513 # Directory-name registration — the pre-`components` convention,
514 # kept so manifests from older builds (no `components` map) still
515 # resolve single-component modules like `button`.
516 $self->_register_manifest_child(
517 $slot_key, $entry->{markedTemplate},
518 $signal_inits->{$slot_key}, $entry->{ssrDefaults},
519 7 );
520  
521 # Per-component registrations (#2132), keyed by the snake_cased
522 # component name the compiled templates actually call.
523 7 my $components = $entry->{components};
524 7 ▶ next unless ref($components) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $components eq "HASH" 2 5 7
525 5 for my $component_name (sort keys %$components) {
526 16 my $component = $components->{$component_name};
527 16 ▶ next unless ref($component) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $component eq "HASH" 0 16 16
528 16 my $component_key = _snake_case($component_name);
529 $self->_register_manifest_child(
530 $component_key, $component->{markedTemplate},
531 $signal_inits->{$component_key}, $component->{ssrDefaults},
532 16 );
533 }
534 }
535 }
536  
537 # Random suffix for a scope id with no slot to derive it from
538 # (`<Template>_<suffix>`). Always six digits: stringifying `rand()` and
539 # stripping its `0.` breaks when Perl prints a small value in exponent form
540 # (`3.2247e-05` -> `3.2247`), which put a `.` into the id. Every Perl-side
541 # producer of such an id calls this, so they cannot drift apart.
542 10013 ▶sub scope_id_suffix () {
Subroutine scope_id_suffix: called CC=1 SCAR=0.0
Pod undocumented
543 10013 return sprintf('%06d', int(rand(1_000_000)));
544 }
545  
546 # PascalCase → snake_case, mirroring the Mojo adapter's `toTemplateName`
547 # (prefix every uppercase letter with `_`, lowercase the whole string,
548 # strip the leading `_`): `ToastProvider` → `toast_provider`.
549 20 ▶sub _snake_case ($name) {
Subroutine _snake_case: called CC=1 SCAR=0.0
550 20 my $s = $name;
551 20 $s =~ s/([A-Z])/_$1/g;
552 20 $s = CORE::lc $s;
553 20 $s =~ s/^_//;
554 20 return $s;
555 }
556  
557 # Register one manifest-driven child renderer: `$slot_key` becomes the
558 # `render_child` name, `$marked` locates the template, and `$signal_init`
559 # / `$manifest_defaults` seed the child's template vars (see
560 # `register_components_from_manifest` for the contract).
561 23 ▶sub _register_manifest_child ($self, $slot_key, $marked, $signal_init, $manifest_defaults) {
Subroutine _register_manifest_child: called CC=3 SCAR=11.2
562 23 ▶ $marked //= '';
Condition100%2/2
$marked //= ""
l!l
221
MC/DC100%1/1
$marked //= ""
$marked
Truth table100%2/2
A
A= $marked
Aresult
11
00
563 23 ▶ return unless $marked;
Branch: 1 branch
BranchTrueFalseTotal
unless $marked 1 22 23
564 22 my $parent_scope = $self->_scope_id;
565 # Weaken the parent capture so the child-renderer closures stored on
566 # `$self->_child_renderers` don't keep `$self` alive (the direct
567 # closure <-> parent cycle). The controller is reached through `$parent`
568 # at call time rather than captured strongly here, so the closures hold
569 # no strong reference to `$c` either — see the controller-cycle note in
570 # `new`. `$parent` is always live whenever a closure runs (the closure is
571 # stored on `$parent`, so `$parent` outlives every invocation).
572 22 weaken(my $parent = $self);
573  
574 # `templates/ui/button/index.html.ep` → `ui/button/index`
575 22 my $template_name = $marked;
576 22 $template_name =~ s{^templates/}{};
577 22 $template_name =~ s{\.html\.ep$}{};
578  
579 10 ▶ $self->register_child_renderer($slot_key, sub {
Subroutine __ANON__: called CC=8 SCAR=21.9
580 # `$caller` is the instance whose template invoked
581 # `render_child` (#1897) — for a nested render that is a child
582 # instance, and the grandchild's scope/slot identity must chain
583 # off ITS scope id (`root_s0_s0`), not the registrant's.
584 10 my ($props, $caller) = @_;
585 10 ▶ my $host = $caller // $parent;
Condition33%1/3
$caller // $parent
l!l&&r!l&&!r
1000
MC/DC0%0/2
$caller // $parent
$caller $parent
Truth table33%1/3
A // B
A= $callerB= $parent
ABresult
1X1
011
000
586 10 ▶ my $host_scope = $host->_scope_id // $parent_scope;
Condition33%1/3
$host->_scope_id // $parent_scope
l!l&&r!l&&!r
1000
MC/DC0%0/2
$host->_scope_id // $parent_scope
$host->_scope_id $parent_scope
Truth table33%1/3
A // B
A= $host->_scope_idB= $parent_scope
ABresult
1X1
011
000
587 # Child shares the parent's backend so nested renders go
588 # through the same engine + controller (and inherit any
589 # injected json_encoder). The controller is fetched via the weak
590 # `$parent` at call time — never captured strongly — so the
591 # closure adds no edge to the per-request reference cycle.
592 10 my $child_bf = BarefootJS->new($parent->c, { backend => $parent->backend });
593 10 my $slot_id = delete $props->{_bf_slot};
594 # JSX `key` (a reserved prop) → data-key on the child's scope root
595 # for keyed-loop reconciliation (see `data_key_attr`).
596 10 my $data_key = delete $props->{key};
597 10 ▶ $child_bf->_data_key($data_key) unless _nullish($data_key);
Branch: 1 branch
BranchTrueFalseTotal
unless _nullish($data_key) 0 10 10
598 10 ▶ $child_bf->_scope_id(
Branch: 1 branch
BranchTrueFalseTotal
$slot_id ? : 0 10 10
599 $slot_id ? $host_scope . '_' . $slot_id
600 : $template_name . '_' . scope_id_suffix()
601 );
602 10 $child_bf->_is_child(1);
603 # (#1249) Slot identity: host scope + slot id. Emitted as
604 # bf-h / bf-m attributes by hydration_attrs.
605 10 ▶ if ($slot_id) {
Branch: 1 branch
BranchTrueFalseTotal
if ($slot_id) 0 10 10
606 0 $child_bf->_bf_parent($host_scope);
607 0 $child_bf->_bf_mount($slot_id);
608 }
609 # Share the root registry so the child's own template can
610 # render further imported components (#1897).
611 10 $child_bf->_child_renderers($parent->_child_renderers);
612 10 $child_bf->_scripts($parent->_scripts);
613 10 $child_bf->_script_seen($parent->_script_seen);
614 10 $child_bf->_preloads($parent->_preloads);
615 10 $child_bf->_preload_seen($parent->_preload_seen);
616 # Shares the SAME root-level arrayref as `_scripts` above — every
617 # child renderer registered here closes over `$parent` (the
618 # instance `register_components_from_manifest` was called on, the
619 # page root), so this reaches ANY "use client" nesting depth for
620 # free, unlike the Go adapter's `PropagatePortals`, which needed an
621 # explicit recursive walk because Go structs copy fields by value
622 # rather than sharing a mutable reference (#3119).
623 10 $child_bf->_portal_elements($parent->_portal_elements);
624  
625 10 my %extra;
626 10 ▶ if ($signal_init) {
Branch: 2 branches
BranchTrueFalseTotal
if ($signal_init) { } 1 9 10
elsif ($manifest_defaults) { } 9 0 9
627 1 %extra = $signal_init->($props);
628 } elsif ($manifest_defaults) {
629 9 %extra = _derive_stash_from_defaults($manifest_defaults, $props);
630 }
631  
632 # Render the child template with $child_bf bound as the active
633 # instance for the nested render. The backend owns the
634 # engine-specific binding + restore (stash juggle for Mojo).
635 10 my $html = $parent->backend->render_named(
636 $template_name, $child_bf, { %$props, %extra },
637 );
638 10 chomp $html;
639 10 return $html;
640 22 });
641 }
642  
643 # Derive template-stash kvs from a manifest entry's `ssrDefaults`
644 # section. Each entry shape:
645 # { value => <static-fallback>, propName => <prop>, isRestProps => bool }
646 # For `isRestProps`, the rest bag passes through unchanged (or the
647 # static `{}` if the caller didn't supply one). For ordinary entries
648 # the caller's `$props->{propName}` wins when present -- `undef` (JS `null`)
649 # included -- and an absent or `UNDEF` prop takes the static `value`, or
650 # `UNDEF` when the entry has none (the manifest writes `value` only for a
651 # prop with a default; spec/js-undefined-value.md, decision 6).
652 # `propName`-less entries (signal / memo locals) always use the static
653 # value — the caller cannot override them.
654 21 ▶sub _derive_stash_from_defaults ($defaults, $props) {
Subroutine _derive_stash_from_defaults: called CC=8 SCAR=21.0
655 21 my %extra;
656 21 for my $name (keys %$defaults) {
657 37 my $d = $defaults->{$name};
658 37 ▶ if (ref($d) ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $d ne "HASH") 0 37 37
659 0 $extra{$name} = BarefootJS::Undefined::decode_undefined($d);
660 0 next;
661 }
662 37 ▶ if ($d->{isRestProps}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($d->{"isRestProps"}) 4 33 37
663 4 ▶ $extra{$name} = exists $props->{$name} ? $props->{$name} : _static_fallback($d);
Branch: 1 branch
BranchTrueFalseTotal
exists $props->{$name} ? : 1 3 4
664 4 next;
665 }
666 33 my $prop_name = $d->{propName};
667 33 ▶ if (defined $prop_name && exists $props->{$prop_name} && !_undef_p($props->{$prop_name})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $prop_name and exists $props->{$prop_name} and not _undef_p($props->{$prop_name})) { } 6 27 33
Condition83%5/6
defined $prop_name and exists $props->{$prop_name} and not _undef_p($props->{$prop_name})
!ll&&!rl&&r
2436
defined $prop_name and exists $props->{$prop_name}
!ll&&!rl&&r
0249
MC/DC66%2/3
defined $prop_name and exists $props->{$prop_name} and not _undef_p($props->{$prop_name})
defined $prop_name exists $props->{$prop_name} not _undef_p($props->{$prop_name})
Truth table75%3/4
A and B and not(C)
A= defined $prop_nameB= exists $props->{$prop_name}C= not _undef_p($props->{$prop_name})
ABCresult
0XX0
10X0
1100
1111
668 6 $extra{$name} = $props->{$prop_name};
669 } else {
670 27 $extra{$name} = _static_fallback($d);
671 }
672 }
673 21 return %extra;
674 }
675  
676 # An `ssrDefaults` entry's seed when the caller's prop is absent or `UNDEF`:
677 # its `value` (a `{"$undef": true}` sentinel in it is `UNDEF`), or `UNDEF`
678 # when it has none.
679 30 ▶sub _static_fallback ($d) {
Subroutine _static_fallback: called CC=2 SCAR=6.9
680 30 ▶ return exists $d->{value} ? BarefootJS::Undefined::decode_undefined($d->{value}) : $UNDEF;
Branch: 1 branch
BranchTrueFalseTotal
exists $d->{'value'} ? : 21 9 30
681 }
682  
683 # ---------------------------------------------------------------------------
684 # Script Output
685 # ---------------------------------------------------------------------------
686  
687 0 ▶sub scripts ($self) {
Subroutine scripts: not called CC=3 SCAR=24.8
Pod undocumented
688 0 my @tags;
689 # Preload hints BEFORE script tags — a hint that arrives after the
690 # script it describes is useless. Same escaping (none; paths are
691 # caller-trusted resolved URLs) as the script tags below.
692 0 for my $path (@{$self->_preloads}) {
693 0 push @tags, qq{<link rel="modulepreload" crossorigin href="$path">};
694 }
695 0 for my $path (@{$self->_scripts}) {
696 0 push @tags, qq{<script type="module" src="$path"></script>};
697 }
698 0 return join("\n", @tags);
699 }
700  
701 # ---------------------------------------------------------------------------
702 # Streaming SSR (Out-of-Order)
703 # ---------------------------------------------------------------------------
704  
705 0 ▶sub streaming_bootstrap ($self) {
Subroutine streaming_bootstrap: not called CC=1 SCAR=6.9
Pod undocumented
706 0 return q{<script>(function(){function s(id){var a=document.querySelector('[bf-async="'+id+'"]');var t=document.querySelector('template[bf-async-resolve="'+id+'"]');if(!a||!t)return;a.replaceChildren(t.content.cloneNode(true));a.removeAttribute('bf-async');t.remove();requestAnimationFrame(function(){if(window.__bf_hydrate)window.__bf_hydrate()})};window.__bf_swap=s})()</script>};
707 }
708  
709 0 ▶sub async_boundary ($self, $id, $fallback_html) {
Subroutine async_boundary: not called CC=1 SCAR=6.9
Pod undocumented
710 # The fallback comes in via Mojo `begin %>...<% end` capture (see
711 # MojoAdapter::renderAsync), which produces a CODE ref returning a
712 # Mojo::ByteStream. Materialize it through the backend so the rendered
713 # HTML embeds in the placeholder rather than the CODE ref's
714 # stringification.
715 0 $fallback_html = $self->backend->materialize($fallback_html);
716 0 return qq{<div bf-async="$id">$fallback_html</div>};
717 }
718  
719 0 ▶sub async_resolve ($self, $id, $content_html) {
Subroutine async_resolve: not called CC=1 SCAR=6.9
Pod undocumented
720 0 return qq{<template bf-async-resolve="$id">$content_html</template><script>__bf_swap("$id")</script>};
721 }
722  
723 # ---------------------------------------------------------------------------
724 # JS-compat callees (#1189) — invoked from generated Mojo templates as
725 # <%= bf->json($val) %>, <%= bf->floor($val) %>, etc. The MojoAdapter's
726 # `templatePrimitives` registry emits these helper calls in place of the
727 # corresponding JS callees (`JSON.stringify`, `Math.floor`, …) so the SSR
728 # template can render value-equivalent output without a JS engine.
729 #
730 # Failure policy mirrors the Go adapter (#1188): user-data marshalling
731 # (json) bubbles errors so Mojolicious aborts loudly on cycles /
732 # unsupported values rather than silently producing an empty payload.
733 # Numeric coercion follows JS semantics (NaN propagates as the special
734 # string 'NaN'; non-numeric input returns 'NaN' rather than 0). Strings
735 # always coerce to a string representation.
736 # ---------------------------------------------------------------------------
737  
738 67 ▶sub json ($self, $value) {
Subroutine json: called CC=9 SCAR=22.0
Pod undocumented
739 # `JSON.stringify`: `null` (`undef`) is "null"; `undefined` (`UNDEF`)
740 # gives no string at the top level -- the result is `UNDEF` itself,
741 # which prints nothing and omits an attribute -- an object member
742 # holding it is skipped, and an array element holding it is written as
743 # `null`.
744 #
745 # A number is written as JS writes it (`_format_number`): shortest
746 # round-trip digits, `-0` as `0`, an unpadded exponent (`-4e-8`,
747 # `-4e+21`), and NaN / Infinity as `null`, at any depth (#3787). The
748 # encoders print `%.15g` (`0.3` for `0.1 + 0.2`), pad the exponent
749 # (`-4e-08`) and spell Infinity `-Inf` or `"-Inf"`. Arrays and hashes
750 # are walked here with sorted keys, as the canonical encoders do;
751 # strings and other leaves go through the backend's encoder (Mojo's
752 # `to_json` returns a character string, suitable for embedding in HTML
753 # output via Mojo::ByteStream / `<%==`).
754 67 ▶ return $value if _undef_p($value);
Branch: 1 branch
BranchTrueFalseTotal
if _undef_p($value) 1 66 67
755 66 my $ref = ref $value;
756 66 ▶ return '[' . CORE::join(',', map { _undef_p($_) ? 'null' : $self->json($_) } @$value) . ']' if $ref eq 'ARRAY';
Branch: 2 branches
BranchTrueFalseTotal
if $ref eq "ARRAY" 14 52 66
_undef_p($_) ? : 1 37 38
757 52 ▶ if ($ref eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref eq "HASH") 6 46 52
758 return '{' . CORE::join(',', map {
759 6 $self->backend->encode_json("$_") . ':' . $self->json($value->{$_})
760 6 } grep { !_undef_p($value->{$_}) } sort keys %$value) . '}';
761 }
762 46 ▶ if (_json_is_number($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_json_is_number($value)) 27 19 46
763 27 my $n = BarefootJS::Evaluator::_double($value + 0);
764 27 ▶ return 'null' if $n != $n || $n == 9**9**9 || $n == -(9**9**9);
Branch: 1 branch
BranchTrueFalseTotal
if $n != $n or $n == "Inf" or $n == "-Inf" 5 22 27
Condition100%6/6
$n != $n or $n == "Inf" or $n == "-Inf"
l!l&&r!l&&!r
2322
$n != $n or $n == "Inf"
l!l&&r!l&&!r
1125
MC/DC100%3/3
$n != $n or $n == "Inf" or $n == "-Inf"
$n != $n $n == "Inf" $n == "-Inf"
Truth table100%4/4
A or B or C
A= $n != $nB= $n == "Inf"C= $n == "-Inf"
ABCresult
1XX1
01X1
0011
0000
765 22 return BarefootJS::Evaluator::_format_number($n);
766 }
767 19 return $self->backend->encode_json($value);
768 }
769  
770 # Whether `json` writes $value as a JSON number. Decided from the scalar's
771 # flags the way JSON::PP / Cpanel::JSON::XS do: a scalar carrying a public
772 # string flag (SVf_POK) is a string, even after a numeric comparison has
773 # cached a number on it (`"1e5" < 0` leaves IOK/NOK set), so a JSON string
774 # prop keeps its quotes whatever the template compared it with. A number
775 # that was only stringified keeps the private flag alone (Perl 5.36+) and
776 # stays a number.
777 # `$value` as `JSON.stringify` sees it, for a host encoder: a member holding
778 # `undefined` is dropped and an `undefined` element is `null`, at any depth.
779 # The encoder (JSON::PP dies on `UNDEF`, Mojo::JSON writes `""`) never
780 # receives `UNDEF`. A JSON boolean and any other leaf pass through.
781 12 ▶sub _json_ready ($value) {
Subroutine _json_ready: called CC=5 SCAR=16.2
782 12 my $ref = ref $value;
783 12 ▶ if ($ref eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref eq "HASH") 5 7 12
784 5 return { map { ($_ => _json_ready($value->{$_})) } grep { !_undef_p($value->{$_}) } keys %$value };
785 }
786 7 ▶ if ($ref eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref eq "ARRAY") 2 5 7
787 2 ▶ return [ map { _undef_p($_) ? undef : _json_ready($_) } @$value ];
Branch: 1 branch
BranchTrueFalseTotal
_undef_p($_) ? : 2 0 2
788 }
789 5 ▶ return undef if _undef_p($value);
Branch: 1 branch
BranchTrueFalseTotal
if _undef_p($value) 0 5 5
790 5 return $value;
791 }
792  
793 46 ▶sub _json_is_number ($value) {
Subroutine _json_is_number: called CC=5 SCAR=16.1
794 46 ▶ return 0 if !defined $value || ref $value;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $value or ref $value 11 35 46
Condition100%3/3
not defined $value or ref $value
l!l&&r!l&&!r
4735
MC/DC100%2/2
not defined $value or ref $value
not defined $value ref $value
Truth table100%3/3
not(A) or B
A= not defined $valueB= ref $value
ABresult
1X1
011
000
795 35 my $flags = B::svref_2object(\$value)->FLAGS;
796 35 ▶ return 0 if $flags & B::SVf_POK;
Branch: 1 branch
BranchTrueFalseTotal
if $flags & 1024 8 27 35
797 27 ▶ return ($flags & (B::SVp_IOK | B::SVp_NOK)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$flags & 12288 ? : 27 0 27
798 }
799  
800 38 ▶sub string ($self, $value) {
Subroutine string: called CC=6 SCAR=18.0
Pod undocumented
801 # JS `String(v)` mirror for a display sink. `undef` (`null`) and `UNDEF`
802 # (`undefined`) render as the empty string here, as JSX renders them in a
803 # text or attribute position -- same divergence the Go adapter documents
804 # for `bf_string`. JS ToString itself is `to_string`.
805 38 ▶ return '' if _nullish($value);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($value) 6 32 38
806 # JS `Array.prototype.toString` is `this.join(',')`, applied
807 # recursively — a bare `"$value"` interpolation would otherwise
808 # stringify an ARRAY ref as its Perl memory address
809 # ("ARRAY(0x...)") instead of the JS comma-join. Reached via
810 # `.flat(0)`'s shallow copy stringified afterwards (#2262, shared
811 # with Mojolicious/Xslate via this runtime).
812 0 ▶ return CORE::join(',', map { $self->string($_) } @$value) if ref($value) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $value eq "ARRAY" 0 32 32
813 # A JSON boolean prints as JS does (`true` / `false`), not as the `1` /
814 # `0` its numeric overload yields (#3440).
815 32 ▶ return $value ? 'true' : 'false' if _is_json_bool($value);
Branch: 2 branches
BranchTrueFalseTotal
if _is_json_bool($value) 3 29 32
$value ? : 2 1 3
816 # A number prints as JS `Number::toString` does, not with Perl's `%.15g`
817 # (#3380); a string passes through unchanged.
818 29 ▶ return BarefootJS::Evaluator::_format_number($value + 0) if BarefootJS::Evaluator::_is_number($value);
Branch: 1 branch
BranchTrueFalseTotal
if BarefootJS::Evaluator::_is_number($value) 22 7 29
819 7 return "$value";
820 }
821  
822 # A JS boolean as a value the JSON encoder writes as `true` / `false`
823 # (`JSON.stringify([n, true])`): Perl holds a boolean as `1` / `''` / `0`,
824 # which encodes as a number or a string.
825 9 ▶sub boolean ($self, $value) {
Subroutine boolean: called CC=2 SCAR=6.9
Pod undocumented
826 9 ▶ return $value ? JSON::PP::true() : JSON::PP::false();
Branch: 1 branch
BranchTrueFalseTotal
$value ? : 4 5 9
827 }
828  
829 # A JSX text child's value: JSX renders nothing for a boolean (#3824 step 5).
830 # Perl holds a comparison as `1` / `''`, so only a JSON boolean is one here:
831 # the compiler materializes every boolean a displayed value can be with
832 # `boolean` first. Any other value passes through to the text sink.
833 6 ▶sub display ($self, $value) {
Subroutine display: called CC=2 SCAR=6.9
Pod undocumented
834 6 ▶ return _is_json_bool($value) ? '' : $value;
Branch: 1 branch
BranchTrueFalseTotal
_is_json_bool($value) ? : 3 3 6
835 }
836  
837 # A decoded JSON boolean (`Mojo::JSON::true` / `false`, a `JSON::PP::Boolean`).
838 38 ▶sub _is_json_bool ($value) {
Subroutine _is_json_bool: called CC=2 SCAR=7.1
839 38 my $ref = ref($value);
840 38 ▶ return $ref eq 'JSON::PP::Boolean' || $ref eq 'Mojo::JSON::_Bool';
Condition66%2/3
$ref eq 'JSON::PP::Boolean' || $ref eq 'Mojo::JSON::_Bool'
l!l&&r!l&&!r
6032
MC/DC50%1/2
$ref eq 'JSON::PP::Boolean' || $ref eq 'Mojo::JSON::_Bool'
$ref eq 'JSON::PP::Boolean' $ref eq 'Mojo::JSON::_Bool'
Truth table66%2/3
A || B
A= $ref eq 'JSON::PP::Boolean'B= $ref eq 'Mojo::JSON::_Bool'
ABresult
1X1
011
000
841 }
842  
843 7 ▶sub number ($self, $value) {
Subroutine number: called CC=3 SCAR=11.0
Pod undocumented
844 # JS `Number(v)` mirror. Numeric coerces via Perl's implicit
845 # numeric context; non-numeric / undef yield real numeric NaN
846 # (`'nan' + 0`) so downstream arithmetic propagates correctly
847 # (`Math.floor(NaN) === NaN`). Returning the literal string
848 # "NaN" would conflate the user-passing-the-string-"NaN" case
849 # with the parse-failure case, and break NaN detection in
850 # downstream helpers.
851 7 ▶ return 0 + 'nan' if _nullish($value);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($value) 3 4 7
852 4 ▶ return $value + 0 if looks_like_number($value);
Branch: 1 branch
BranchTrueFalseTotal
if &looks_like_number($value) 3 1 4
853 1 return 0 + 'nan';
854 }
855  
856 # JS `+` / `-` / `*` / `/` over numbers (#3454). The adapters emit these
857 # instead of Perl's native operators so the result is the IEEE double JS
858 # computes: a 64-bit IV sum past 2**53 rounds as a double, a perl with a
859 # wider NV (-Duselongdouble / -Dusequadmath) rounds to the double JS has,
860 # and division by zero yields +/-Infinity or NaN instead of dying. Each
861 # operand goes through JS ToNumber (`_num`): `undef` (`null`) is 0, `UNDEF`
862 # (`undefined`) NaN, a string its JS numeric value.
863 52 ▶sub _as_double { unpack('d', pack('d', $_[0])) }
Subroutine _as_double: called CC=1 SCAR=0.0
864 46 ▶sub _num { _as_double(_js_number($_[0])) }
Subroutine _num: called CC=1 SCAR=0.0
865  
866 0 ▶sub add ($self, $l, $r) {
Subroutine add: not called CC=1 SCAR=6.9
Pod undocumented
867 0 return _as_double(_num($l) + _num($r));
868 }
869  
870 2 ▶sub subtract ($self, $l, $r) {
Subroutine subtract: called CC=1 SCAR=0.0
Pod undocumented
871 2 return _as_double(_num($l) - _num($r));
872 }
873  
874 2 ▶sub multiply ($self, $l, $r) {
Subroutine multiply: called CC=1 SCAR=0.0
Pod undocumented
875 2 return _as_double(_num($l) * _num($r));
876 }
877  
878 7 ▶sub divide ($self, $l, $r) {
Subroutine divide: called CC=1 SCAR=0.0
Pod undocumented
879 7 return BarefootJS::Evaluator::_divide(_num($l), _num($r));
880 }
881  
882 # JS `%` (#3474): the truncated remainder, which takes the dividend's sign
883 # (`-7 % 2` is -1) and keeps a fraction. Perl's native `%` floors (`-7 % 2`
884 # is 1) and converts both operands to integers (`NaN % 2` is 0).
885 12 ▶sub mod ($self, $l, $r) {
Subroutine mod: called CC=1 SCAR=0.0
Pod undocumented
886 12 return BarefootJS::Evaluator::_remainder(_num($l), _num($r));
887 }
888  
889 # NaN is the only float for which `$x != $x` holds. Used as the
890 # portable sentinel check in floor/ceil/round. The `Math` helpers coerce
891 # through JS ToNumber (`null` is 0, `undefined` NaN), as `Math.floor(null)`
892 # is 0.
893 128 ▶sub _is_nan { my $n = shift; return $n != $n }
Subroutine _is_nan: called CC=1 SCAR=0.0
894  
895 # True for +/-Infinity. `9**9**9` is Perl's portable infinity literal; a
896 # finite number is always strictly less than +Inf in magnitude.
897 1 ▶sub _is_inf { my $n = shift; return $n == 9**9**9 || $n == -9**9**9 }
Subroutine _is_inf: called CC=2 SCAR=8.1
Condition33%1/3
$n == 9**9**9 || $n == -9**9**9
l!l&&r!l&&!r
001
MC/DC0%0/2
$n == 9**9**9 || $n == -9**9**9
$n == 9**9**9 $n == -9**9**9
Truth table33%1/3
A || B
A= $n == 9**9**9B= $n == -9**9**9
ABresult
1X1
011
000
898  
899 5 ▶sub floor ($self, $value) {
Subroutine floor: called CC=2 SCAR=6.9
Pod undocumented
900 5 my $n = _js_number($value);
901 5 ▶ return $n if _is_nan($n);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($n) 2 3 5
902 3 return POSIX::floor($n);
903 }
904  
905 3 ▶sub ceil ($self, $value) {
Subroutine ceil: called CC=2 SCAR=6.9
Pod undocumented
906 3 my $n = _js_number($value);
907 3 ▶ return $n if _is_nan($n);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($n) 1 2 3
908 2 return POSIX::ceil($n);
909 }
910  
911 5 ▶sub round ($self, $value) {
Subroutine round: called CC=2 SCAR=6.9
Pod undocumented
912 5 my $n = _js_number($value);
913 5 ▶ return $n if _is_nan($n);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($n) 1 4 5
914 # POSIX has no `round`. JS `Math.round` rounds half toward
915 # +Infinity (so `Math.round(-1.5) === -1`, not -2). `floor(n
916 # + 0.5)` reproduces that for both signs.
917 4 return POSIX::floor($n + 0.5);
918 }
919  
920 # `Math.min(a, b)` / `Math.max(a, b)` -- two-arg forms only (#2168
921 # math-methods). JS returns NaN if either operand is NaN.
922 5 ▶sub min ($self, $a, $b) {
Subroutine min: called CC=4 SCAR=13.9
Pod undocumented
923 5 my $x = _js_number($a);
924 5 my $y = _js_number($b);
925 5 ▶ return $x if _is_nan($x);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($x) 1 4 5
926 4 ▶ return $y if _is_nan($y);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($y) 1 3 4
927 3 ▶ return $x < $y ? $x : $y;
Branch: 1 branch
BranchTrueFalseTotal
$x < $y ? : 1 2 3
928 }
929  
930 5 ▶sub max ($self, $a, $b) {
Subroutine max: called CC=4 SCAR=13.9
Pod undocumented
931 5 my $x = _js_number($a);
932 5 my $y = _js_number($b);
933 5 ▶ return $x if _is_nan($x);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($x) 1 4 5
934 4 ▶ return $y if _is_nan($y);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($y) 1 3 4
935 3 ▶ return $x > $y ? $x : $y;
Branch: 1 branch
BranchTrueFalseTotal
$x > $y ? : 2 1 3
936 }
937  
938 # `Math.abs()` (#2168 math-methods). `CORE::abs` avoids Perl's
939 # ambiguous-call warning against this package's own `abs` sub.
940 4 ▶sub abs ($self, $value) {
Subroutine abs: called CC=2 SCAR=6.9
Pod undocumented
941 4 my $n = _js_number($value);
942 4 ▶ return $n if _is_nan($n);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($n) 1 3 4
943 3 return CORE::abs($n);
944 }
945  
946 # `date($recv, $op)` -- zero-arg `Date.prototype` method lowering (#2274,
947 # spec entry "date"). `$recv` arrives as either a `BarefootJS::Date` (this
948 # runtime's own epoch-ms wrapper, below) or an ISO-8601 string (a template
949 # prop may carry either depending on how the host populated it); both
950 # normalize to a single epoch-ms integer via `_date_epoch_ms` before
951 # dispatch. `gmtime`'s `mon` field (index 4) is ALREADY 0-based in Perl
952 # (unlike every other backend's native month accessor), so — uniquely among
953 # this catalogue's ports — `getUTCMonth` needs NO -1. `getTime` is the exact
954 # epoch-ms integer already carried by `$recv`/parsed from the string, so it
955 # needs no float rounding even for a pre-epoch instant.
956 0 ▶sub date ($self, $recv, $op) {
Subroutine date: not called CC=11 SCAR=48.8
Pod undocumented
957 0 my $ms = _date_epoch_ms($recv);
958 0 ▶ return $op eq 'toISOString' ? '' : 0 unless defined $ms;
Branch: 2 branches
BranchTrueFalseTotal
unless defined $ms 0 0 0
$op eq 'toISOString' ? : 0 0 0
959 0 ▶ return $ms if $op eq 'getTime';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "getTime" 0 0 0
960  
961 # Floor (not truncate) toward -Infinity: Perl's `/` truncates toward
962 # zero, which would round a negative ms value (e.g. -14182939877) up to
963 # the wrong whole second (-14182939 instead of -14182940).
964 0 my $sec = POSIX::floor($ms / 1000);
965 0 my $msec = $ms - ($sec * 1000);
966 0 my @t = gmtime($sec); # (sec,min,hour,mday,mon,year,...) -- mon is 0-based
967  
968 0 ▶ return $t[5] + 1900 if $op eq 'getUTCFullYear';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "getUTCFullYear" 0 0 0
969 0 ▶ return $t[4] if $op eq 'getUTCMonth'; # already 0-based, no -1
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "getUTCMonth" 0 0 0
970 0 ▶ return $t[3] if $op eq 'getUTCDate';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "getUTCDate" 0 0 0
971 0 ▶ return $t[2] if $op eq 'getUTCHours';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "getUTCHours" 0 0 0
972 0 ▶ return $t[1] if $op eq 'getUTCMinutes';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "getUTCMinutes" 0 0 0
973 0 ▶ return $t[0] if $op eq 'getUTCSeconds';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "getUTCSeconds" 0 0 0
974 0 ▶ return POSIX::strftime('%Y-%m-%dT%H:%M:%S', @t) . sprintf('.%03dZ', $msec)
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "toISOString" 0 0 0
975 if $op eq 'toISOString';
976 0 return 0;
977 }
978  
979 # Normalizes a `date()` receiver to a single epoch-ms integer: a
980 # `BarefootJS::Date` (unwraps `epoch_ms` directly) or an ISO-8601 string
981 # (`YYYY-MM-DDTHH:MM:SS[.sss]Z`, the exact shape every ISO string this
982 # runtime itself ever produces via `toISOString` above, and the shape the
983 # golden vectors exercise). `Time::Local::timegm_modern` (core since
984 # Time::Local 1.27, like `POSIX`) converts the broken-down UTC fields to
985 # epoch SECONDS correctly across the full pre-1970/post-2038 range on a
986 # 64-bit `time_t` build; unlike the legacy `timegm`, it takes `$y` as a
987 # literal calendar year with no two-digit-year windowing heuristic — the
988 # regex above always captures a 4-digit year, so that heuristic would only
989 # ever be a latent footgun here, never a real branch. The optional
990 # millisecond group defaults to 0. Returns `undef` for anything else
991 # (unparsable string, wrong type) so `date` can apply its documented
992 # zero-value fallback instead of dying mid-render.
993 10 ▶sub _date_epoch_ms ($recv) {
Subroutine _date_epoch_ms: called CC=6 SCAR=18.6
994 10 ▶ if (ref($recv) eq 'BarefootJS::Date') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $recv eq "BarefootJS::Date") 0 10 10
995 0 return $recv->{epoch_ms};
996 }
997 10 ▶ return undef if ref($recv);
Branch: 1 branch
BranchTrueFalseTotal
if ref $recv 0 10 10
998 10 ▶ return undef unless defined $recv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $recv 1 9 10
999 9 ▶ return undef unless $recv =~ /\A(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{3}))?Z\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $recv =~ /\A(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{3}))?Z\z/ 1 8 9
1000 8 ▶ my ($y, $mon, $day, $h, $min, $s, $ms) = ($1, $2, $3, $4, $5, $6, $7 // 0);
Condition50%1/2
$7 // 0
l!l
80
MC/DC0%0/1
$7 // 0
$7
Truth table50%1/2
A
A= $7
Aresult
11
00
1001 8 my $epoch_s = Time::Local::timegm_modern($s, $min, $h, $day, $mon - 1, $y);
1002 8 return $epoch_s * 1000 + $ms;
1003 }
1004  
1005 # `format_date($recv, $pattern, $tz, $names)` -- pure, explicit-timezone
1006 # date formatter (#2324, #2334, spec entry "format_date"). Same receiver
1007 # contract as `date` (a `BarefootJS::Date`, an ISO-8601 string, or
1008 # undef/unparseable -> ''), then pure pattern substitution over the
1009 # shifted instant. Mirrors packages/client/src/format-date.ts
1010 # byte-for-byte -- deterministic, no locale, no host TZ, no `time()`.
1011 #
1012 # `$tz` (#2344) is 'UTC', a range-valid fixed offset `±HH:MM` (hours
1013 # 00-23, minutes 00-59), or a canonical IANA zone name ('Asia/Tokyo')
1014 # resolved through tzdata via DateTime::TimeZone -- the zone's UTC
1015 # offset AT THE INSTANT being formatted (DST-aware,
1016 # historical-transition-aware, seconds precision: pre-standard LMT
1017 # offsets like Tokyo's +09:18:59 count). Anything unresolvable -- an
1018 # unknown zone, a malformed or out-of-range offset ('+9:00', '+25:00'
1019 # fall through to the zone lookup), DateTime::TimeZone's implicit
1020 # 'local'/'floating' specials -- DIES, aborting the render loudly: the
1021 # JS reference throws a RangeError there, and a silently substituted
1022 # timezone is the one failure mode this helper must not have (the
1023 # pre-#2344 normalize-to-UTC total function is gone). The receiver
1024 # contract still precedes tz validation (undef/unparseable -> '').
1025 #
1026 # The shifted instant's UTC calendar fields come from the same
1027 # floor-toward-negative-infinity + `gmtime` discipline as `date` above
1028 # (Perl's `/` truncates toward zero, which mis-floors negative ms), and
1029 # `gmtime`'s 0-based `mon` needs +1 here (unlike `getUTCMonth` in `date`,
1030 # because the pattern token `M`/`MM` is the 1-based JS `Date` display
1031 # month, not the raw accessor value). `gmtime`'s `wday` (element 6) is
1032 # already 0-based Sunday-first, matching JS `getUTCDay()` and the
1033 # `$names` table's weekday section layout -- both read off the same
1034 # offset-shifted `gmtime` call, so pre-1970 instants get the identical
1035 # floor-division-derived weekday as the numeric tokens.
1036 #
1037 # `$names` (#2334) is an arrayref of strings in fixed flat layout:
1038 # [0..11] wide months, [12..23] abbreviated months, [24..30] wide
1039 # weekdays (Sunday-first), [31..37] abbreviated weekdays. A name token
1040 # indexing a missing entry, or given an undef/short/absent table, renders
1041 # '' (defined-or guard) -- never dies.
1042 #
1043 # Token substitution mirrors the JS reference exactly: `s///ge` over the
1044 # `YYYY|MMMM|MMM|MM|DD|dddd|ddd|M|D` alternation (longest-match order so
1045 # e.g. `MMMM` binds before `MMM`/`MM`/`M`, `dddd` before `ddd`), any other
1046 # character (including multi-byte literals) passes through untouched.
1047 # `YYYY` is `abs(year)` zero-padded to (at least) 4 digits, `-`-prefixed
1048 # when the year is negative; `MM`/`DD` zero-pad to 2; `M`/`D` are bare.
1049 10 ▶sub format_date ($self, $recv, $pattern, $tz, $names = []) {
Subroutine format_date: called CC=15 SCAR=32.1
Pod undocumented
1050 10 my $ms = _date_epoch_ms($recv);
1051 10 ▶ return '' unless defined $ms;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ms 2 8 10
1052  
1053 8 my $offset_seconds = 0;
1054 8 ▶ if ($tz ne 'UTC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($tz ne "UTC") 8 0 8
1055 8 ▶ if ($tz =~ /^([+-])([01][0-9]|2[0-3]):([0-5][0-9])$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tz =~ /^([+-])([01][0-9]|2[0-3]):([0-5][0-9])$/) { } 0 8 8
1056 0 ▶ $offset_seconds = ($1 eq '-' ? -1 : 1) * ($2 * 3600 + $3 * 60);
Branch: 1 branch
BranchTrueFalseTotal
$1 eq '-' ? : 0 0 0
1057 }
1058 else {
1059 8 $offset_seconds = _format_date_zone_offset($tz, $ms);
1060 }
1061 }
1062  
1063 1 my $shifted = $ms + $offset_seconds * 1000;
1064 1 my $sec = POSIX::floor($shifted / 1000);
1065 1 my @t = gmtime($sec); # (sec,min,hour,mday,mon,year,wday,...) -- mon/wday are 0-based
1066  
1067 1 my $year = $t[5] + 1900;
1068 1 my $month = $t[4] + 1; # 1-based JS display month, unlike getUTCMonth in `date`
1069 1 my $day = $t[3];
1070 1 my $weekday = $t[6]; # 0 = Sunday, matching the $names table's Sunday-first layout
1071 1 ▶ my $yyyy = ($year < 0 ? '-' : '') . sprintf('%04d', CORE::abs($year));
Branch: 1 branch
BranchTrueFalseTotal
$year < 0 ? : 0 1 1
1072 1 my $mm = sprintf('%02d', $month);
1073 1 my $dd = sprintf('%02d', $day);
1074 0 ▶ my $name_at = sub ($index) { $names->[$index] // '' };
Subroutine __ANON__: not called CC=2 SCAR=13.0
Condition0%0/2
$names->[$index] // ""
l!l
00
MC/DC0%0/1
$names->[$index] // ""
$names->[$index]
Truth table0%0/2
A
A= $names->[$index]
Aresult
11
00
1075  
1076 1 (my $out = $pattern) =~ s/YYYY|MMMM|MMM|MM|DD|dddd|ddd|M|D/
1077 3 ▶ $& eq 'YYYY' ? $yyyy
Branch: 8 branches
BranchTrueFalseTotal
$& eq 'YYYY' ? : 1 2 3
$& eq 'MMMM' ? : 0 2 2
$& eq 'MMM' ? : 0 2 2
$& eq 'MM' ? : 1 1 2
$& eq 'DD' ? : 1 0 1
$& eq 'dddd' ? : 0 0 0
$& eq 'ddd' ? : 0 0 0
$& eq 'M' ? : 0 0 0
1078 : $& eq 'MMMM' ? $name_at->($month - 1)
1079 : $& eq 'MMM' ? $name_at->(12 + $month - 1)
1080 : $& eq 'MM' ? $mm
1081 : $& eq 'DD' ? $dd
1082 : $& eq 'dddd' ? $name_at->(24 + $weekday)
1083 : $& eq 'ddd' ? $name_at->(31 + $weekday)
1084 : $& eq 'M' ? $month
1085 : $day
1086 /gex;
1087 1 return $out;
1088 }
1089  
1090 # Minimal `utc_rd_values`/`utc_year` provider so
1091 # `DateTime::TimeZone->offset_for_datetime` can resolve an offset for a raw
1092 # epoch instant without pulling the full DateTime object model into this
1093 # runtime (its documented duck-type contract is exactly these two methods).
1094 # RD day 719163 is 1970-01-01; the floor-division discipline matches
1095 # `format_date`'s own pre-1970 handling.
1096 17 package BarefootJS::_TZProbe {
1097  
1098 1 ▶ sub new ($class, $epoch_s) {
Subroutine new: called CC=1 SCAR=0.0
1099 1 my $days = POSIX::floor($epoch_s / 86400);
1100 1 my @t = gmtime($epoch_s);
1101 1 return bless {
1102 rd_days => $days + 719_163,
1103 rd_secs => $epoch_s - $days * 86400,
1104 year => $t[5] + 1900,
1105 }, $class;
1106 }
1107  
1108 0 ▶ sub utc_rd_values ($self) { return ($self->{rd_days}, $self->{rd_secs}, 0) }
Subroutine utc_rd_values: not called CC=1 SCAR=6.9
1109 0 ▶ sub utc_year ($self) { return $self->{year} }
Subroutine utc_year: not called CC=1 SCAR=6.9
1110  
1111 1 ▶ sub utc_rd_as_seconds ($self) {
Subroutine utc_rd_as_seconds: called CC=1 SCAR=0.0
1112 1 return $self->{rd_days} * 86400 + $self->{rd_secs};
1113 }
1114 }
1115  
1116 # Resolve a canonical IANA zone name's UTC offset (whole seconds) at the
1117 # epoch-ms instant through DateTime::TimeZone (#2344). Loaded lazily so the
1118 # 'UTC'/fixed-offset paths -- and every other helper -- keep working on a
1119 # core-modules-only install; reaching a named zone without the module dies
1120 # with the same loud message as an unknown zone (never a silent UTC
1121 # fallback). 'local' and 'floating' are DateTime::TimeZone specials that
1122 # would read the host environment / return a zoneless offset -- both
1123 # refused explicitly, same as the JS reference refuses 'Local'.
1124 8 ▶sub _format_date_zone_offset ($tz, $ms) {
Subroutine _format_date_zone_offset: called CC=6 SCAR=17.9
1125 8 ▶ if ($tz eq '' || lc($tz) eq 'local' || lc($tz) eq 'floating') {
Branch: 1 branch
BranchTrueFalseTotal
if ($tz eq "" or CORE::lc $tz eq "local" or CORE::lc $tz eq "floating") 4 4 8
Condition100%6/6
$tz eq "" or CORE::lc $tz eq "local" or CORE::lc $tz eq "floating"
l!l&&r!l&&!r
314
$tz eq "" or CORE::lc $tz eq "local"
l!l&&r!l&&!r
125
MC/DC100%3/3
$tz eq "" or CORE::lc $tz eq "local" or CORE::lc $tz eq "floating"
$tz eq "" CORE::lc $tz eq "local" CORE::lc $tz eq "floating"
Truth table100%4/4
A or B or C
A= $tz eq ""B= CORE::lc $tz eq "local"C= CORE::lc $tz eq "floating"
ABCresult
1XX1
01X1
0011
0000
1126 4 die qq{format_date: unresolvable timeZone "$tz"};
1127 }
1128 4 my $zone = eval {
1129 4 require DateTime::TimeZone;
1130 4 DateTime::TimeZone->new(name => $tz);
1131 };
1132 4 ▶ if (!$zone) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($zone) 3 1 4
1133 # Carry the underlying loader/constructor error: "unresolvable"
1134 # covers both an unknown zone AND a broken/absent DateTime::TimeZone
1135 # installation, and the two need different fixes.
1136 3 ▶ my $cause = $@ ? " ($@)" : '';
Branch: 1 branch
BranchTrueFalseTotal
$@ ? : 3 0 3
1137 3 die qq{format_date: unresolvable timeZone "$tz"$cause};
1138 }
1139 1 return $zone->offset_for_datetime(
1140 BarefootJS::_TZProbe->new(POSIX::floor($ms / 1000)));
1141 }
1142  
1143 # ---------------------------------------------------------------------------
1144 # Array / String method helpers (#1448 Tier A)
1145 # ---------------------------------------------------------------------------
1146 #
1147 # `Array.prototype.includes(x)` and `String.prototype.includes(sub)`
1148 # share a method name in JS; the JSX parser can't tell the two
1149 # receiver shapes apart without TS type inference, so both lower to
1150 # the same IR node (`array-method` / method `includes`). This helper
1151 # dispatches at the Perl level via `ref()`:
1152 # - ARRAY ref: scan elements with `BarefootJS::Evaluator::_same_value_zero`,
1153 # matching `Array.prototype.includes`'s SameValueZero
1154 # semantics (no cross-type coercion, e.g. `[2].includes("2")`
1155 # is false; NaN matches NaN) — the same algorithm the
1156 # evaluator's serialized-callback path already uses for
1157 # `.includes`, so both positions agree. This used to be a
1158 # stringy `eq` scan, which coerced numbers to strings
1159 # (`[2].includes("2")` was true) and diverged from JS.
1160 # - scalar: `index($recv, $sub) != -1`, the needle JS ToString'd
1161 # (`null` searches for "null", `undefined` for
1162 # "undefined").
1163 # Anything else (HASH ref, code ref) returns false — matches the
1164 # JS semantic where `.includes` is only defined on Array /
1165 # TypedArray / String.
1166  
1167 # JS `a === b` when neither operand's type is known at compile time. Perl's
1168 # numeric `==` reads two different non-numeric strings as `0 == 0`, and `eq`
1169 # reads `1` and `1.0` as different, so the comparison goes by the operands'
1170 # JS types: numbers by value, strings by content, booleans by truth value,
1171 # `undef` (`null`) only to `undef`, `UNDEF` (`undefined`) only to `UNDEF`, an
1172 # object or array only to the same reference,
1173 # and values of different types never equal. The
1174 # result is a Perl boolean, the same value the native operators yield.
1175 26 ▶sub strict_eq ($self, $l, $r) {
Subroutine strict_eq: called CC=2 SCAR=6.9
Pod undocumented
1176 26 ▶ return BarefootJS::Evaluator::_strict_eq($l, $r) ? !!1 : !!0;
Branch: 1 branch
BranchTrueFalseTotal
BarefootJS::Evaluator::_strict_eq($l, $r) ? : 9 17 26
1177 }
1178  
1179 # JS primitive helpers (spec/js-primitive-semantics.md, "Operation table"):
1180 # ToBoolean, ToNumber, ToString, the relational operators, binary `+` and
1181 # unary `-`. Each delegates to the callback evaluator's primitive of the same
1182 # operation, so a template helper call and a callback body share one
1183 # implementation. A boolean result is a Perl boolean, as `strict_eq`'s is.
1184 # Unlike `number` and `string` (display helpers: `undef` / `UNDEF` -> NaN /
1185 # ''), an `undef` operand reads as JS null here (0 / 'null') and `UNDEF` as JS
1186 # undefined (NaN / 'undefined').
1187 1 ▶sub truthy ($self, $v) {
Subroutine truthy: called CC=2 SCAR=7.6
Pod undocumented
1188 1 ▶ return BarefootJS::Evaluator::_truthy($v) ? !!1 : !!0;
Branch: 1 branch
BranchTrueFalseTotal
BarefootJS::Evaluator::_truthy($v) ? : 0 1 1
1189 }
1190  
1191 # Boxes for a value-position JS `l || r` / `l && r` (#3824): the adapters
1192 # spell `l || r` as `(keep_truthy(l) || [r])->[0]` and `l && r` as
1193 # `(keep_falsy(l) || [r])->[0]`. `keep_truthy` is the one-element arrayref
1194 # `[$v]` when `$v` is JS-truthy and undef otherwise (`keep_falsy` the
1195 # reverse), so Perl's `||` stops at `$v`'s box exactly when JS returns `$v`
1196 # itself and builds `[r]` only otherwise (the short circuit); `->[0]` unboxes
1197 # the operand. Each operand appears once, so a chain grows linearly.
1198 0 ▶sub keep_truthy ($self, $v) {
Subroutine keep_truthy: not called CC=2 SCAR=17.9
Pod undocumented
1199 0 ▶ return BarefootJS::Evaluator::_truthy($v) ? [$v] : undef;
Branch: 1 branch
BranchTrueFalseTotal
BarefootJS::Evaluator::_truthy($v) ? : 0 0 0
1200 }
1201  
1202 0 ▶sub keep_falsy ($self, $v) {
Subroutine keep_falsy: not called CC=2 SCAR=17.9
Pod undocumented
1203 0 ▶ return BarefootJS::Evaluator::_truthy($v) ? undef : [$v];
Branch: 1 branch
BranchTrueFalseTotal
BarefootJS::Evaluator::_truthy($v) ? : 0 0 0
1204 }
1205  
1206 # The box for a value-position JS `l ?? r`: the adapters spell it as
1207 # `(keep_nonnil(l) || [r])->[0]`, so each operand appears once. Only the two
1208 # nils (`null`, `undefined`) are absent; `0`, `''` and `false` are kept, as
1209 # in JS. Perl's `//` would keep `UNDEF`.
1210 4 ▶sub keep_nonnil ($self, $v) {
Subroutine keep_nonnil: called CC=2 SCAR=6.9
Pod undocumented
1211 4 ▶ return _nullish($v) ? undef : [$v];
Branch: 1 branch
BranchTrueFalseTotal
_nullish($v) ? : 2 2 4
1212 }
1213  
1214 2 ▶sub to_number ($self, $v) { return BarefootJS::Evaluator::_to_number($v) }
Subroutine to_number: called CC=1 SCAR=0.0
Pod undocumented
1215  
1216 2 ▶sub to_string ($self, $v) { return BarefootJS::Evaluator::_to_string($v) }
Subroutine to_string: called CC=1 SCAR=0.0
Pod undocumented
1217  
1218 2 ▶sub plus ($self, $l, $r) { return BarefootJS::Evaluator::_binary('+', $l, $r) }
Subroutine plus: called CC=1 SCAR=0.0
Pod undocumented
1219  
1220 0 ▶sub neg ($self, $v) { return BarefootJS::Evaluator::_unary('-', $v) }
Subroutine neg: not called CC=1 SCAR=6.9
Pod undocumented
1221  
1222 1 ▶sub lt ($self, $l, $r) { return BarefootJS::Evaluator::_relational('<', $l, $r) ? !!1 : !!0 }
Subroutine lt: called CC=2 SCAR=7.6
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
BarefootJS::Evaluator::_relational('<', $l, $r) ? : 0 1 1
1223 1 ▶sub le ($self, $l, $r) { return BarefootJS::Evaluator::_relational('<=', $l, $r) ? !!1 : !!0 }
Subroutine le: called CC=2 SCAR=7.6
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
BarefootJS::Evaluator::_relational('<=', $l, $r) ? : 1 0 1
1224 0 ▶sub gt ($self, $l, $r) { return BarefootJS::Evaluator::_relational('>', $l, $r) ? !!1 : !!0 }
Subroutine gt: not called CC=2 SCAR=17.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
BarefootJS::Evaluator::_relational('>', $l, $r) ? : 0 0 0
1225 0 ▶sub ge ($self, $l, $r) { return BarefootJS::Evaluator::_relational('>=', $l, $r) ? !!1 : !!0 }
Subroutine ge: not called CC=2 SCAR=17.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
BarefootJS::Evaluator::_relational('>=', $l, $r) ? : 0 0 0
1226  
1227 22 ▶sub includes ($self, $recv, $elem) {
Subroutine includes: called CC=6 SCAR=17.9
Pod undocumented
1228 22 ▶ if (ref($recv) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $recv eq "ARRAY") 13 9 22
1229 13 for my $item (@$recv) {
1230 18 ▶ return 1 if BarefootJS::Evaluator::_same_value_zero($item, $elem);
Branch: 1 branch
BranchTrueFalseTotal
if BarefootJS::Evaluator::_same_value_zero($item, $elem) 7 11 18
1231 }
1232 6 return 0;
1233 }
1234 9 ▶ return 0 if ref($recv);
Branch: 1 branch
BranchTrueFalseTotal
if ref $recv 2 7 9
1235 # The needle is JS ToString'd (`"anullb".includes(null)` is true).
1236 7 ▶ return index($self->string($recv), _js_string($elem)) != -1 ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
index($self->string($recv), _js_string($elem)) != -1 ? : 4 3 7
1237 }
1238  
1239 # `Array.prototype.filter(fn)` / `.every(fn)` / `.some(fn)`. The Xslate adapter
1240 # lowers a JS arrow predicate to a Kolon lambda (`-> $x { ... }`), which is
1241 # callable from Perl as a code ref, and emits `$bf.filter($arr, <lambda>)`.
1242 # `filter` returns a new arrayref; `every` / `some` return 1/0. Non-array /
1243 # empty receivers follow JS (`filter` → [], `every` → true, `some` → false).
1244 # (The Mojo adapter lowers these shapes inline and never reaches these methods.)
1245 0 ▶sub filter ($self, $recv, $pred) {
Subroutine filter: not called CC=2 SCAR=17.9
Pod undocumented
1246 0 ▶ return [] unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 0 0
1247 0 return [ grep { $pred->($_) } @$recv ];
1248 }
1249  
1250 0 ▶sub every ($self, $recv, $pred) {
Subroutine every: not called CC=4 SCAR=30.0
Pod undocumented
1251 0 ▶ return 1 unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 0 0
1252 0 ▶ for my $item (@$recv) { return 0 unless $pred->($item) }
Branch: 1 branch
BranchTrueFalseTotal
unless &$pred($item) 0 0 0
1253 0 return 1;
1254 }
1255  
1256 0 ▶sub some ($self, $recv, $pred) {
Subroutine some: not called CC=4 SCAR=30.0
Pod undocumented
1257 0 ▶ return 0 unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 0 0
1258 0 ▶ for my $item (@$recv) { return 1 if $pred->($item) }
Branch: 1 branch
BranchTrueFalseTotal
if &$pred($item) 0 0 0
1259 0 return 0;
1260 }
1261  
1262 # `Array.prototype.find(fn)` / `.findIndex(fn)` / `.findLast(fn)` /
1263 # `.findLastIndex(fn)` — same Kolon-lambda predicate mechanism as filter. The
1264 # camelCase JS names lower to these snake_case methods (like index_of /
1265 # last_index_of). `find` / `find_last` return the matching element (or JS
1266 # `undefined`, `UNDEF`); the index forms return the 0-based position (or -1).
1267 1 ▶sub find ($self, $recv, $pred) {
Subroutine find: called CC=4 SCAR=14.5
Pod undocumented
1268 1 ▶ return $UNDEF unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 1 1
1269 1 ▶ for my $item (@$recv) { return $item if $pred->($item) }
Branch: 1 branch
BranchTrueFalseTotal
if &$pred($item) 0 1 1
1270 1 return $UNDEF;
1271 }
1272  
1273 0 ▶sub find_index ($self, $recv, $pred) {
Subroutine find_index: not called CC=4 SCAR=30.0
Pod undocumented
1274 0 ▶ return -1 unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 0 0
1275 0 ▶ for my $i (0 .. $#$recv) { return $i if $pred->($recv->[$i]) }
Branch: 1 branch
BranchTrueFalseTotal
if &$pred($recv->[$i]) 0 0 0
1276 0 return -1;
1277 }
1278  
1279 1 ▶sub find_last ($self, $recv, $pred) {
Subroutine find_last: called CC=4 SCAR=14.5
Pod undocumented
1280 1 ▶ return $UNDEF unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 1 1
1281 1 ▶ for my $i (reverse 0 .. $#$recv) { return $recv->[$i] if $pred->($recv->[$i]) }
Branch: 1 branch
BranchTrueFalseTotal
if &$pred($recv->[$i]) 0 1 1
1282 1 return $UNDEF;
1283 }
1284  
1285 0 ▶sub find_last_index ($self, $recv, $pred) {
Subroutine find_last_index: not called CC=4 SCAR=30.0
Pod undocumented
1286 0 ▶ return -1 unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 0 0
1287 0 ▶ for my $i (reverse 0 .. $#$recv) { return $i if $pred->($recv->[$i]) }
Branch: 1 branch
BranchTrueFalseTotal
if &$pred($recv->[$i]) 0 0 0
1288 0 return -1;
1289 }
1290  
1291 # `String.prototype.toLowerCase()` / `.toUpperCase()`. Kolon has a builtin
1292 # `.join` array method (so the adapter uses that directly) but no builtin
1293 # `lc` / `uc`, so these live on the runtime object. `CORE::` avoids recursing
1294 # into these methods.
1295 0 ▶sub lc ($self, $s) { return CORE::lc($self->string($s)) }
Subroutine lc: not called CC=1 SCAR=6.9
Pod undocumented
1296 0 ▶sub uc ($self, $s) { return CORE::uc($self->string($s)) }
Subroutine uc: not called CC=1 SCAR=6.9
Pod undocumented
1297  
1298 # `Array.prototype.join(sep)` with JS semantics: an omitted or `undefined`
1299 # separator is ",", any other one is ToString'd (`null` joins with "null");
1300 # undefined / null elements render as empty (`[1,,2].join(",")` → "1,,2").
1301 # Kolon has a builtin `.join`, but routing through the runtime keeps the
1302 # JS-compat element handling in one place. `CORE::join` avoids recursing.
1303 3 ▶sub join ($self, $recv, $sep = $OMITTED) {
Subroutine join: called CC=4 SCAR=13.9
Pod undocumented
1304 3 ▶ return '' unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 3 3
1305 3 ▶ $sep = _omitted($sep) ? ',' : _js_string($sep);
Branch: 1 branch
BranchTrueFalseTotal
_omitted($sep) ? : 2 1 3
1306 # Each element routes through `string()` (JS `String(v)`), not a bare
1307 # defined-check, so a nested-array element (e.g. `.flat(0)`'s shallow
1308 # copy, #2262) gets the recursive JS comma-join instead of stringifying
1309 # to a Perl ARRAY ref's memory address.
1310 3 return CORE::join($sep, map { $self->string($_) } @$recv);
1311 }
1312  
1313 # `.length` — JS works on BOTH arrays (element count) and strings; Kolon's
1314 # builtin `.size()` is array-only and faults on a string. So dispatch on ref
1315 # type here. The string branch counts UTF-16 CODE UNITS, matching JS
1316 # `String.prototype.length` (#2255) — NOT `CORE::length`'s Unicode codepoint
1317 # count. A codepoint outside the Basic Multilingual Plane (astral,
1318 # U+10000-U+10FFFF — e.g. '👍') is a surrogate PAIR in UTF-16, so it counts
1319 # as 2, not 1; '日本語' is 3 either way (BMP-only). An object's `.length` is
1320 # its own `length` property (`{ length: 3 }`), `undefined` when it has none — the
1321 # same read the evaluator's `_read_index` does (`UNDEF` when it has none).
1322 1 ▶sub length ($self, $recv) {
Subroutine length: called CC=8 SCAR=36.8
Pod undocumented
1323 1 ▶ return scalar @$recv if ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $recv eq "ARRAY" 0 1 1
1324 1 ▶ return BarefootJS::Evaluator::_read_index($recv, 'length') if ref($recv) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $recv eq "HASH" 1 0 1
1325 0 ▶ return 0 if ref($recv) || _nullish($recv);
Branch: 1 branch
BranchTrueFalseTotal
if ref $recv or _nullish($recv) 0 0 0
Condition0%0/3
ref $recv or _nullish($recv)
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $recv or _nullish($recv)
ref $recv _nullish($recv)
Truth table0%0/3
A or B
A= ref $recvB= _nullish($recv)
ABresult
1X1
011
000
1326 0 my $n = 0;
1327 0 ▶ $n += ord($_) > 0xFFFF ? 2 : 1 for split //, ($recv // '');
Branch: 1 branch
BranchTrueFalseTotal
ord $_ > 65535 ? : 0 0 0
Condition0%0/2
$recv // ""
l!l
00
MC/DC0%0/1
$recv // ""
$recv
Truth table0%0/2
A
A= $recv
Aresult
11
00
1328 0 return $n;
1329 }
1330  
1331 # `arr[index]` / `hash[key]` — a runtime-polymorphic dynamic-key element
1332 # access (`emitIndexAccessPerl`, expr/operand.ts). Perl's deref syntax
1333 # forces a compile-time choice between `->{$k}` (hash) and `->[$k]`
1334 # (array), but a dynamic key's shape is only known at run time (#2491), so
1335 # this dispatches on the receiver's RUNTIME `ref`. It is the callback
1336 # evaluator's `_read_index`, so a template read and a callback read share
1337 # one JS ToPropertyKey implementation (spec/js-primitive-semantics.md,
1338 # "ToPropertyKey and index read").
1339 30 ▶sub get ($self, $collection, $key) {
Subroutine get: called CC=1 SCAR=0.0
Pod undocumented
1340 30 return BarefootJS::Evaluator::_read_index($collection, $key);
1341 }
1342  
1343 # JS `o?.k`: `undefined` over a nullish receiver, the read of `k` (`get`)
1344 # otherwise.
1345 5 ▶sub get_opt ($self, $collection, $key) {
Subroutine get_opt: called CC=2 SCAR=6.9
Pod undocumented
1346 5 ▶ return $UNDEF if _nullish($collection);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($collection) 2 3 5
1347 3 return BarefootJS::Evaluator::_read_index($collection, $key);
1348 }
1349  
1350 # JS `undefined` as a template spells it (`bf->undefined` / `$bf.undefined()`):
1351 # the `undefined` identifier, an omitted method argument's default, the
1352 # result of a `?.` over a nullish receiver.
1353 1 ▶sub undefined ($self) { return $UNDEF }
Subroutine undefined: called CC=1 SCAR=0.0
Pod undocumented
1354  
1355 # The nil tests (spec/js-undefined-value.md, decisions 3 and 7): JS
1356 # `x === undefined`, `x === null` and the loose `x == null`. A template
1357 # spells a nil-test plan, an attribute omission and a `??` through them;
1358 # Perl's `defined` / `//` see `UNDEF` as a value. A boolean result is a Perl
1359 # boolean, as `strict_eq`'s is.
1360 2 ▶sub is_undefined ($self, $v) { return _undef_p($v) ? !!1 : !!0 }
Subroutine is_undefined: called CC=2 SCAR=6.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
_undef_p($v) ? : 1 1 2
1361 2 ▶sub is_null ($self, $v) { return defined($v) ? !!0 : !!1 }
Subroutine is_null: called CC=2 SCAR=6.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 1 1 2
1362 3 ▶sub is_nullish ($self, $v) { return _nullish($v) ? !!1 : !!0 }
Subroutine is_nullish: called CC=2 SCAR=6.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
_nullish($v) ? : 2 1 3
1363  
1364 # `isValidElement(x)` -- the framework "is this a renderable element (not
1365 # plain text)?" predicate `Slot`'s `asChild` pattern uses (#2266). Mirrors
1366 # JS's `'tag' in x && 'props' in x`: true only for a HASH ref carrying both
1367 # keys (case-insensitively, matching the case-tolerant field lookups
1368 # elsewhere in this module). A passed-through JSX child is represented as
1369 # pre-rendered markup (a plain string) on this SSR model, so a non-empty
1370 # STRING child is NOT a valid element -- routing `isValidElement` through
1371 # bare truthiness here would wrongly take the element-merge branch.
1372 0 ▶sub is_element ($self, $v) {
Subroutine is_element: not called CC=7 SCAR=40.3
Pod undocumented
1373 0 ▶ return 0 unless ref($v) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $v eq "HASH" 0 0 0
1374 0 my ($has_tag, $has_props) = (0, 0);
1375 0 for my $key (keys %$v) {
1376 0 ▶ $has_tag = 1 if CORE::lc($key) eq 'tag';
Branch: 1 branch
BranchTrueFalseTotal
if CORE::lc $key eq "tag" 0 0 0
1377 0 ▶ $has_props = 1 if CORE::lc($key) eq 'props';
Branch: 1 branch
BranchTrueFalseTotal
if CORE::lc $key eq "props" 0 0 0
1378 }
1379 0 ▶ return ($has_tag && $has_props) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$has_tag && $has_props ? : 0 0 0
Condition0%0/3
$has_tag and $has_props
!ll&&!rl&&r
000
MC/DC0%0/2
$has_tag and $has_props
$has_tag $has_props
Truth table0%0/3
A and B
A= $has_tagB= $has_props
ABresult
0X0
100
111
1380 }
1381  
1382 # `Array.prototype.indexOf(x)` / `Array.prototype.lastIndexOf(x)`
1383 # value-equality search (#1448 Tier A). Returns the 0-based position
1384 # of the first / last matching element, or -1 if not found.
1385 # A plain-scalar (string) receiver is `String.prototype.indexOf` /
1386 # `.lastIndexOf` instead, counted in UTF-16 code units like JS (#3613):
1387 # `'日本語'.indexOf('本')` is 1 and `'a😀b'.indexOf('b')` is 3. Any other
1388 # reference returns -1 (`.indexOf` is only defined on Array / TypedArray /
1389 # String).
1390  
1391 14 ▶sub _array_index_of ($recv, $elem, $reverse) {
Subroutine _array_index_of: called CC=11 SCAR=24.0
1392 14 ▶ return -1 unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 1 13 14
1393 13 ▶ my @indices = $reverse ? (reverse 0 .. $#{$recv}) : (0 .. $#{$recv});
Branch: 1 branch
BranchTrueFalseTotal
$reverse ? : 5 8 13
1394 13 for my $i (@indices) {
1395 31 my $item = $recv->[$i];
1396 # Strict equality tells the nils apart: `null` matches only `null`,
1397 # `undefined` only `undefined`.
1398 31 ▶ if (_nullish($item) || _nullish($elem)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_nullish($item) or _nullish($elem)) 6 25 31
Condition66%2/3
_nullish($item) or _nullish($elem)
l!l&&r!l&&!r
6025
MC/DC50%1/2
_nullish($item) or _nullish($elem)
_nullish($item) _nullish($elem)
Truth table66%2/3
A or B
A= _nullish($item)B= _nullish($elem)
ABresult
1X1
011
000
1399 6 ▶ return $i if (!defined $item && !defined $elem) || (_undef_p($item) && _undef_p($elem));
Branch: 1 branch
BranchTrueFalseTotal
if not defined $item || defined $elem or _undef_p($item) and _undef_p($elem) 4 2 6
Condition100%9/9
not defined $item || defined $elem or _undef_p($item) and _undef_p($elem)
l!l&&r!l&&!r
312
defined $item || defined $elem
l!l&&r!l&&!r
213
_undef_p($item) and _undef_p($elem)
!ll&&!rl&&r
111
MC/DC75%3/4
not defined $item || defined $elem or _undef_p($item) and _undef_p($elem)
defined $item defined $elem _undef_p($item) _undef_p($elem)
Truth table57%4/7
not(A || B) or C and D
A= defined $itemB= defined $elemC= _undef_p($item)D= _undef_p($elem)
ABCDresult
00XX1
1X111
01111
1X0X0
1X100
010X0
01100
1400 2 next;
1401 }
1402 25 ▶ return $i if $item eq $elem;
Branch: 1 branch
BranchTrueFalseTotal
if $item eq $elem 5 20 25
1403 }
1404 4 return -1;
1405 }
1406  
1407 # JS `ToIntegerOrInfinity` for a string position or index (#3613): NaN →
1408 # 0, truncation toward zero, and ±Infinity clamped to ±2**53 so the
1409 # caller's range check treats it as out of range (a bare `int()` keeps
1410 # NaN, which then indexes element 0 with a warning).
1411 92 ▶sub _to_integer_or_infinity ($self, $value) {
Subroutine _to_integer_or_infinity: called CC=4 SCAR=13.9
1412 92 my $n = _js_number($value);
1413 92 ▶ return 0 if _is_nan($n);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($n) 6 86 92
1414 86 ▶ return 2**53 if $n >= 2**53;
Branch: 1 branch
BranchTrueFalseTotal
if $n >= "9.00719925474099e+15" 3 83 86
1415 83 ▶ return -(2**53) if $n <= -(2**53);
Branch: 1 branch
BranchTrueFalseTotal
if $n <= "-9.00719925474099e+15" 1 82 83
1416 82 return int($n);
1417 }
1418  
1419 # `$s` as JS sees it: a list of UTF-16 code units. JS string positions
1420 # (`indexOf`, `at`, `startsWith`'s position, …) count these, so an astral
1421 # character such as '😀' is two units (#3613).
1422 70 ▶sub _utf16_units ($s) {
Subroutine _utf16_units: called CC=3 SCAR=11.0
1423 70 my @units;
1424 70 for my $o (map { ord } split //, $s) {
1425 154 ▶ if ($o > 0xFFFF) {
Branch: 1 branch
BranchTrueFalseTotal
if ($o > 65535) { } 12 142 154
1426 12 $o -= 0x10000;
1427 12 push @units, 0xD800 + ($o >> 10), 0xDC00 + ($o & 0x3FF);
1428 } else {
1429 142 push @units, $o;
1430 }
1431 }
1432 70 return \@units;
1433 }
1434  
1435 # Whether `$needle` (unit list) occurs in `$hay` at unit offset `$at`.
1436 36 ▶sub _utf16_has_at ($hay, $needle, $at) {
Subroutine _utf16_has_at: called CC=5 SCAR=16.1
1437 36 ▶ return 0 if $at < 0 || $at + @$needle > @$hay;
Branch: 1 branch
BranchTrueFalseTotal
if $at < 0 or $at + @$needle > @$hay 3 33 36
Condition100%3/3
$at < 0 or $at + @$needle > @$hay
l!l&&r!l&&!r
2133
MC/DC100%2/2
$at < 0 or $at + @$needle > @$hay
$at < 0 $at + @$needle > @$hay
Truth table100%3/3
A or B
A= $at < 0B= $at + @$needle > @$hay
ABresult
1X1
011
000
1438 33 for my $i (0 .. $#$needle) {
1439 34 ▶ return 0 if $hay->[$at + $i] != $needle->[$i];
Branch: 1 branch
BranchTrueFalseTotal
if $$hay[$at + $i] != $needle->[$i] 13 21 34
1440 }
1441 20 return 1;
1442 }
1443  
1444 10 ▶sub _utf16_index_of ($self, $recv, $elem, $reverse) {
Subroutine _utf16_index_of: called CC=4 SCAR=13.9
1445 10 my $hay = _utf16_units("$recv");
1446 # The needle is JS ToString'd (`'anullb'.indexOf(null)` is 1).
1447 10 my $needle = _utf16_units(_js_string($elem));
1448 10 my $last = @$hay - @$needle;
1449 10 ▶ my @indices = $reverse ? (reverse 0 .. $last) : (0 .. $last);
Branch: 1 branch
BranchTrueFalseTotal
$reverse ? : 4 6 10
1450 10 for my $i (@indices) {
1451 17 ▶ return $i if _utf16_has_at($hay, $needle, $i);
Branch: 1 branch
BranchTrueFalseTotal
if _utf16_has_at($hay, $needle, $i) 8 9 17
1452 }
1453 2 return -1;
1454 }
1455  
1456 15 ▶sub index_of ($self, $recv, $elem) {
Subroutine index_of: called CC=3 SCAR=11.1
Pod undocumented
1457 15 ▶ return $self->_utf16_index_of($recv, $elem, 0) if defined $recv && !ref($recv);
Branch: 1 branch
BranchTrueFalseTotal
if defined $recv and not ref $recv 6 9 15
Condition66%2/3
defined $recv and not ref $recv
!ll&&!rl&&r
096
MC/DC50%1/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table66%2/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1458 9 return _array_index_of($recv, $elem, 0);
1459 }
1460  
1461 9 ▶sub last_index_of ($self, $recv, $elem) {
Subroutine last_index_of: called CC=3 SCAR=11.1
Pod undocumented
1462 9 ▶ return $self->_utf16_index_of($recv, $elem, 1) if defined $recv && !ref($recv);
Branch: 1 branch
BranchTrueFalseTotal
if defined $recv and not ref $recv 4 5 9
Condition66%2/3
defined $recv and not ref $recv
!ll&&!rl&&r
054
MC/DC50%1/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table66%2/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1463 5 return _array_index_of($recv, $elem, 1);
1464 }
1465  
1466 # `Array.prototype.at(i)` — supports negative indices (`.at(-1)` is
1467 # the last element); out-of-bounds returns JS `undefined` (`UNDEF`, which
1468 # renders as the empty string).
1469 # Matches the Go `bf_at` arithmetic (`length + i` for i < 0) so adapter
1470 # output stays symmetric. A plain-scalar (string) receiver is
1471 # `String.prototype.at`, indexed in UTF-16 code units (#3613). Half of a
1472 # surrogate pair comes back as U+FFFD, not the lone surrogate JS returns:
1473 # a Perl string could hold the code point, but two halves concatenated
1474 # stay two characters (they never rejoin into the astral one) and encode
1475 # to invalid UTF-8 on output, so the helper keeps its result valid text
1476 # instead (limitation `string-at-lone-surrogate`). Other references
1477 # return `undefined`.
1478  
1479 25 ▶sub at ($self, $recv, $i = $OMITTED) {
Subroutine at: called CC=10 SCAR=23.0
Pod undocumented
1480 # The index is ToIntegerOrInfinity'd, so an omitted, `undefined` or
1481 # `null` one reads element 0.
1482 25 ▶ $i = $UNDEF if _omitted($i);
Branch: 1 branch
BranchTrueFalseTotal
if _omitted($i) 2 23 25
1483 25 ▶ if (defined $recv && !ref($recv)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $recv and not ref $recv) 12 13 25
Condition100%3/3
defined $recv and not ref $recv
!ll&&!rl&&r
11212
MC/DC100%2/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table100%3/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1484 12 my $units = _utf16_units("$recv");
1485 12 my $idx = $self->_relative_index($i, scalar @$units);
1486 12 ▶ return $UNDEF unless defined $idx;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $idx 5 7 12
1487 7 my $u = $units->[$idx];
1488 7 ▶ return $u >= 0xD800 && $u <= 0xDFFF ? "\x{FFFD}" : chr($u);
Branch: 1 branch
BranchTrueFalseTotal
$u >= 55296 && $u <= 57343 ? : 1 6 7
Condition66%2/3
$u >= 55296 and $u <= 57343
!ll&&!rl&&r
601
MC/DC50%1/2
$u >= 55296 and $u <= 57343
$u >= 55296 $u <= 57343
Truth table66%2/3
A and B
A= $u >= 55296B= $u <= 57343
ABresult
0X0
100
111
1489 }
1490 13 ▶ return $UNDEF unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 2 11 13
1491 11 my $idx = $self->_relative_index($i, scalar @$recv);
1492 11 ▶ return defined $idx ? $recv->[$idx] : $UNDEF;
Branch: 1 branch
BranchTrueFalseTotal
defined $idx ? : 7 4 11
1493 }
1494  
1495 # `Array.prototype.at`'s index: ToIntegerOrInfinity, counted from the end
1496 # when negative; undef when it falls outside `[0, length)`.
1497 23 ▶sub _relative_index ($self, $value, $len) {
Subroutine _relative_index: called CC=4 SCAR=13.9
1498 23 my $idx = $self->_to_integer_or_infinity($value);
1499 23 ▶ $idx += $len if $idx < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $idx < 0 7 16 23
1500 23 ▶ return ($idx >= 0 && $idx < $len) ? $idx : undef;
Branch: 1 branch
BranchTrueFalseTotal
$idx >= 0 && $idx < $len ? : 14 9 23
Condition100%3/3
$idx >= 0 and $idx < $len
!ll&&!rl&&r
2714
MC/DC100%2/2
$idx >= 0 and $idx < $len
$idx >= 0 $idx < $len
Truth table100%3/3
A and B
A= $idx >= 0B= $idx < $len
ABresult
0X0
100
111
1501 }
1502  
1503 # `Array.prototype.concat(other)` — merges two arrays in order
1504 # into a new ARRAY ref. Non-array operands collapse to empty
1505 # (matches the Go `bf_concat` semantic so cross-adapter output
1506 # stays symmetric; differs from JS where a non-Array argument
1507 # with `Symbol.isConcatSpreadable` would be spread, a behaviour
1508 # the template-language path never observes).
1509  
1510 9 ▶sub concat ($self, $a, $b) {
Subroutine concat: called CC=3 SCAR=11.0
Pod undocumented
1511 9 my @out;
1512 9 ▶ push @out, @$a if ref($a) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $a eq "ARRAY" 6 3 9
1513 9 ▶ push @out, @$b if ref($b) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $b eq "ARRAY" 8 1 9
1514 9 return \@out;
1515 }
1516  
1517 # `Array.prototype.slice(start, end?)` AND `String.prototype.slice`
1518 # (the `string-slice` divergence) — carves out a sub-range. The
1519 # adapter emits the same call for both receiver shapes (it can't
1520 # disambiguate string vs. array at compile time), so this dispatches
1521 # at runtime on `ref($recv)`, mirroring `includes` above. Mirrors the
1522 # Go `bf_slice` arithmetic so adapter output stays symmetric:
1523 # - start < 0 → length + start (e.g. -1 = last index)
1524 # - end < 0 → length + end
1525 # - start < 0 after clamp → 0
1526 # - end > length → length
1527 # - start >= end → empty
1528 # - end omitted / `undefined` → "to length"; `null` is 0
1529 # Both bounds are ToIntegerOrInfinity'd (`null` and `undefined` are 0 as a
1530 # start). String length/positions are characters (`use utf8` is active), not
1531 # bytes. Any other receiver returns an empty ARRAY ref.
1532  
1533 23 ▶sub slice ($self, $recv, $start = $OMITTED, $end = $OMITTED) {
Subroutine slice: called CC=9 SCAR=22.0
Pod undocumented
1534 23 ▶ if (!ref($recv) && defined $recv) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $recv and defined $recv) 5 18 23
Condition100%3/3
not ref $recv and defined $recv
!ll&&!rl&&r
1715
MC/DC100%2/2
not ref $recv and defined $recv
not ref $recv defined $recv
Truth table100%3/3
not(A) and B
A= not ref $recvB= defined $recv
ABresult
0X0
100
111
1535 5 my $len = CORE::length($recv);
1536 5 my ($s, $e) = $self->_clamp_slice_range($len, $start, $end);
1537 5 ▶ return '' if $s >= $e;
Branch: 1 branch
BranchTrueFalseTotal
if $s >= $e 1 4 5
1538 4 return substr($recv, $s, $e - $s);
1539 }
1540 18 ▶ return [] unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 2 16 18
1541 16 my $len = scalar @$recv;
1542 16 ▶ return [] if $len == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $len == 0 1 15 16
1543  
1544 15 my ($s, $e) = $self->_clamp_slice_range($len, $start, $end);
1545 15 ▶ return [] if $s >= $e;
Branch: 1 branch
BranchTrueFalseTotal
if $s >= $e 5 10 15
1546 10 return [ @{$recv}[$s .. $e - 1] ];
1547 }
1548  
1549 # Shared bounds arithmetic for both `slice` branches above.
1550 20 ▶sub _clamp_slice_range ($self, $len, $start, $end) {
Subroutine _clamp_slice_range: called CC=9 SCAR=22.3
1551 20 ▶ my $s = _omitted($start) ? 0 : $self->_to_integer_or_infinity($start);
Branch: 1 branch
BranchTrueFalseTotal
_omitted($start) ? : 0 20 20
1552 20 ▶ $s = $len + $s if $s < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $s < 0 3 17 20
1553 20 ▶ $s = 0 if $s < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $s < 0 0 20 20
1554 20 ▶ $s = $len if $s > $len;
Branch: 1 branch
BranchTrueFalseTotal
if $s > $len 1 19 20
1555  
1556 20 ▶ my $e = _omitted($end) ? $len : $self->_to_integer_or_infinity($end);
Branch: 1 branch
BranchTrueFalseTotal
_omitted($end) ? : 9 11 20
1557 20 ▶ $e = $len + $e if $e < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $e < 0 2 18 20
1558 20 ▶ $e = 0 if $e < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $e < 0 0 20 20
1559 20 ▶ $e = $len if $e > $len;
Branch: 1 branch
BranchTrueFalseTotal
if $e > $len 0 20 20
1560  
1561 20 return ($s, $e);
1562 }
1563  
1564 # `Array.prototype.reverse()` / `Array.prototype.toReversed()` —
1565 # both shapes share this lowering. SSR templates render a snapshot
1566 # of state, so JS's mutate-receiver (`reverse`) vs
1567 # return-new-array (`toReversed`) distinction has no template-
1568 # level meaning. Always returns a new ARRAY ref to keep callers
1569 # safe from accidental aliasing. Non-array receivers return an
1570 # empty ARRAY ref.
1571  
1572 8 ▶sub reverse ($self, $recv) {
Subroutine reverse: called CC=2 SCAR=6.9
Pod undocumented
1573 8 ▶ return [] unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 3 5 8
1574 5 return [ reverse @$recv ];
1575 }
1576  
1577 # `Array.prototype.flat(depth?)` (#1448 Tier C) — flatten nested ARRAY
1578 # refs `$depth` levels deep. A `$depth` of -1 is the `Infinity` sentinel
1579 # (flatten fully); 0 returns a shallow copy. Non-ARRAY elements are kept
1580 # as-is (JS only flattens nested arrays). Non-ARRAY receiver → [].
1581 4 ▶sub flat ($self, $recv, $depth = 1) {
Subroutine flat: called CC=7 SCAR=19.5
Pod undocumented
1582 4 ▶ return [] unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 4 4
1583 4 my @out;
1584 4 for my $el (@$recv) {
1585 5 ▶ if ($depth != 0 && ref($el) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($depth != 0 and ref $el eq 'ARRAY') { } 1 4 5
Condition100%3/3
$depth != 0 and ref $el eq "ARRAY"
!ll&&!rl&&r
311
MC/DC100%2/2
$depth != 0 and ref $el eq "ARRAY"
$depth != 0 ref $el eq "ARRAY"
Truth table100%3/3
A and B
A= $depth != 0B= ref $el eq "ARRAY"
ABresult
0X0
100
111
1586 1 ▶ my $next = $depth > 0 ? $depth - 1 : $depth;
Branch: 1 branch
BranchTrueFalseTotal
$depth > 0 ? : 1 0 1
1587 1 push @out, @{ $self->flat($el, $next) };
1588 }
1589 else {
1590 4 push @out, $el;
1591 }
1592 }
1593 4 return \@out;
1594 }
1595  
1596 # `Array.prototype.flat(depth)` with a DYNAMIC depth (#2094) — the depth is
1597 # itself an arbitrary runtime value (e.g. a prop), not a compile-time literal,
1598 # so it must be coerced with JS's `ToIntegerOrInfinity` before delegating to
1599 # `flat` above: truncate toward zero; negative -> 0; NaN / non-numeric -> 0;
1600 # +Infinity or a huge finite value -> flatten fully.
1601 #
1602 # Deliberately a SEPARATE entry point from `flat`, not a smarter version of
1603 # it: the literal-depth path's `-1` argument is a compile-time SENTINEL baked
1604 # into the template source, meaning "the source literally said `Infinity`". A
1605 # genuinely dynamic depth that happens to evaluate to `-1` at render time
1606 # means the OPPOSITE in real JS (`[1,[2]].flat(-1)` never recurses — same as
1607 # `.flat(0)`). Since both paths would otherwise hand the same literal-looking
1608 # argument to one shared function, that function couldn't tell which case
1609 # it's in — so the two stay separate. Mirrors Go's `FlatDynamicDepth` /
1610 # `coerceFlatDepth` in bf.go.
1611 2 ▶sub flat_dynamic ($self, $recv, $depth) {
Subroutine flat_dynamic: called CC=2 SCAR=6.9
Pod undocumented
1612 # An `undefined` depth is the default, 1; `null` coerces to 0.
1613 2 ▶ return $self->flat($recv, 1) if _omitted($depth);
Branch: 1 branch
BranchTrueFalseTotal
if _omitted($depth) 1 1 2
1614 1 return $self->flat($recv, _coerce_flat_depth($depth));
1615 }
1616  
1617 # _coerce_flat_depth: JS `ToIntegerOrInfinity` for a dynamic `.flat(depth)`
1618 # argument, collapsed to `flat`'s int contract (`-1` == flatten fully).
1619 #
1620 # Perl's scalar type system blurs string/number duality, so `looks_like_number`
1621 # (already the codebase's ToNumber-style coercion check, see BarefootJS::
1622 # Evaluator's `_to_number`) is reused here rather than inventing a new
1623 # convention. `looks_like_number` on this Perl (5.38) already recognises the
1624 # strings "Infinity" / "-Infinity" / "NaN" as numeric (verified empirically:
1625 # `perl -MScalar::Util=looks_like_number -e 'print looks_like_number("Infinity")'`
1626 # prints 1), and `$str + 0` on those strings yields the corresponding Perl
1627 # non-finite double, so no extra string special-casing is needed here.
1628 1 ▶sub _coerce_flat_depth ($depth) {
Subroutine _coerce_flat_depth: called CC=11 SCAR=47.2
1629 1 ▶ return 0 unless defined $depth;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $depth 1 0 1
1630 0 my $f;
1631 0 ▶ if (ref($depth) eq 'JSON::PP::Boolean') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $depth eq 'JSON::PP::Boolean') { } 0 0 0
elsif (not ref $depth and &looks_like_number($depth)) { } 0 0 0
1632 0 ▶ $f = $depth ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$depth ? : 0 0 0
1633 }
1634 ▶ elsif (!ref($depth) && looks_like_number($depth)) {
Condition0%0/3
not ref $depth and &looks_like_number($depth)
!ll&&!rl&&r
000
MC/DC0%0/2
not ref $depth and &looks_like_number($depth)
not ref $depth &looks_like_number($depth)
Truth table0%0/3
not(A) and B
A= not ref $depthB= &looks_like_number($depth)
ABresult
0X0
100
111
1635 0 $f = $depth + 0;
1636 }
1637 else {
1638 # undef handled above; anything else non-numeric (a plain string
1639 # that isn't a number, a HASH/ARRAY ref, ...) coerces via NaN.
1640 0 return 0;
1641 }
1642 0 ▶ return 0 if $f != $f; # NaN
Branch: 1 branch
BranchTrueFalseTotal
if $f != $f 0 0 0
1643 0 ▶ return -1 if $f == 9**9**9; # +Infinity -> flatten fully sentinel
Branch: 1 branch
BranchTrueFalseTotal
if $f == "Inf" 0 0 0
1644 0 ▶ return 0 if $f == -(9**9**9); # -Infinity -> 0
Branch: 1 branch
BranchTrueFalseTotal
if $f == "-Inf" 0 0 0
1645 0 my $trunc = int($f); # Perl's int() truncates toward zero
1646 0 ▶ return 0 if $trunc < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $trunc < 0 0 0 0
1647 0 ▶ return -1 if $trunc > 1_000_000; # huge finite ~= flatten fully
Branch: 1 branch
BranchTrueFalseTotal
if $trunc > 1000000 0 0 0
1648 0 return $trunc;
1649 }
1650  
1651 # `Array.prototype.flatMap(fn)` value-returning field projection
1652 # (#1448 Tier C) — map each element through a self / field projection,
1653 # then flatten one level. `field` reads a HASH-ref key (the raw JS prop
1654 # name, as `bf->reduce` does); a projected non-ARRAY value is kept as-is
1655 # (flatMap = map + flat(1)). Non-ARRAY receiver → [].
1656 1 ▶sub flat_map ($self, $recv, $key_kind, $key) {
Subroutine flat_map: called CC=4 SCAR=14.6
Pod undocumented
1657 1 ▶ return [] unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 1 1
1658 1 my @projected;
1659 1 for my $el (@$recv) {
1660 1 ▶ if ($key_kind eq 'field') {
Branch: 1 branch
BranchTrueFalseTotal
if ($key_kind eq 'field') { } 1 0 1
1661 # JS `i => i.field` on a non-object, or a missing field, yields
1662 # `undefined`, not the element itself — so a scalar element
1663 # doesn't leak into the output.
1664 1 push @projected, _field_value($el, $key);
1665 }
1666 else {
1667 0 push @projected, $el;
1668 }
1669 }
1670 1 return $self->flat(\@projected, 1);
1671 }
1672  
1673 # `Array.prototype.flatMap(i => [i.a, i.b])` — array-literal tuple
1674 # projection (#1448 Tier C). Each `@specs` entry is a [kind, key] arrayref
1675 # (['self', ''] or ['field', 'a']). For each element, every leaf's value
1676 # is appended in order. flat(1) removes only the literal wrapper, so an
1677 # array-valued leaf is appended verbatim (no spread) — i.e. just append
1678 # each leaf. A non-HASH element under a `field` leaf, or a missing field,
1679 # yields `undefined` (JS `i.field`). Non-ARRAY receiver → [].
1680 0 ▶sub flat_map_tuple ($self, $recv, @specs) {
Subroutine flat_map_tuple: not called CC=5 SCAR=34.0
Pod undocumented
1681 0 ▶ return [] unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 0 0
1682 0 my @out;
1683 0 for my $el (@$recv) {
1684 0 for my $spec (@specs) {
1685 0 my ($kind, $key) = @$spec;
1686 0 ▶ if ($kind eq 'field') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq 'field') { } 0 0 0
1687 0 push @out, _field_value($el, $key);
1688 }
1689 else {
1690 0 push @out, $el;
1691 }
1692 }
1693 }
1694 0 return \@out;
1695 }
1696  
1697 # `String.prototype.trim()` — strip leading + trailing whitespace.
1698 # JS's `String.prototype.trim` matches `\s` in the Unicode sense
1699 # (any whitespace including non-breaking space U+00A0); Perl's `\s`
1700 # inside a regex with `/u` flag is the same. Undef receivers return
1701 # the empty string (matches JS's `String(undefined).trim()` which
1702 # would be "undefined" → "undefined", but in our template context
1703 # undef commonly means "missing prop"; rendering the empty string
1704 # is the safer choice and mirrors the JS-compat divergence we
1705 # already document for `bf->string(undef) === ""`).
1706  
1707 11 ▶sub trim ($self, $recv) {
Subroutine trim: called CC=3 SCAR=11.0
Pod undocumented
1708 11 ▶ return '' if _nullish($recv);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($recv) 1 10 11
1709 10 ▶ return '' if ref($recv);
Branch: 1 branch
BranchTrueFalseTotal
if ref $recv 2 8 10
1710 8 my $s = "$recv";
1711 8 $s =~ s/^\s+|\s+$//gu;
1712 8 return $s;
1713 }
1714  
1715 # `String.prototype.trimStart()` / `.trimEnd()` — the one-sided
1716 # siblings of `trim` above (#2183 follow-up), same `\s` /u regex
1717 # semantics restricted to one side.
1718  
1719 7 ▶sub trim_start ($self, $recv) {
Subroutine trim_start: called CC=3 SCAR=11.0
Pod undocumented
1720 7 ▶ return '' if _nullish($recv);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($recv) 1 6 7
1721 6 ▶ return '' if ref($recv);
Branch: 1 branch
BranchTrueFalseTotal
if ref $recv 1 5 6
1722 5 my $s = "$recv";
1723 5 $s =~ s/^\s+//u;
1724 5 return $s;
1725 }
1726  
1727 7 ▶sub trim_end ($self, $recv) {
Subroutine trim_end: called CC=3 SCAR=11.0
Pod undocumented
1728 7 ▶ return '' if _nullish($recv);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($recv) 1 6 7
1729 6 ▶ return '' if ref($recv);
Branch: 1 branch
BranchTrueFalseTotal
if ref $recv 1 5 6
1730 5 my $s = "$recv";
1731 5 $s =~ s/\s+$//u;
1732 5 return $s;
1733 }
1734  
1735 # `Number.prototype.toFixed(digits)` (#1897) — fixed-decimal string with
1736 # zero-padding. JS rounds the scaled integer half toward +Infinity (the
1737 # spec's "pick the larger n" tie-break), so `(2.5).toFixed(0)` is "3";
1738 # bare `sprintf("%.*f")` would round half-to-even ("2"), diverging. Scale
1739 # by 10**digits, round with `floor(x + 0.5)` (the same tie-break the
1740 # `round` helper uses), then format the exact multiple. A negative
1741 # `digits` clamps to 0, mirroring how the adapters default an omitted
1742 # argument.
1743 1 ▶sub to_fixed ($self, $value, $digits = $OMITTED) {
Subroutine to_fixed: called CC=7 SCAR=21.5
Pod undocumented
1744 1 my $n = $self->number($value);
1745 # JS toFixed returns the STRINGS "NaN" / "Infinity" / "-Infinity" for
1746 # non-finite inputs; the numeric values would stringify per-platform
1747 # ("nan"/"inf"/...) and diverge.
1748 1 ▶ return 'NaN' if _is_nan($n);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($n) 0 1 1
1749 1 ▶ return $n < 0 ? '-Infinity' : 'Infinity' if _is_inf($n);
Branch: 2 branches
BranchTrueFalseTotal
if _is_inf($n) 0 1 1
$n < 0 ? : 0 0 0
1750 # An omitted or `undefined` digit count is 0, as ToIntegerOrInfinity
1751 # makes `null` too.
1752 1 ▶ $digits = _omitted($digits) ? 0 : $self->_to_integer_or_infinity($digits);
Branch: 1 branch
BranchTrueFalseTotal
_omitted($digits) ? : 1 0 1
1753 1 ▶ $digits = 0 if $digits < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $digits < 0 0 1 1
1754 1 my $factor = 10 ** $digits;
1755 # Scaled as doubles, so `(1.005).toFixed(2)` sees JS's 100.49999… on a
1756 # perl whose NV is wider than a double (#3454).
1757 1 my $rounded = POSIX::floor(_as_double(_as_double($n) * $factor) + 0.5);
1758 1 return sprintf('%.*f', $digits, $rounded / $factor);
1759 }
1760  
1761 # `String.prototype.split(sep)` (#1448 Tier B) — string → ARRAY ref.
1762 #
1763 # Two JS-parity wrinkles drive the helper (a bare `split` emit would
1764 # diverge from both JS and Go):
1765 #
1766 # * Perl's `split` treats its first argument as a *regex*, so a
1767 # separator like '.' or '|' would match far too much. We
1768 # `quotemeta` it to force literal-string matching, mirroring JS's
1769 # string-separator semantics (the regex-separator form stays
1770 # refused upstream — see the parser arm).
1771 # * Perl's `split` drops trailing empty fields by default; JS keeps
1772 # them (`"a,".split(",")` is `["a", ""]`). Passing the `-1` limit
1773 # preserves them, matching JS and Go's `strings.Split`.
1774 #
1775 # An empty separator splits into individual characters (JS + Go agree).
1776 # Undef receiver renders as the single-element `['']` — the same
1777 # "missing prop → empty string" convention `bf->trim` uses.
1778  
1779 21 ▶sub split ($self, $recv, $sep = $OMITTED, $limit = $OMITTED) {
Subroutine split: called CC=10 SCAR=23.0
Pod undocumented
1780 21 ▶ my $s = defined $recv && !ref($recv) ? "$recv" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $recv && !ref($recv) ? : 20 1 21
Condition66%2/3
defined $recv and not ref $recv
!ll&&!rl&&r
1020
MC/DC50%1/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table66%2/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1781  
1782 21 my @parts;
1783 21 ▶ if (_omitted($sep)) {
Branch: 3 branches
BranchTrueFalseTotal
if (_omitted($sep)) { } 2 19 21
elsif (($sep = _js_string($sep)) eq '') { } 2 17 19
elsif ($s eq '') { } 1 16 17
1784 # No separator → the whole string in a single-element array
1785 # (matches JS `"x".split()` / `.split(undefined)`). Any other one is
1786 # ToString'd (`null` splits on "null").
1787 2 @parts = ($s);
1788 }
1789 elsif (($sep = _js_string($sep)) eq '') {
1790 # Empty separator → individual characters. No `-1` limit here:
1791 # on an empty pattern Perl's `split` with `-1` appends a spurious
1792 # trailing empty field ("abc" → 'a','b','c',''), which JS/Go don't.
1793 2 @parts = split //, $s;
1794 }
1795 elsif ($s eq '') {
1796 # Empty input with a non-empty separator: JS `"".split(",")` is
1797 # `[""]` and Go's `strings.Split("", ",")` is `[""]`, but Perl's
1798 # `split /,/, ''` returns the empty list — special-case for parity.
1799 1 @parts = ('');
1800 }
1801 else {
1802 # `quotemeta` forces literal-string matching (JS string-separator
1803 # semantics); the `-1` keeps trailing empty fields (JS keeps them,
1804 # Perl's bare `split` drops them).
1805 16 my $q = quotemeta("$sep");
1806 16 @parts = split /$q/, $s, -1;
1807 }
1808  
1809 # Optional `limit` caps the number of pieces (JS `split(sep, limit)`):
1810 # an omitted or `undefined` one is unbounded, any other one ToUint32'd
1811 # (`null` and NaN are 0 → empty; a negative limit wraps to a large one,
1812 # effectively unbounded).
1813 21 ▶ unless (_omitted($limit)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_omitted($limit)) 5 16 21
1814 5 my $n = _to_uint32($limit);
1815 5 ▶ @parts = @parts[0 .. $n - 1] if $n < scalar @parts;
Branch: 1 branch
BranchTrueFalseTotal
if $n < scalar @parts 3 2 5
1816 }
1817  
1818 21 return [@parts];
1819 }
1820  
1821 # `String.prototype.startsWith(prefix, position?)` (#1448 Tier B) —
1822 # string → boolean (1 / 0). `substr`-anchored literal comparison mirrors
1823 # Go's `strings.HasPrefix`. An empty prefix is always true (JS parity);
1824 # undef / non-string receivers coerce to the empty string first. The
1825 # optional `position` re-anchors the test (UTF-16 code units, clamped to
1826 # `[0, length]`), matching JS `"abc".startsWith("b", 1)`.
1827  
1828 17 ▶sub starts_with ($self, $recv, $prefix, $position = $OMITTED) {
Subroutine starts_with: called CC=8 SCAR=20.8
Pod undocumented
1829 17 ▶ my $s = defined $recv && !ref($recv) ? "$recv" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $recv && !ref($recv) ? : 15 2 17
Condition66%2/3
defined $recv and not ref $recv
!ll&&!rl&&r
2015
MC/DC50%1/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table66%2/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1830 17 my $p = _js_string($prefix);
1831 # An omitted or `undefined` position is 0; `null` is 0 too.
1832 17 ▶ unless (_omitted($position)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_omitted($position)) 9 8 17
1833 # `position` counts UTF-16 code units, like JS (#3613).
1834 9 my $units = _utf16_units($s);
1835 9 my $n = $self->_to_integer_or_infinity($position);
1836 9 ▶ $n = 0 if $n < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $n < 0 1 8 9
1837 9 ▶ $n = @$units if $n > @$units;
Branch: 1 branch
BranchTrueFalseTotal
if $n > @$units 2 7 9
1838 9 return _utf16_has_at($units, _utf16_units($p), $n);
1839 }
1840 8 ▶ return substr($s, 0, CORE::length $p) eq $p ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
substr($s, 0, CORE::length $p) eq $p ? : 5 3 8
1841 }
1842  
1843 # `String.prototype.endsWith(suffix, endPosition?)` (#1448 Tier B) —
1844 # string → boolean (1 / 0). Mirrors Go's `strings.HasSuffix`. An empty
1845 # suffix is always true (JS parity); a suffix longer than the string is
1846 # false. `substr($s, -length $x)` would mis-read the whole string when
1847 # `length $x == 0`, so that case short-circuits. The optional
1848 # `endPosition` treats the string as if it were only that many UTF-16
1849 # code units long (clamped to `[0, length]`), matching JS
1850 # `"abc".endsWith("b", 2)`.
1851  
1852 17 ▶sub ends_with ($self, $recv, $suffix, $end_position = $OMITTED) {
Subroutine ends_with: called CC=10 SCAR=23.1
Pod undocumented
1853 17 ▶ my $s = defined $recv && !ref($recv) ? "$recv" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $recv && !ref($recv) ? : 17 0 17
Condition33%1/3
defined $recv and not ref $recv
!ll&&!rl&&r
0017
MC/DC0%0/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table33%1/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1854 17 my $x = _js_string($suffix);
1855 # An omitted or `undefined` endPosition is the length; `null` is 0.
1856 17 ▶ unless (_omitted($end_position)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_omitted($end_position)) 10 7 17
1857 # `endPosition` counts UTF-16 code units, like JS (#3613).
1858 10 my $units = _utf16_units($s);
1859 10 my $needle = _utf16_units($x);
1860 10 my $e = $self->_to_integer_or_infinity($end_position);
1861 10 ▶ $e = 0 if $e < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $e < 0 1 9 10
1862 10 ▶ $e = @$units if $e > @$units;
Branch: 1 branch
BranchTrueFalseTotal
if $e > @$units 2 8 10
1863 10 return _utf16_has_at($units, $needle, $e - @$needle);
1864 }
1865 7 ▶ return 1 if $x eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $x eq "" 1 6 7
1866 6 ▶ return 0 if CORE::length($s) < CORE::length($x);
Branch: 1 branch
BranchTrueFalseTotal
if CORE::length $s < CORE::length $x 1 5 6
1867 5 ▶ return substr($s, -CORE::length $x) eq $x ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
substr($s, -CORE::length($x)) eq $x ? : 3 2 5
1868 }
1869  
1870 # `String.prototype.replace(pattern, replacement)` — string-pattern
1871 # form only (#1448 Tier B), replacing the FIRST occurrence (JS string-
1872 # pattern semantics). Spliced via index/substr rather than `s///` so
1873 # BOTH the pattern and the replacement are literal: no Perl regex
1874 # metacharacters in the pattern and no `$1` / `$&` interpolation in the
1875 # replacement. Go's `bf_replace` (strings.Replace, n=1) treats the
1876 # replacement literally too, so the two adapters stay byte-equal — this
1877 # diverges from JS only for replacement strings containing `$`-patterns
1878 # (rare in template position). An empty pattern inserts the replacement
1879 # at the front (`"abc".replace("", "X")` → "Xabc"), matching JS + Go.
1880  
1881 9 ▶sub replace ($self, $recv, $pattern, $replacement) {
Subroutine replace: called CC=5 SCAR=16.1
Pod undocumented
1882 9 ▶ my $s = defined $recv && !ref($recv) ? "$recv" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $recv && !ref($recv) ? : 8 1 9
Condition66%2/3
defined $recv and not ref $recv
!ll&&!rl&&r
108
MC/DC50%1/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table66%2/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1883 # The pattern and the replacement are JS ToString'd.
1884 9 my $o = _js_string($pattern);
1885 9 my $n = _js_string($replacement);
1886 9 ▶ return $n . $s if $o eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $o eq "" 1 8 9
1887 8 my $i = index($s, $o);
1888 8 ▶ return $s if $i < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $i < 0 2 6 8
1889 6 return substr($s, 0, $i) . $n . substr($s, $i + CORE::length($o));
1890 }
1891  
1892 # `String.prototype.replaceAll(pattern, replacement)` — string-pattern
1893 # form only (#2182), replacing EVERY occurrence (the all-occurrences
1894 # sibling of `replace` above). Same literal-splice approach (no regex
1895 # metacharacters, no `$1`/`$&` interpolation) as `replace`, looped
1896 # forward from each match's end. An empty pattern inserts the
1897 # replacement at every boundary, including before the first and after
1898 # the last character (`"abc".replaceAll("", "X")` -> "XaXbXcX"),
1899 # matching JS.
1900  
1901 0 ▶sub replace_all ($self, $recv, $pattern, $replacement) {
Subroutine replace_all: not called CC=5 SCAR=34.0
Pod undocumented
1902 0 ▶ my $s = defined $recv && !ref($recv) ? "$recv" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $recv && !ref($recv) ? : 0 0 0
Condition0%0/3
defined $recv and not ref $recv
!ll&&!rl&&r
000
MC/DC0%0/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table0%0/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1903 # The pattern and the replacement are JS ToString'd.
1904 0 my $o = _js_string($pattern);
1905 0 my $n = _js_string($replacement);
1906 0 ▶ return CORE::join($n, '', split(//, $s), '') if $o eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $o eq "" 0 0 0
1907 0 my $out = '';
1908 0 my $pos = 0;
1909 0 my $olen = CORE::length($o);
1910 0 while (1) {
1911 0 my $i = index($s, $o, $pos);
1912 0 ▶ last if $i < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $i < 0 0 0 0
1913 0 $out .= substr($s, $pos, $i - $pos) . $n;
1914 0 $pos = $i + $olen;
1915 }
1916 0 $out .= substr($s, $pos);
1917 0 return $out;
1918 }
1919  
1920 # `queryHref(base, { … })` (#2042) — build `"$base?k=v&…"` from a flat list of
1921 # (guard, key, value) triples. A pair is included iff its guard is truthy AND
1922 # its value is a non-empty string, mirroring the client `queryHref`'s `if
1923 # (value)` over string values: the adapter passes the guard `1` for a plain
1924 # `key: v`, or the lowered condition for `key: cond ? v : undefined`. Repeating a
1925 # key overwrites the value at its first position (`URLSearchParams.set`
1926 # semantics).
1927 #
1928 # A value may instead be an array ref, which APPENDS one pair per non-empty
1929 # member (`{ tag => ['a','b'] }` → `tag=a&tag=b`, i.e. `URLSearchParams.append`);
1930 # empty members are skipped, so an empty/all-empty array contributes nothing.
1931 #
1932 # Keys/values are form-encoded to equal the browser render byte-for-byte; no
1933 # surviving pair yields the bare base.
1934 5 ▶sub query ($self, $base, @triples) {
Subroutine query: called CC=17 SCAR=29.5
Pod undocumented
1935 5 ▶ my $b = defined $base && !ref($base) ? "$base" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $base && !ref($base) ? : 5 0 5
Condition33%1/3
defined $base and not ref $base
!ll&&!rl&&r
005
MC/DC0%0/2
defined $base and not ref $base
defined $base not ref $base
Truth table33%1/3
A and not(B)
A= defined $baseB= not ref $base
ABresult
0X0
100
111
1936 5 my (@pairs, %pos);
1937 5 my $i = 0;
1938 5 ▶ while ($i + 2 < @triples) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i + 2 < @triples) 8 5 13
1939 8 my ($guard, $key, $val) = @triples[$i, $i + 1, $i + 2];
1940 8 $i += 3;
1941 8 ▶ next unless $guard;
Branch: 1 branch
BranchTrueFalseTotal
unless $guard 0 8 8
1942 8 ▶ $key = defined $key && !ref($key) ? "$key" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $key && !ref($key) ? : 8 0 8
Condition33%1/3
defined $key and not ref $key
!ll&&!rl&&r
008
MC/DC0%0/2
defined $key and not ref $key
defined $key not ref $key
Truth table33%1/3
A and not(B)
A= defined $keyB= not ref $key
ABresult
0X0
100
111
1943 8 ▶ if (ref($val) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq "ARRAY") 1 7 8
1944 # Append each non-empty member; appended pairs never overwrite, so
1945 # they don't participate in the set()-position map.
1946 1 for my $m (@$val) {
1947 3 ▶ my $s = defined $m && !ref($m) ? "$m" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $m && !ref($m) ? : 3 0 3
Condition33%1/3
defined $m and not ref $m
!ll&&!rl&&r
003
MC/DC0%0/2
defined $m and not ref $m
defined $m not ref $m
Truth table33%1/3
A and not(B)
A= defined $mB= not ref $m
ABresult
0X0
100
111
1948 3 ▶ next if $s eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $s eq "" 1 2 3
1949 2 push @pairs, [$key, $s];
1950 }
1951 1 next;
1952 }
1953 7 ▶ $val = defined $val && !ref($val) ? "$val" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $val && !ref($val) ? : 5 2 7
Condition66%2/3
defined $val and not ref $val
!ll&&!rl&&r
205
MC/DC50%1/2
defined $val and not ref $val
defined $val not ref $val
Truth table66%2/3
A and not(B)
A= defined $valB= not ref $val
ABresult
0X0
100
111
1954 7 ▶ next if $val eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $val eq "" 2 5 7
1955 5 ▶ if (exists $pos{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $pos{$key}) { } 1 4 5
1956 1 $pairs[$pos{$key}][1] = $val;
1957 }
1958 else {
1959 4 $pos{$key} = scalar @pairs;
1960 4 push @pairs, [$key, $val];
1961 }
1962 }
1963 5 ▶ return $b unless @pairs;
Branch: 1 branch
BranchTrueFalseTotal
unless @pairs 1 4 5
1964 4 return "$b?" . CORE::join('&', map { _form_escape($_->[0]) . '=' . _form_escape($_->[1]) } @pairs);
1965 }
1966  
1967 # `String.prototype.repeat(n)` — the receiver concatenated n times
1968 # (#1448 Tier B), via Perl's `x` operator. JS throws RangeError for a
1969 # negative count, but SSR templates degrade to the empty string rather
1970 # than dying mid-render, so a count <= 0 returns "" (Go's `bf_repeat`
1971 # applies the same clamp). The count is truncated toward zero
1972 # (`int`), matching JS's ToIntegerOrInfinity on `"a".repeat(3.7)`.
1973  
1974 8 ▶sub repeat ($self, $recv, $count = $OMITTED) {
Subroutine repeat: called CC=6 SCAR=17.9
Pod undocumented
1975 8 ▶ my $s = defined $recv && !ref($recv) ? "$recv" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $recv && !ref($recv) ? : 7 1 8
Condition66%2/3
defined $recv and not ref $recv
!ll&&!rl&&r
107
MC/DC50%1/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table66%2/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1976 # ToIntegerOrInfinity: an omitted, `undefined` or `null` count is 0.
1977 8 ▶ my $n = $self->_to_integer_or_infinity(_omitted($count) ? $UNDEF : $count);
Branch: 1 branch
BranchTrueFalseTotal
_omitted($count) ? : 1 7 8
1978 8 ▶ return $n <= 0 ? '' : $s x $n;
Branch: 1 branch
BranchTrueFalseTotal
$n <= 0 ? : 3 5 8
1979 }
1980  
1981 # `String.prototype.padStart` / `padEnd` (#1448 Tier B) — pad the
1982 # receiver to `$target` characters with `$pad` (default a single space)
1983 # repeated and truncated to fill, prepended or appended. Length is
1984 # measured in characters (Perl `length`), matching Go's rune-based
1985 # `bf_pad_*` — diverges from JS's UTF-16-unit length only for
1986 # astral-plane input. An empty pad, or a receiver already >= `$target`,
1987 # returns the receiver unchanged (JS parity). The `$target` is
1988 # truncated toward zero (JS ToLength on the first arg).
1989  
1990 12 ▶sub _pad ($self, $s, $target, $pad, $at_start) {
Subroutine _pad: called CC=6 SCAR=17.9
1991 # An omitted or `undefined` pad string is a space; any other one is
1992 # ToString'd (`null` pads with "null"). The target is ToIntegerOrInfinity'd.
1993 12 ▶ $pad = _omitted($pad) ? ' ' : _js_string($pad);
Branch: 1 branch
BranchTrueFalseTotal
_omitted($pad) ? : 3 9 12
1994 12 ▶ return $s if $pad eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $pad eq "" 1 11 12
1995 11 my $len = CORE::length $s;
1996 11 ▶ my $t = $self->_to_integer_or_infinity(_omitted($target) ? $UNDEF : $target);
Branch: 1 branch
BranchTrueFalseTotal
_omitted($target) ? : 0 11 11
1997 11 ▶ return $s if $len >= $t;
Branch: 1 branch
BranchTrueFalseTotal
if $len >= $t 1 10 11
1998 10 my $need = $t - $len;
1999 # Repeat enough copies to cover $need, then trim to exactly $need.
2000 10 my $fill = substr($pad x (int($need / CORE::length($pad)) + 1), 0, $need);
2001 10 ▶ return $at_start ? $fill . $s : $s . $fill;
Branch: 1 branch
BranchTrueFalseTotal
$at_start ? : 7 3 10
2002 }
2003  
2004 9 ▶sub pad_start ($self, $recv, $target = $OMITTED, $pad = $OMITTED) {
Subroutine pad_start: called CC=5 SCAR=16.2
Pod undocumented
2005 9 ▶ my $s = defined $recv && !ref($recv) ? "$recv" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $recv && !ref($recv) ? : 8 1 9
Condition66%2/3
defined $recv and not ref $recv
!ll&&!rl&&r
108
MC/DC50%1/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table66%2/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
2006 9 return $self->_pad($s, $target, $pad, 1);
2007 }
2008  
2009 3 ▶sub pad_end ($self, $recv, $target = $OMITTED, $pad = $OMITTED) {
Subroutine pad_end: called CC=5 SCAR=17.8
Pod undocumented
2010 3 ▶ my $s = defined $recv && !ref($recv) ? "$recv" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $recv && !ref($recv) ? : 3 0 3
Condition33%1/3
defined $recv and not ref $recv
!ll&&!rl&&r
003
MC/DC0%0/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table33%1/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
2011 3 return $self->_pad($s, $target, $pad, 0);
2012 }
2013  
2014 # JS `ToUint32` (`split`'s limit): NaN and the infinities are 0.
2015 5 ▶sub _to_uint32 ($value) {
Subroutine _to_uint32: called CC=6 SCAR=19.1
2016 5 my $n = _js_number($value);
2017 5 ▶ return 0 if $n != $n || $n == 9**9**9 || $n == -(9**9**9);
Branch: 1 branch
BranchTrueFalseTotal
if $n != $n or $n == "Inf" or $n == "-Inf" 0 5 5
Condition33%2/6
$n != $n or $n == "Inf" or $n == "-Inf"
l!l&&r!l&&!r
005
$n != $n or $n == "Inf"
l!l&&r!l&&!r
005
MC/DC0%0/3
$n != $n or $n == "Inf" or $n == "-Inf"
$n != $n $n == "Inf" $n == "-Inf"
Truth table25%1/4
A or B or C
A= $n != $nB= $n == "Inf"C= $n == "-Inf"
ABCresult
1XX1
01X1
0011
0000
2018 5 ▶ my $t = $n < 0 ? POSIX::ceil($n) : POSIX::floor($n);
Branch: 1 branch
BranchTrueFalseTotal
$n < 0 ? : 1 4 5
2019 5 $t = POSIX::fmod($t, 4294967296);
2020 5 ▶ $t += 4294967296 if $t < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $t < 0 1 4 5
2021 5 return $t;
2022 }
2023  
2024 # A row field's value: JS `item.key`, `undefined` when the row has no such
2025 # field (or is no object).
2026 25 ▶sub _field_value ($item, $key) {
Subroutine _field_value: called CC=3 SCAR=11.1
2027 25 ▶ return $UNDEF unless ref($item) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item eq "HASH" 0 25 25
2028 25 ▶ return exists $item->{$key} ? $item->{$key} : $UNDEF;
Branch: 1 branch
BranchTrueFalseTotal
exists $item->{$key} ? : 24 1 25
2029 }
2030  
2031 # `Array.prototype.sort(cmp)` / `Array.prototype.toSorted(cmp)`
2032 # lowering (#1448 Tier B). Non-mutating — JS's mutate-vs-new
2033 # distinction is moot in SSR template context.
2034 #
2035 # Opts hash-ref. The compiler emits a `keys` list of per-key hashes
2036 # in priority order; each hash carries:
2037 #
2038 # key_kind => 'self' | 'field'
2039 # key => '' when key_kind eq 'self'; field name verbatim
2040 # from the comparator AST (e.g. 'price', 'createdAt')
2041 # when key_kind eq 'field' — no case normalisation
2042 # applied. Perl hash lookups are case-sensitive so
2043 # the key here must match the actual hash key the
2044 # user populated.
2045 # compare_type => 'numeric' | 'string' | 'auto'
2046 # direction => 'asc' | 'desc'
2047 #
2048 # Accepted comparator catalogue (gated upstream at parse time —
2049 # anything outside refuses with BF101 before reaching this helper):
2050 #
2051 # (a,b) => a.f - b.f → field, numeric
2052 # (a,b) => a - b → self, numeric
2053 # (a,b) => a[.f].localeCompare(b[.f]) → field|self, string
2054 # (a,b) => a.f > b.f ? 1 : -1 → field|self, auto
2055 # any of the above ||-chained → multi-key tie-breaks
2056 # (and reversed-operand variants for `desc`).
2057 #
2058 # `auto` (relational-ternary lowering) compares numerically when both
2059 # keys `looks_like_number`, else lexically — Go's `bf_sort` applies the
2060 # same rule so the two template adapters stay byte-equal.
2061 #
2062 # A future `nulls => 'first' | 'last'` knob can land per key without
2063 # churn — the opts hash is the right place to grow.
2064  
2065 # Evaluator-driven sort / reduce (#2018): the comparator / reducer body rides
2066 # as a serialized-ParsedExpr JSON string and is evaluated per element, delegating
2067 # to the shared BarefootJS::Evaluator. The adapter emits `bf->sort_eval(...)` /
2068 # `bf->reduce_eval(...)` for any pure comparator / reducer body; a body it can't
2069 # model (e.g. localeCompare) keeps the legacy `bf->sort` / `bf->reduce` path.
2070 1 ▶sub sort_eval ($self, $recv, $cmp_json, $param_a, $param_b, $base_env = {}) {
Subroutine sort_eval: called CC=2 SCAR=6.9
Pod undocumented
2071 1 return BarefootJS::Evaluator::sort_by_json($recv, $cmp_json, $param_a, $param_b, $base_env);
2072 }
2073  
2074 0 ▶sub reduce_eval ($self, $recv, $body_json, $acc_name, $item_name, $init, $direction = 'left', $base_env = {}) {
Subroutine reduce_eval: not called CC=3 SCAR=24.8
Pod undocumented
2075 0 return BarefootJS::Evaluator::fold_json($recv, $body_json, $acc_name, $item_name, $init, $direction, $base_env);
2076 }
2077  
2078 # Evaluator-driven higher-order predicates (#2018, P2): the predicate body
2079 # rides as a serialized-ParsedExpr JSON string evaluated per element, delegating
2080 # to the shared BarefootJS::Evaluator. The adapter emits `bf->filter_eval(...)`
2081 # etc. for any pure predicate; a body it can't model (e.g. a method-call
2082 # predicate) keeps the legacy `grep` / `bf->find` path. `find_eval` /
2083 # `find_index_eval` take a `$forward` flag (false → findLast / findLastIndex).
2084 0 ▶sub filter_eval ($self, $recv, $pred_json, $param, $base_env = {}) {
Subroutine filter_eval: not called CC=2 SCAR=17.9
Pod undocumented
2085 0 return BarefootJS::Evaluator::filter_json($recv, $pred_json, $param, $base_env);
2086 }
2087  
2088 0 ▶sub every_eval ($self, $recv, $pred_json, $param, $base_env = {}) {
Subroutine every_eval: not called CC=2 SCAR=17.9
Pod undocumented
2089 0 return BarefootJS::Evaluator::every_json($recv, $pred_json, $param, $base_env);
2090 }
2091  
2092 0 ▶sub some_eval ($self, $recv, $pred_json, $param, $base_env = {}) {
Subroutine some_eval: not called CC=2 SCAR=17.9
Pod undocumented
2093 0 return BarefootJS::Evaluator::some_json($recv, $pred_json, $param, $base_env);
2094 }
2095  
2096 0 ▶sub find_eval ($self, $recv, $pred_json, $param, $forward = 1, $base_env = {}) {
Subroutine find_eval: not called CC=3 SCAR=24.8
Pod undocumented
2097 0 return BarefootJS::Evaluator::find_json($recv, $pred_json, $param, $forward, $base_env);
2098 }
2099  
2100 0 ▶sub find_index_eval ($self, $recv, $pred_json, $param, $forward = 1, $base_env = {}) {
Subroutine find_index_eval: not called CC=3 SCAR=24.8
Pod undocumented
2101 0 return BarefootJS::Evaluator::find_index_json($recv, $pred_json, $param, $forward, $base_env);
2102 }
2103  
2104 0 ▶sub flat_map_eval ($self, $recv, $proj_json, $param, $base_env = {}) {
Subroutine flat_map_eval: not called CC=2 SCAR=17.9
Pod undocumented
2105 0 return BarefootJS::Evaluator::flat_map_json($recv, $proj_json, $param, $base_env);
2106 }
2107  
2108 # Value-producing `.map(cb)` (#2073): project each element through the
2109 # serialized projection body, one result per element (no flatten). Composes
2110 # through the array-method chain (`.map(cb).join(' ')`).
2111 0 ▶sub map_eval ($self, $recv, $proj_json, $param, $base_env = {}) {
Subroutine map_eval: not called CC=2 SCAR=17.9
Pod undocumented
2112 0 return BarefootJS::Evaluator::map_json($recv, $proj_json, $param, $base_env);
2113 }
2114  
2115 17 ▶sub sort ($self, $recv, $opts = {}) {
Subroutine sort: called CC=10 SCAR=23.2
Pod undocumented
2116 17 ▶ return [] unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 3 14 17
2117  
2118 # Normalise the per-key specs (priority order, length >= 1).
2119 my @spec = map {
2120 {
2121 key_kind => $_->{key_kind} // 'self',
2122 key => $_->{key} // '',
2123 compare_type => $_->{compare_type} // 'numeric',
2124 16 ▶ direction => $_->{direction} // 'asc',
Condition62%5/8
$_->{"key_kind"} // "self"
l!l
160
$_->{"key"} // ""
l!l
97
$_->{"compare_type"} // "numeric"
l!l
160
$_->{"direction"} // "asc"
l!l
160
MC/DC0%0/1
$_->{"key_kind"} // "self"
$_->{"key_kind"}
MC/DC100%1/1
$_->{"key"} // ""
$_->{"key"}
MC/DC0%0/1
$_->{"compare_type"} // "numeric"
$_->{"compare_type"}
MC/DC0%0/1
$_->{"direction"} // "asc"
$_->{"direction"}
Truth table50%1/2
A
A= $_->{"key_kind"}
Aresult
11
00
Truth table100%2/2
A
A= $_->{"key"}
Aresult
11
00
Truth table50%1/2
A
A= $_->{"compare_type"}
Aresult
11
00
Truth table50%1/2
A
A= $_->{"direction"}
Aresult
11
00
2125 }
2126 14 ▶ } @{ $opts->{keys} // [] };
Condition50%1/2
$opts->{"keys"} // []
l!l
140
MC/DC0%0/1
$opts->{"keys"} // []
$opts->{"keys"}
Truth table50%1/2
A
A= $opts->{"keys"}
Aresult
11
00
2127 14 ▶ return [ @$recv ] unless @spec;
Branch: 1 branch
BranchTrueFalseTotal
unless @spec 0 14 14
2128  
2129 # JS moves every `undefined` element to the end without handing it to
2130 # the comparator.
2131 14 my @tail = grep { _undef_p($_) } @$recv;
2132  
2133 # Schwartzian transform: project each item to all its sort keys
2134 # once, then compare projected keys. Cheaper than re-resolving the
2135 # field accessors inside every comparison for non-trivial arrays.
2136 my @keyed = map {
2137 40 my $item = $_;
2138 my @ks = map {
2139 40 ▶ $_->{key_kind} eq 'field' ? _field_value($item, $_->{key}) : $item;
Branch: 1 branch
BranchTrueFalseTotal
$_->{'key_kind'} eq 'field' ? : 24 22 46
2140 } @spec;
2141 40 [ \@ks, $item ];
2142 14 } grep { !_undef_p($_) } @$recv;
2143  
2144 40 ▶ my $cmp = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
2145 40 for my $i (0 .. $#spec) {
2146 44 my $sp = $spec[$i];
2147 44 my $c = _compare_sort_key($a->[0][$i], $b->[0][$i], $sp->{compare_type});
2148 44 ▶ next if $c == 0; # tie on this key — try the next
Branch: 1 branch
BranchTrueFalseTotal
if $c == 0 7 37 44
2149 37 ▶ return $sp->{direction} eq 'desc' ? -$c : $c;
Branch: 1 branch
BranchTrueFalseTotal
$sp->{'direction'} eq 'desc' ? : 9 28 37
2150 }
2151 3 return 0;
2152 14 };
2153  
2154 14 my @sorted = sort $cmp @keyed;
2155 14 return [ (map { $_->[1] } @sorted), @tail ];
2156 }
2157  
2158 # Compare two projected keys, ascending orientation (-1 / 0 / 1); the
2159 # caller negates for 'desc'. 'auto' compares numerically when both
2160 # keys look like numbers, else lexically (matches Go's `bf_sort`).
2161 # A nil key (`null` / `undefined`) reads as '' lexically and `null` as 0
2162 # numerically, so the order stays total without warnings; a numeric
2163 # `a.f - b.f` over an `undefined` key is NaN, which the sort reads as
2164 # "equal".
2165 44 ▶sub _compare_sort_key ($av, $bv, $compare_type) {
Subroutine _compare_sort_key: called CC=15 SCAR=29.7
2166 44 ▶ my $str = sub ($v) { _nullish($v) ? '' : $v };
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
_nullish($v) ? : 0 26 26
2167 44 ▶ if ($compare_type eq 'string') {
Branch: 1 branch
BranchTrueFalseTotal
if ($compare_type eq "string") 10 34 44
2168 10 return $str->($av) cmp $str->($bv);
2169 }
2170 34 ▶ if ($compare_type eq 'auto') {
Branch: 1 branch
BranchTrueFalseTotal
if ($compare_type eq "auto") 9 25 34
2171 9 ▶ if (!_undef_p($av) && !_undef_p($bv) && looks_like_number($av // '') && looks_like_number($bv // '')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not _undef_p($av) || _undef_p($bv) and &looks_like_number(scalar($av // "")) and &looks_like_number(scalar($bv // ""))) 6 3 9
Condition53%7/13
not _undef_p($av) || _undef_p($bv) and &looks_like_number(scalar($av // "")) and &looks_like_number(scalar($bv // ""))
!ll&&!rl&&r
306
not _undef_p($av) || _undef_p($bv) and &looks_like_number(scalar($av // ""))
!ll&&!rl&&r
036
_undef_p($av) || _undef_p($bv)
l!l&&r!l&&!r
009
$av // ""
l!l
90
$bv // ""
l!l
60
MC/DC25%1/4
not _undef_p($av) || _undef_p($bv) and &looks_like_number(scalar($av // "")) and &looks_like_number(scalar($bv // ""))
_undef_p($av) _undef_p($bv) &looks_like_number(scalar($av // "")) &looks_like_number(scalar($bv // ""))
MC/DC0%0/1
$av // ""
$av
MC/DC0%0/1
$bv // ""
$bv
Truth table40%2/5
not(A || B) and C and D
A= _undef_p($av)B= _undef_p($bv)C= &looks_like_number(scalar($av // ""))D= &looks_like_number(scalar($bv // ""))
ABCDresult
1XXX0
01XX0
000X0
00100
00111
Truth table50%1/2
A
A= $av
Aresult
11
00
Truth table50%1/2
A
A= $bv
Aresult
11
00
2172 6 ▶ return ($av // 0) <=> ($bv // 0);
Condition50%2/4
$av // 0
l!l
60
$bv // 0
l!l
60
MC/DC0%0/1
$av // 0
$av
MC/DC0%0/1
$bv // 0
$bv
Truth table50%1/2
A
A= $av
Aresult
11
00
Truth table50%1/2
A
A= $bv
Aresult
11
00
2173 }
2174 3 return $str->($av) cmp $str->($bv);
2175 }
2176 25 ▶ return 0 if _undef_p($av) || _undef_p($bv);
Branch: 1 branch
BranchTrueFalseTotal
if _undef_p($av) or _undef_p($bv) 0 25 25
Condition33%1/3
_undef_p($av) or _undef_p($bv)
l!l&&r!l&&!r
0025
MC/DC0%0/2
_undef_p($av) or _undef_p($bv)
_undef_p($av) _undef_p($bv)
Truth table33%1/3
A or B
A= _undef_p($av)B= _undef_p($bv)
ABresult
1X1
011
000
2177 25 ▶ return ($av // 0) <=> ($bv // 0); # numeric
Condition100%4/4
$av // 0
l!l
241
$bv // 0
l!l
241
MC/DC100%1/1
$av // 0
$av
MC/DC100%1/1
$bv // 0
$bv
Truth table100%2/2
A
A= $av
Aresult
11
00
Truth table100%2/2
A
A= $bv
Aresult
11
00
2178 }
2179  
2180 # Fold an array into a scalar via the arithmetic-fold catalogue
2181 # (#1448 Tier C). Mirrors Go's `bf_reduce` and JS `reduce(fn, init)` /
2182 # `reduceRight(fn, init)` for the shapes `(acc, x) => acc <op> x` /
2183 # `(acc, x) => acc <op> x.field`:
2184 #
2185 # bf->reduce($recv, {
2186 # op => '+' | '*',
2187 # key_kind => 'self' | 'field',
2188 # key => '<field>', # when key_kind eq 'field'
2189 # type => 'numeric' | 'string',
2190 # init => <seed>, # number, or string for concat
2191 # direction => 'left' | 'right', # 'right' = reduceRight (default 'left')
2192 # })
2193 #
2194 # Numeric folds accumulate with `+` / `*` (non-numeric keys coalesce to
2195 # 0); string folds concatenate via `bf->string` (undef → ''). The init
2196 # seeds the accumulator, so an empty array returns it unchanged — exactly
2197 # like JS. `direction => 'right'` folds right-to-left (reduceRight); only
2198 # observable for string concat, since numeric sum / product commute.
2199 # Float stringification can diverge from Go's for inexact binary
2200 # fractions (e.g. 0.1 + 0.2); integer sums — the common case — agree.
2201 0 ▶sub reduce ($self, $recv, $opts = {}) {
Subroutine reduce: not called CC=17 SCAR=57.2
Pod undocumented
2202 0 ▶ my $op = $opts->{op} // '+';
Condition0%0/2
$opts->{"op"} // "+"
l!l
00
MC/DC0%0/1
$opts->{"op"} // "+"
$opts->{"op"}
Truth table0%0/2
A
A= $opts->{"op"}
Aresult
11
00
2203 0 ▶ my $key_kind = $opts->{key_kind} // 'self';
Condition0%0/2
$opts->{"key_kind"} // "self"
l!l
00
MC/DC0%0/1
$opts->{"key_kind"} // "self"
$opts->{"key_kind"}
Truth table0%0/2
A
A= $opts->{"key_kind"}
Aresult
11
00
2204 0 ▶ my $key = $opts->{key} // '';
Condition0%0/2
$opts->{"key"} // ""
l!l
00
MC/DC0%0/1
$opts->{"key"} // ""
$opts->{"key"}
Truth table0%0/2
A
A= $opts->{"key"}
Aresult
11
00
2205 0 ▶ my $type = $opts->{type} // 'numeric';
Condition0%0/2
$opts->{"type"} // "numeric"
l!l
00
MC/DC0%0/1
$opts->{"type"} // "numeric"
$opts->{"type"}
Truth table0%0/2
A
A= $opts->{"type"}
Aresult
11
00
2206 0 ▶ my $direction = $opts->{direction} // 'left';
Condition0%0/2
$opts->{"direction"} // "left"
l!l
00
MC/DC0%0/1
$opts->{"direction"} // "left"
$opts->{"direction"}
Truth table0%0/2
A
A= $opts->{"direction"}
Aresult
11
00
2207  
2208 0 ▶ my @items = ref($recv) eq 'ARRAY' ? @$recv : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $recv eq 'ARRAY' ? : 0 0 0
2209 # reduceRight folds right-to-left; reversing the snapshot keeps the
2210 # single forward loop below. Only observable for string concat —
2211 # numeric sum / product commute. Qualify as CORE::reverse — this
2212 # package defines `sub reverse` (the `.reverse()` helper), so a bare
2213 # `reverse` is ambiguous under `use warnings`.
2214 0 ▶ @items = CORE::reverse(@items) if $direction eq 'right';
Branch: 1 branch
BranchTrueFalseTotal
if $direction eq "right" 0 0 0
2215 0 ▶ my $project = sub ($item) {
Subroutine __ANON__: not called CC=3 SCAR=24.8
2216 0 ▶ $key_kind eq 'field' && ref($item) eq 'HASH' ? $item->{$key} : $item;
Branch: 1 branch
BranchTrueFalseTotal
$key_kind eq 'field' && ref $item eq 'HASH' ? : 0 0 0
Condition0%0/3
$key_kind eq "field" and ref $item eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
$key_kind eq "field" and ref $item eq "HASH"
$key_kind eq "field" ref $item eq "HASH"
Truth table0%0/3
A and B
A= $key_kind eq "field"B= ref $item eq "HASH"
ABresult
0X0
100
111
2217 0 };
2218 # The catalogue folds read a nil (`null` / `undefined`) item as '' / 0
2219 # (`string` / the numeric guard below), as they always have.
2220  
2221 0 ▶ if ($type eq 'string') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "string") 0 0 0
2222 0 ▶ my $acc = $opts->{init} // '';
Condition0%0/2
$opts->{"init"} // ""
l!l
00
MC/DC0%0/1
$opts->{"init"} // ""
$opts->{"init"}
Truth table0%0/2
A
A= $opts->{"init"}
Aresult
11
00
2223 0 $acc .= $self->string($project->($_)) for @items;
2224 0 return $acc;
2225 }
2226  
2227 0 ▶ my $acc = $opts->{init} // 0;
Condition0%0/2
$opts->{"init"} // 0
l!l
00
MC/DC0%0/1
$opts->{"init"} // 0
$opts->{"init"}
Truth table0%0/2
A
A= $opts->{"init"}
Aresult
11
00
2228 0 for my $item (@items) {
2229 0 my $n = $project->($item);
2230 # Guard `defined` before `looks_like_number` so a missing field
2231 # (undef) folds as 0 without an "uninitialized value" warning
2232 # under `use warnings` — matching the `$av // ''` style `sort` uses.
2233 0 ▶ $n = 0 if _nullish($n) || !looks_like_number($n);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($n) or not &looks_like_number($n) 0 0 0
Condition0%0/3
_nullish($n) or not &looks_like_number($n)
l!l&&r!l&&!r
000
MC/DC0%0/2
_nullish($n) or not &looks_like_number($n)
_nullish($n) not &looks_like_number($n)
Truth table0%0/3
A or not(B)
A= _nullish($n)B= not &looks_like_number($n)
ABresult
1X1
011
000
2234 0 ▶ $op eq '*' ? ($acc *= $n) : ($acc += $n);
Branch: 1 branch
BranchTrueFalseTotal
$op eq '*' ? : 0 0 0
2235 }
2236 0 return $acc;
2237 }
2238  
2239 # ---------------------------------------------------------------------------
2240 # JSX intrinsic-element spread (#1407)
2241 # ---------------------------------------------------------------------------
2242 #
2243 # Mirrors the JS `spreadAttrs` runtime
2244 # (`packages/client/src/runtime/spread-attrs.ts`) and the Go adapter's
2245 # `bf.SpreadAttrs` so SSR output stays byte-equal across the three
2246 # adapters. Generated Mojo templates invoke this as
2247 # `<%== bf->spread_attrs($bag) %>`.
2248 #
2249 # Skip rules: nil/false values, event handlers (`on[A-Z]…` shape
2250 # matching JS `key[2] === key[2].toUpperCase()` — true for any
2251 # character whose uppercase is itself, including digits and
2252 # underscore), `children`. `ref` is intentionally NOT filtered,
2253 # matching the JS reference.
2254 #
2255 # Key remap: className → class, htmlFor → for; SVG camelCase
2256 # attrs preserved (case-sensitive XML spec); other camelCase keys
2257 # lowered to kebab-case with a leading `-` for an initial
2258 # uppercase letter (mirrors JS `key.replace(/([A-Z])/g, '-$1')`).
2259 #
2260 # `style` is routed through `_style_to_css` so object literals
2261 # serialise to a real CSS string instead of Perl's default
2262 # `HASH(0x...)` form.
2263 #
2264 # Output is deterministic: keys are sorted alphabetically before
2265 # emission, matching the Go adapter's `sort.Strings(keys)` policy
2266 # and Mojo::JSON's marshal order.
2267 #
2268 # The return value is a Mojo::ByteStream so the calling template's
2269 # `<%==` raw-emit skips re-escaping (the helper has already
2270 # HTML-escaped each value).
2271  
2272 17 my %SVG_CAMEL_CASE_ATTRS = map { $_ => 1 } qw(
2273 allowReorder attributeName attributeType autoReverse
2274 baseFrequency baseProfile calcMode clipPathUnits
2275 contentScriptType contentStyleType diffuseConstant edgeMode
2276 externalResourcesRequired filterRes filterUnits glyphRef
2277 gradientTransform gradientUnits kernelMatrix kernelUnitLength
2278 keyPoints keySplines keyTimes lengthAdjust limitingConeAngle
2279 markerHeight markerUnits markerWidth maskContentUnits
2280 maskUnits numOctaves pathLength patternContentUnits
2281 patternTransform patternUnits pointsAtX pointsAtY pointsAtZ
2282 preserveAlpha preserveAspectRatio primitiveUnits refX refY
2283 repeatCount repeatDur requiredExtensions requiredFeatures
2284 specularConstant specularExponent spreadMethod startOffset
2285 stdDeviation stitchTiles surfaceScale systemLanguage
2286 tableValues targetX targetY textLength viewBox viewTarget
2287 xChannelSelector yChannelSelector zoomAndPan
2288 );
2289  
2290 23 ▶sub _to_attr_name ($key) {
Subroutine _to_attr_name: called CC=4 SCAR=13.9
2291 23 ▶ return 'class' if $key eq 'className';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "className" 1 22 23
2292 22 ▶ return 'for' if $key eq 'htmlFor';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "htmlFor" 1 21 22
2293 21 ▶ return $key if $SVG_CAMEL_CASE_ATTRS{$key};
Branch: 1 branch
BranchTrueFalseTotal
if $SVG_CAMEL_CASE_ATTRS{$key} 2 19 21
2294 # camelCase → kebab-case, with a leading `-` for an initial
2295 # uppercase letter (JS-reference parity, even though that case
2296 # produces an HTML-invalid attribute name — same documented
2297 # behaviour as the Go adapter's `toAttrName`).
2298 19 my $out = $key;
2299 19 $out =~ s/([A-Z])/-\L$1/g;
2300 19 return $out;
2301 }
2302  
2303 12 ▶sub _form_escape ($s) {
Subroutine _form_escape: called CC=3 SCAR=11.2
2304 # application/x-www-form-urlencoded serialisation, matching the browser's
2305 # `URLSearchParams` (which the SSR query render must equal): keep ASCII
2306 # alphanumerics and `* - . _`; encode every other byte as `%XX` (UPPER hex);
2307 # space → `+`. Non-ASCII is encoded byte-wise over its UTF-8 bytes.
2308 12 ▶ my $bytes = defined $s ? "$s" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $s ? : 12 0 12
2309 12 ▶ utf8::encode($bytes) if utf8::is_utf8($bytes);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($bytes) 0 12 12
2310 12 $bytes =~ s/([^A-Za-z0-9*\-._ ])/sprintf('%%%02X', ord($1))/ge;
2311 12 $bytes =~ tr/ /+/;
2312 12 return $bytes;
2313 }
2314  
2315 26 ▶sub _html_escape ($value) {
Subroutine _html_escape: called CC=2 SCAR=7.0
2316 # HTML attribute-value escape for SSR string emission. The
2317 # spread bag's values reach the browser as part of a generated
2318 # `key="..."` substring inside the rendered HTML, so the
2319 # escape set has to cover everything that could break either
2320 # the surrounding double-quoted attribute or the enclosing
2321 # tag: `&`, `<`, `>`, `"`, and `'`. Matches Go's
2322 # `template.HTMLEscapeString` semantics byte-for-byte (using
2323 # `&#34;` / `&#39;` for quotes rather than the named entities)
2324 # so the SSR output is identical across the Go and Mojo
2325 # adapters (#1407, #1413 review). The CSR-side
2326 # `applyRestAttrs` calls `el.setAttribute(name, String(value))`
2327 # — which does its own DOM-level escaping in the browser —
2328 # so JS doesn't need an explicit escape pass; Perl/Go emit a
2329 # string, so we do.
2330 26 ▶ my $s = defined $value ? "$value" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 26 0 26
2331 26 $s =~ s/&/&amp;/g;
2332 26 $s =~ s/</&lt;/g;
2333 26 $s =~ s/>/&gt;/g;
2334 26 $s =~ s/"/&#34;/g;
2335 26 $s =~ s/'/&#39;/g;
2336 26 return $s;
2337 }
2338  
2339 2 ▶sub _style_to_css ($value) {
Subroutine _style_to_css: called CC=7 SCAR=19.9
2340 2 ▶ return undef if _nullish($value);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($value) 0 2 2
2341 # Non-hashref values pass through stringified — matches the JS
2342 # `typeof value !== 'object'` branch in `styleToCss`.
2343 2 ▶ if (ref($value) ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value ne "HASH") 1 1 2
2344 1 my $s = "$value";
2345 1 ▶ return CORE::length $s ? $s : undef;
Branch: 1 branch
BranchTrueFalseTotal
CORE::length $s ? : 1 0 1
2346 }
2347 1 my @parts;
2348 1 for my $key (sort keys %$value) {
2349 2 my $v = $value->{$key};
2350 2 ▶ next if _nullish($v);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($v) 0 2 2
2351 2 my $prop = $key;
2352 2 $prop =~ s/([A-Z])/-\L$1/g;
2353 2 push @parts, "$prop:$v";
2354 }
2355 1 ▶ return @parts ? CORE::join(';', @parts) : undef;
Branch: 1 branch
BranchTrueFalseTotal
@parts ? : 1 0 1
2356 }
2357  
2358  
2359 # Object-rest residual for a `.map()` destructure binding
2360 # (`{ id, ...rest } => …`, #2087 Phase B): returns a NEW hashref holding
2361 # every key of `$bag` except those named in `$keys` (an ARRAY ref of key
2362 # strings). This is plain JS destructure semantics (`const { id, ...rest }
2363 # = item`) — unlike `spread_attrs` below, there's no event-handler /
2364 # `children` filtering or key remapping here, because the residual is a
2365 # *value* the template may read fields off of (`$rest->{flag}`) or later
2366 # forward wholesale to `spread_attrs` (`{...rest}` on an element) — either
2367 # consumer applies its own rules downstream. A non-hashref `$bag` returns
2368 # an empty hashref rather than dying, so this stays safe as a `my` local
2369 # initializer even off unexpected/absent data (same defensive contract as
2370 # `spread_attrs`'s "no bag → nothing").
2371 # Structural scan for characters that could break a value out of a CSS
2372 # declaration -- ported byte-for-byte from Hono's own `hasUnsafeStyleValue`
2373 # (`hono/jsx/utils.ts`), the ORACLE this adapter's dynamic `style={{...}}`
2374 # values must match (#2261). NOT real CSSOM property validation. Every
2375 # character this scan tests is ASCII, so scanning by character (this file's
2376 # `use utf8` makes Perl string ops character-indexed) agrees with Hono's
2377 # UTF-16-code-unit scan for every input -- a non-ASCII codepoint can never
2378 # spuriously match one of these single-character comparisons.
2379 0 ▶sub _has_unsafe_style_value ($value) {
Subroutine _has_unsafe_style_value: not called CC=27 SCAR=66.3
2380 0 my $quote = '';
2381 0 my @block_stack;
2382 0 my $len = CORE::length $value;
2383 0 my $i = 0;
2384 0 ▶ while ($i < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 0 0 0
2385 0 my $c = substr($value, $i, 1);
2386 0 ▶ if ($c eq '\\') {
Branch: 9 branches
BranchTrueFalseTotal
if ($c eq '\\') { } 0 0 0
elsif ($quote ne '') { } 0 0 0
elsif ($c eq '/' and $i + 1 < $len and substr($value, $i + 1, 1) eq '*') { } 0 0 0
elsif ($c eq '"' or $c eq q[']) { } 0 0 0
elsif ($c eq '(') { } 0 0 0
elsif ($c eq '[') { } 0 0 0
elsif ($c eq '{' or $c eq '}') { } 0 0 0
elsif ($c eq ')' or $c eq ']') { } 0 0 0
elsif ($c eq ';' and not @block_stack) { } 0 0 0
2387 0 ▶ return 1 if $i == $len - 1;
Branch: 1 branch
BranchTrueFalseTotal
if $i == $len - 1 0 0 0
2388 0 $i++;
2389 }
2390 elsif ($quote ne '') {
2391 0 ▶ return 1 if $c eq "\n" || $c eq "\f" || $c eq "\r";
Branch: 1 branch
BranchTrueFalseTotal
if $c eq "\n" or $c eq "\f" or $c eq "\r" 0 0 0
Condition0%0/6
$c eq "\n" or $c eq "\f" or $c eq "\r"
l!l&&r!l&&!r
000
$c eq "\n" or $c eq "\f"
l!l&&r!l&&!r
000
MC/DC0%0/3
$c eq "\n" or $c eq "\f" or $c eq "\r"
$c eq "\n" $c eq "\f" $c eq "\r"
Truth table0%0/4
A or B or C
A= $c eq "\n"B= $c eq "\f"C= $c eq "\r"
ABCresult
1XX1
01X1
0011
0000
2392 0 ▶ $quote = '' if $c eq $quote;
Branch: 1 branch
BranchTrueFalseTotal
if $c eq $quote 0 0 0
2393 }
2394 ▶ elsif ($c eq '/' && $i + 1 < $len && substr($value, $i + 1, 1) eq '*') {
Condition0%0/6
$c eq "/" and $i + 1 < $len and substr($value, $i + 1, 1) eq "*"
!ll&&!rl&&r
000
$c eq "/" and $i + 1 < $len
!ll&&!rl&&r
000
MC/DC0%0/3
$c eq "/" and $i + 1 < $len and substr($value, $i + 1, 1) eq "*"
$c eq "/" $i + 1 < $len substr($value, $i + 1, 1) eq "*"
Truth table0%0/4
A and B and C
A= $c eq "/"B= $i + 1 < $lenC= substr($value, $i + 1, 1) eq "*"
ABCresult
0XX0
10X0
1100
1111
2395 0 my $end = index($value, '*/', $i + 2);
2396 0 ▶ return 1 if $end < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $end < 0 0 0 0
2397 0 $i = $end + 1;
2398 }
2399 ▶ elsif ($c eq '"' || $c eq "'") {
Condition0%0/3
$c eq "\"" or $c eq "'"
l!l&&r!l&&!r
000
MC/DC0%0/2
$c eq "\"" or $c eq "'"
$c eq "\"" $c eq "'"
Truth table0%0/3
A or B
A= $c eq "\""B= $c eq "'"
ABresult
1X1
011
000
2400 0 $quote = $c;
2401 }
2402 elsif ($c eq '(') {
2403 0 push @block_stack, ')';
2404 }
2405 elsif ($c eq '[') {
2406 0 push @block_stack, ']';
2407 }
2408 ▶ elsif ($c eq '{' || $c eq '}') {
Condition0%0/3
$c eq "{" or $c eq "}"
l!l&&r!l&&!r
000
MC/DC0%0/2
$c eq "{" or $c eq "}"
$c eq "{" $c eq "}"
Truth table0%0/3
A or B
A= $c eq "{"B= $c eq "}"
ABresult
1X1
011
000
2409 0 return 1;
2410 }
2411 ▶ elsif ($c eq ')' || $c eq ']') {
Condition0%0/3
$c eq ")" or $c eq "]"
l!l&&r!l&&!r
000
MC/DC0%0/2
$c eq ")" or $c eq "]"
$c eq ")" $c eq "]"
Truth table0%0/3
A or B
A= $c eq ")"B= $c eq "]"
ABresult
1X1
011
000
2412 0 ▶ return 1 if !@block_stack || $block_stack[-1] ne $c;
Branch: 1 branch
BranchTrueFalseTotal
if not @block_stack or $block_stack[-1] ne $c 0 0 0
Condition0%0/3
not @block_stack or $block_stack[-1] ne $c
l!l&&r!l&&!r
000
MC/DC0%0/2
not @block_stack or $block_stack[-1] ne $c
not @block_stack $block_stack[-1] ne $c
Truth table0%0/3
not(A) or B
A= not @block_stackB= $block_stack[-1] ne $c
ABresult
1X1
011
000
2413 0 pop @block_stack;
2414 }
2415 ▶ elsif ($c eq ';' && !@block_stack) {
Condition0%0/3
$c eq ";" and not @block_stack
!ll&&!rl&&r
000
MC/DC0%0/2
$c eq ";" and not @block_stack
$c eq ";" not @block_stack
Truth table0%0/3
A and not(B)
A= $c eq ";"B= not @block_stack
ABresult
0X0
100
111
2416 0 return 1;
2417 }
2418 0 $i++;
2419 }
2420 0 ▶ return ($quote ne '' || @block_stack) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$quote ne '' || @block_stack ? : 0 0 0
Condition0%0/3
$quote ne "" or @block_stack
l!l&&r!l&&!r
000
MC/DC0%0/2
$quote ne "" or @block_stack
$quote ne "" @block_stack
Truth table0%0/3
A or B
A= $quote ne ""B= @block_stack
ABresult
1X1
011
000
2421 }
2422  
2423 # Builds the CSS string for a `style={{...}}` JSX object-literal attribute
2424 # (#2261). `@pairs` alternates CSS key (always compile-time-known), then
2425 # value. A value that fails `_has_unsafe_style_value` (after JS-`String()`-
2426 # style stringification) is DROPPED -- the whole `key:value` pair is
2427 # omitted -- matching Hono's oracle exactly. The joined string is STILL
2428 # HTML-escaped (mirroring Hono's own `escapeToBuffer` call) since a
2429 # structurally "safe" value can still carry a literal `"`/`'`/`&`. Marked
2430 # raw so the calling template's raw-emit form doesn't re-escape it.
2431 0 ▶sub style_object ($self, @pairs) {
Subroutine style_object: not called CC=3 SCAR=24.8
Pod undocumented
2432 0 my @parts;
2433 0 ▶ for (my $i = 0; $i + 1 < @pairs; $i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i + 1 < @pairs) 0 0 0
2434 0 my $key = $self->string($pairs[$i]);
2435 0 my $value = $self->string($pairs[$i + 1]);
2436 0 ▶ next if _has_unsafe_style_value($value);
Branch: 1 branch
BranchTrueFalseTotal
if _has_unsafe_style_value($value) 0 0 0
2437 0 push @parts, _html_escape($key) . ":" . _html_escape($value);
2438 }
2439 0 return $self->backend->mark_raw(CORE::join(';', @parts));
2440 }
2441  
2442 8 ▶sub omit ($self, $bag, $keys) {
Subroutine omit: called CC=3 SCAR=11.0
Pod undocumented
2443 8 ▶ return {} unless defined $bag && ref($bag) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bag and ref $bag eq "HASH" 2 6 8
Condition100%3/3
defined $bag and ref $bag eq "HASH"
!ll&&!rl&&r
116
MC/DC100%2/2
defined $bag and ref $bag eq "HASH"
defined $bag ref $bag eq "HASH"
Truth table100%3/3
A and B
A= defined $bagB= ref $bag eq "HASH"
ABresult
0X0
100
111
2444 6 my %exclude = map { $_ => 1 } @$keys;
2445 6 return { map { $_ => $bag->{$_} } grep { !$exclude{$_} } keys %$bag };
2446 }
2447  
2448 25 ▶sub spread_attrs ($self, $bag) {
Subroutine spread_attrs: called CC=16 SCAR=27.8
Pod undocumented
2449 25 ▶ return '' unless defined $bag && ref($bag) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bag and ref $bag eq "HASH" 2 23 25
Condition100%3/3
defined $bag and ref $bag eq "HASH"
!ll&&!rl&&r
1123
MC/DC100%2/2
defined $bag and ref $bag eq "HASH"
defined $bag ref $bag eq "HASH"
Truth table100%3/3
A and B
A= defined $bagB= ref $bag eq "HASH"
ABresult
0X0
100
111
2450 23 my @parts;
2451 23 for my $key (sort keys %$bag) {
2452 # Event handlers: skip when key starts `on` and the third
2453 # character is its own uppercase form (uppercase letter,
2454 # digit, underscore, …). Mirrors the JS predicate.
2455 31 ▶ if (CORE::length($key) > 2 && substr($key, 0, 2) eq 'on') {
Branch: 1 branch
BranchTrueFalseTotal
if (CORE::length $key > 2 and substr($key, 0, 2) eq "on") 4 27 31
Condition100%3/3
CORE::length $key > 2 and substr($key, 0, 2) eq "on"
!ll&&!rl&&r
11164
MC/DC100%2/2
CORE::length $key > 2 and substr($key, 0, 2) eq "on"
CORE::length $key > 2 substr($key, 0, 2) eq "on"
Truth table100%3/3
A and B
A= CORE::length $key > 2B= substr($key, 0, 2) eq "on"
ABresult
0X0
100
111
2456 4 my $c = substr($key, 2, 1);
2457 4 ▶ next if CORE::uc($c) eq $c;
Branch: 1 branch
BranchTrueFalseTotal
if CORE::uc $c eq $c 3 1 4
2458 }
2459 28 ▶ next if $key eq 'children';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "children" 1 27 28
2460 27 my $val = $bag->{$key};
2461 # null / undefined → drop.
2462 27 ▶ next if _nullish($val);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($val) 1 26 27
2463 # Boolean values arrive as Mojo::JSON sentinel objects
2464 # (`Mojo::JSON::true` / `false`) — both from JSON-deserialised
2465 # props and from the test harness's `toPerlLiteral`
2466 # (which emits the sentinels rather than plain 0/1 to avoid
2467 # conflating booleans with numeric attribute values like
2468 # `tabindex="0"`). The contract is: callers MUST use the
2469 # sentinels for boolean values; plain Perl scalars 0/1
2470 # render as numeric attribute values, matching how JS
2471 # `spreadAttrs` treats a `0`/`1` JS number.
2472 26 ▶ if (ref($val) eq 'JSON::PP::Boolean' || ref($val) eq 'Mojo::JSON::_Bool') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq "JSON::PP::Boolean" or ref $val eq "Mojo::JSON::_Bool") 2 24 26
Condition66%2/3
ref $val eq "JSON::PP::Boolean" or ref $val eq "Mojo::JSON::_Bool"
l!l&&r!l&&!r
2024
MC/DC50%1/2
ref $val eq "JSON::PP::Boolean" or ref $val eq "Mojo::JSON::_Bool"
ref $val eq "JSON::PP::Boolean" ref $val eq "Mojo::JSON::_Bool"
Truth table66%2/3
A or B
A= ref $val eq "JSON::PP::Boolean"B= ref $val eq "Mojo::JSON::_Bool"
ABresult
1X1
011
000
2473 2 ▶ next unless $val;
Branch: 1 branch
BranchTrueFalseTotal
unless $val 1 1 2
2474 1 push @parts, _to_attr_name($key);
2475 1 next;
2476 }
2477 # `style` routes through `_style_to_css` so object literals
2478 # serialise to a real CSS string.
2479 24 ▶ if ($key eq 'style') {
Branch: 1 branch
BranchTrueFalseTotal
if ($key eq "style") 2 22 24
2480 2 my $css = _style_to_css($val);
2481 2 ▶ next unless defined $css && CORE::length $css;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $css and CORE::length $css 0 2 2
Condition33%1/3
defined $css and CORE::length $css
!ll&&!rl&&r
002
MC/DC0%0/2
defined $css and CORE::length $css
defined $css CORE::length $css
Truth table33%1/3
A and B
A= defined $cssB= CORE::length $css
ABresult
0X0
100
111
2482 2 push @parts, qq{style="} . _html_escape($css) . qq{"};
2483 2 next;
2484 }
2485 22 my $name = _to_attr_name($key);
2486 22 push @parts, $name . qq{="} . _html_escape($val) . qq{"};
2487 }
2488 23 ▶ return '' unless @parts;
Branch: 1 branch
BranchTrueFalseTotal
unless @parts 1 22 23
2489 # Mark the result raw so the calling template's `<%==` raw-emit
2490 # doesn't re-escape the already-escaped values (the Mojo backend
2491 # returns a Mojo::ByteStream).
2492 22 return $self->backend->mark_raw(CORE::join(' ', @parts));
2493 }
2494  
2495 # ---------------------------------------------------------------------------
2496 # BarefootJS::Date -- this runtime's native date/time type, holding a single
2497 # epoch-ms integer. Exists so a Perl host can hand `date()` (above) a real
2498 # typed value instead of always going through the ISO-8601 string half of
2499 # the helper's contract (mirrors the Go runtime's `time.Time` / the Ruby
2500 # runtime's `Time` as the "native" receiver shape in spec/template-helpers.md
2501 # "date"). Deliberately minimal: one field, one constructor -- this is a
2502 # value wrapper, not a full calendar API.
2503 # ---------------------------------------------------------------------------
2504 package BarefootJS::Date;
2505  
2506 # Must carry its own literal $VERSION. META's `provides` is built by
2507 # Module::Metadata (see Makefile.PL), which reads each package's own
2508 # $VERSION and reports undef for one that has none -- and since a dist
2509 # with `provides` makes PAUSE index from META instead of scanning the
2510 # .pm files, an undef here is what PAUSE compares against the previously
2511 # indexed version. That reads as a *decreasing* version number and the
2512 # package drops out of the index -- which is what happened to this one in
2513 # BarefootJS-0.30.0, freezing it at the 0.29.0 tarball. It has to be
2514 # a literal string: Module::Metadata evaluates the version line in a Safe
2515 # compartment where `$BarefootJS::VERSION` is not visible and collapses to
2516 # 0. scripts/sync-perl-versions.ts bumps every `our $VERSION` line in the
2517 # file, so this stays in lockstep with the package version above.
2518 17 our $VERSION = "0.41.3";
2519  
2520 0 ▶sub new {
Subroutine new: not called CC=1 SCAR=6.9
2521 0 my ($class, $epoch_ms) = @_;
2522 0 return bless { epoch_ms => $epoch_ms }, $class;
2523 }
2524  
2525 package BarefootJS;
2526  
2527 17 1;
2528 __END__
↑ Summary lib/BarefootJS/Evaluator.pm »