blib/lib/BarefootJS/DevReload.pm

filter: Statementstmt 82.6% 62 / 75 Branchbran 62.5% 10 / 16 Conditioncond 41.6% 5 / 12 MC/DCmcdc 14.2% 1 / 7 Subroutinesub 100% 13 / 13 Podpod 0.0% 0 / 5 totaltotal 71.0% 91 / 128 CC 14 SCAR 18.2
CC
14
Cov
75%
__ANON__
16.5
__ANON__
4.1
read_build_id
4.0
CRAP 6.2
« lib/BarefootJS/Evaluator.pm ↑ Summary lib/BarefootJS/Undefined.pm »
1 package BarefootJS::DevReload;
2 1 our $VERSION = "0.41.3";
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use feature 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶no warnings 'experimental::signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 1 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 =encoding utf8
11  
12 =head1 NAME
13  
14 BarefootJS::DevReload - Framework-agnostic dev-only browser auto-reload for BarefootJS apps
15  
16 =head1 SYNOPSIS
17  
18 # Plain PSGI / Plack (e.g. the Text::Xslate backend)
19 use BarefootJS::DevReload;
20  
21 # Mount the SSE endpoint (dev only):
22 my $reload = BarefootJS::DevReload->to_app(dist_dir => 'dist');
23 # ... route '/_bf/reload' => $reload ...
24  
25 # And emit the browser snippet before </body> in your layout:
26 BarefootJS::DevReload->snippet('/_bf/reload');
27  
28 =head1 DESCRIPTION
29  
30 Companion to C<barefoot build --watch> in C<@barefootjs/cli>. The CLI drops
31 C<< <dist>/.dev/build-id >> after every successful rebuild that changed output;
32 a browser snippet subscribes to an SSE endpoint that emits C<< event: reload >>
33 when that file changes, so an editor save triggers an automatic reload.
34  
35 This module holds the engine-agnostic pieces — the browser snippet, the
36 build-id reader, and a ready-made PSGI streaming app for the SSE endpoint — so
37 both L<Mojolicious::Plugin::BarefootJS::DevReload> (Mojo streaming) and plain
38 PSGI/Plack hosts (the Text::Xslate backend) share one implementation.
39  
40 =cut
41  
42 # Sentinel path contract with @barefootjs/cli (DEV_SENTINEL_SUBDIR /
43 # DEV_SENTINEL_FILENAME in packages/cli/src/lib/build.ts). Duplicated so this
44 # package avoids a runtime dep on the CLI — keep in sync with the CLI.
45 1 my $DEV_SUBDIR = '.dev';
46 1 my $BUILD_ID_FILE = 'build-id';
47  
48 1 our $SCROLL_STORAGE_KEY = '__bf_devreload_scroll';
49  
50 # Heartbeat < any reasonable proxy/IOLoop idle timeout so a quiet connection
51 # doesn't get reaped between rebuilds.
52 1 our $HEARTBEAT_S = 5;
53  
54 # Polling instead of Linux::Inotify2 / Mac::FSEvents keeps the runtime
55 # dependency-free. Sub-second latency is imperceptible next to browser reload.
56 1 our $POLL_S = 0.5;
57  
58 # <dist>/.dev/build-id — the sentinel `barefoot build --watch` rewrites.
59 2 ▶sub build_id_path ($class, $dist_dir) {
Subroutine build_id_path: called CC=1 SCAR=0.0
Pod undocumented
60 2 return File::Spec->catfile($dist_dir, $DEV_SUBDIR, $BUILD_ID_FILE);
61 }
62  
63 # Ensure <dist>/.dev exists so the watcher can write the sentinel even if the
64 # server started first. Returns the dir.
65 2 ▶sub ensure_dev_dir ($class, $dist_dir) {
Subroutine ensure_dev_dir: called CC=2 SCAR=6.9
Pod undocumented
66 2 my $dev = File::Spec->catdir($dist_dir, $DEV_SUBDIR);
67 2 ▶ mkdir $dev unless -d $dev;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dev 1 1 2
68 2 return $dev;
69 }
70  
71 4 ▶sub read_build_id ($class, $path) {
Subroutine read_build_id: called CC=4 SCAR=14.0
Pod undocumented
72 4 ▶ return '' unless -f $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path 1 3 4
73 3 ▶ open my $fh, '<', $path or return '';
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $path or return "" 3 0 3
74 3 local $/;
75 3 my $content = <$fh>;
76 3 close $fh;
77 3 ▶ $content //= '';
Condition50%1/2
$content //= ""
l!l
30
MC/DC0%0/1
$content //= ""
$content
Truth table50%1/2
A
A= $content
Aresult
11
00
78 3 $content =~ s/^\s+|\s+$//g;
79 3 return $content;
80 }
81  
82 # The browser snippet: a small IIFE — EventSource subscriber + scrollY
83 # preservation across reloads. Idempotent across duplicate mounts (the
84 # window.__bfDevReload guard). Returns a plain HTML string; callers mark it raw
85 # for their template engine.
86 1 ▶sub snippet ($class, $endpoint) {
Subroutine snippet: called CC=1 SCAR=0.0
Pod undocumented
87 1 my $ep = _js_str($endpoint);
88 1 my $sk = _js_str($SCROLL_STORAGE_KEY);
89 1 return qq{<script>(function(){if(window.__bfDevReload)return;window.__bfDevReload=1;try{var s=sessionStorage.getItem($sk);if(s){sessionStorage.removeItem($sk);var y=parseInt(s,10);if(!isNaN(y)){var restore=function(){window.scrollTo(0,y)};if(document.readyState==='loading'){addEventListener('DOMContentLoaded',restore,{once:true})}else{restore()}}}}catch(e){}var es=new EventSource($ep);es.addEventListener('reload',function(){try{sessionStorage.setItem($sk,String(window.scrollY))}catch(e){}location.reload()});es.addEventListener('error',function(){})})();</script>};
90 }
91  
92 # A ready-made PSGI app for the SSE endpoint. Streams `event: reload` whenever
93 # <dist>/.dev/build-id changes, with `: hb` heartbeats in between.
94 #
95 # Implemented with the PSGI streaming interface and a blocking poll loop, so it
96 # holds one worker per open connection for the connection's lifetime — run it
97 # under a prefork PSGI server (Starman / Starlet) in dev, which is the natural
98 # choice for an app that also streams (e.g. an AI-chat SSE route). DevReload is
99 # automatically a no-op unless you mount it, and you should only mount it in
100 # development.
101 1 ▶sub to_app ($class, %opts) {
Subroutine to_app: called CC=2 SCAR=8.7
Pod undocumented
102 1 ▶ my $dist_dir = $opts{dist_dir} // 'dist';
Condition50%1/2
$opts{"dist_dir"} // "dist"
l!l
10
MC/DC0%0/1
$opts{"dist_dir"} // "dist"
$opts{"dist_dir"}
Truth table50%1/2
A
A= $opts{"dist_dir"}
Aresult
11
00
103 1 my $build_id_path = $class->build_id_path($dist_dir);
104 1 $class->ensure_dev_dir($dist_dir);
105  
106 3 ▶ return sub ($env) {
Subroutine __ANON__: called CC=3 SCAR=14.2
107 return [500, ['Content-Type' => 'text/plain'], ['DevReload needs a psgi.streaming server']]
108 3 ▶ unless $env->{'psgi.streaming'};
Branch: 1 branch
BranchTrueFalseTotal
unless $env->{"psgi.streaming"} 1 2 3
109  
110 2 ▶ my $last_event_id = $env->{HTTP_LAST_EVENT_ID} // '';
Condition50%1/2
$env->{"HTTP_LAST_EVENT_ID"} // ""
l!l
20
MC/DC0%0/1
$env->{"HTTP_LAST_EVENT_ID"} // ""
$env->{"HTTP_LAST_EVENT_ID"}
Truth table50%1/2
A
A= $env->{"HTTP_LAST_EVENT_ID"}
Aresult
11
00
111 2 $last_event_id =~ s/^\s+|\s+$//g;
112  
113 2 ▶ return sub ($responder) {
Subroutine __ANON__: called CC=7 SCAR=28.0
114 2 my $writer = $responder->([
115 200,
116 [
117 'Content-Type' => 'text/event-stream',
118 'Cache-Control' => 'no-cache, no-transform',
119 'X-Accel-Buffering' => 'no',
120 ],
121 ]);
122  
123 # A write to a disconnected client throws (SIGPIPE/EPIPE); the eval
124 # turns that into a clean loop exit.
125 2 local $SIG{PIPE} = 'IGNORE';
126 2 eval {
127 2 $writer->write("retry: 1000\n\n");
128  
129 2 my $initial = $class->read_build_id($build_id_path);
130 2 my $last_sent = '';
131 2 ▶ if (length $initial) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $initial) 2 0 2
132 2 $last_sent = $initial;
133 # A stale Last-Event-ID means a build happened while the
134 # client was disconnected — fire `reload` immediately so the
135 # missed rebuild doesn't stay unpainted.
136 2 ▶ my $event = (length $last_event_id && $last_event_id ne $initial)
Branch: 1 branch
BranchTrueFalseTotal
length $last_event_id && $last_event_id ne $initial ? : 1 1 2
Condition66%2/3
length $last_event_id and $last_event_id ne $initial
!ll&&!rl&&r
101
MC/DC50%1/2
length $last_event_id and $last_event_id ne $initial
length $last_event_id $last_event_id ne $initial
Truth table66%2/3
A and B
A= length $last_event_idB= $last_event_id ne $initial
ABresult
0X0
100
111
137 ? 'reload' : 'hello';
138 2 $writer->write("event: $event\nid: $initial\ndata: $initial\n\n");
139 }
140  
141 0 my $since_hb = 0;
142 0 while (1) {
143 0 select undef, undef, undef, $POLL_S;
144 0 my $id = $class->read_build_id($build_id_path);
145 0 ▶ if (length $id && $id ne $last_sent) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $id and $id ne $last_sent) { } 0 0 0
Condition0%0/3
length $id and $id ne $last_sent
!ll&&!rl&&r
000
MC/DC0%0/2
length $id and $id ne $last_sent
length $id $id ne $last_sent
Truth table0%0/3
A and B
A= length $idB= $id ne $last_sent
ABresult
0X0
100
111
146 0 $last_sent = $id;
147 0 $since_hb = 0;
148 0 $writer->write("event: reload\nid: $id\ndata: $id\n\n");
149 }
150 else {
151 0 $since_hb += $POLL_S;
152 0 ▶ if ($since_hb >= $HEARTBEAT_S) {
Branch: 1 branch
BranchTrueFalseTotal
if ($since_hb >= $BarefootJS::DevReload::HEARTBEAT_S) 0 0 0
153 0 $since_hb = 0;
154 0 $writer->write(": hb\n\n");
155 }
156 }
157 }
158 0 1;
159 };
160 2 $writer->close;
161 2 };
162 1 };
163 }
164  
165 2 ▶sub _js_str ($s) {
Subroutine _js_str: called CC=1 SCAR=0.0
166 # Minimal JS string escape for the handful of characters that can appear in
167 # a URL path or storage key. Good enough for package-internal + trusted
168 # operator-supplied strings; never interpolate untrusted input here.
169 2 my $t = $s;
170 2 $t =~ s/\\/\\\\/g;
171 2 $t =~ s/"/\\"/g;
172 2 $t =~ s/\n/\\n/g;
173 2 $t =~ s/\r/\\r/g;
174 2 return qq{"$t"};
175 }
176  
177 1 1;
« lib/BarefootJS/Evaluator.pm ↑ Summary lib/BarefootJS/Undefined.pm »