capybara-lightpanda 0.17.1 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f73305ebb70a014b9b5345eade37ec044e2b07cbe99cf30a9eaa2bdbdb80eca5
4
- data.tar.gz: '095323a36971553487cfa1517df1e08bf67f7a188599e5d93c7db4d44d58868b'
3
+ metadata.gz: f7f40b21e78951ba7f1434247d4685db414730460bc2b40d3ffa1fc06801bd32
4
+ data.tar.gz: 295d5170fd0f09da10e1a1017b034b5017257d2ca9326271ee2a94f949e178fa
5
5
  SHA512:
6
- metadata.gz: eba98666f4f06a68d008bd04248aa8be99a0b2f03ec5d214cd3f2b02fee2f2685085c5fe44c2045faa2e992a090f8b25c13a21e8a703e799d079461aa20bb5ac
7
- data.tar.gz: 483d3b13353f17e76378a3a0d991a1d5951779a4ea9f4e51b7b6c99485ca66ff1b3efecbdce65c51bb49e49ee11a83e2d7a5da0c7ec2d79d93de0c036e029118
6
+ metadata.gz: 60c1891000fd8024f1183d687c89d698a4c793a940fa2c8250144e9b7a6afdbffb72e5c579737cf4edf9b16b08b951135d8199d4a67502121c29650ddfdc00d3
7
+ data.tar.gz: cce0bef954fa8935fa4badaa2a355d8f20b5f676957866c8cf8da4252487a8c0316a2c4ee2b2ac4a874d60b46798c1bddde7be72f7e17c3c2163201f7728ef1c
data/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.19.0] - 2026-11-17
4
+
5
+ > **The default browser is now a release, not the nightly.** If you relied on the rolling nightly, set `Capybara::Lightpanda::Binary.required_version = "nightly"` or `LIGHTPANDA_VERSION=nightly`. `required_version = nil` now means "the gem's default release".
6
+
7
+ ### Changed
8
+
9
+ - **Each gem version downloads the Lightpanda release it was validated against** (1.0.4 for now) instead of that day's nightly. The browser changes when you upgrade the gem and not otherwise, and CI no longer breaks because of a nightly published that morning.
10
+ - **Upgrading the gem no longer leaves a too-old browser in the cache.** The binary is cached per version, so the new gem fetches its own release instead of failing at driver start with "Lightpanda … is too old". On the nightly, a cached build below the required version is now re-downloaded at once instead of being kept for up to 24 hours.
11
+
12
+ ### Added
13
+
14
+ - **`bundle exec capybara-lightpanda install`** downloads the browser ahead of the test run. Call it from `bin/setup` and from a CI step when your suite stubs HTTP (VCR/WebMock), which blocks the download the driver would otherwise do on first use. It takes a version (`install nightly`, `install 1.0.4`), `--force` to re-download, and `-r FILE` to load your `Binary.configure` block. `version`, `path` and `remove` are there too.
15
+ - **`LIGHTPANDA_VERSION`** picks the browser version from the environment.
16
+ - When a download is blocked and nothing is cached, the driver now prints the command to run, next to the HTTP stub's own error.
17
+
18
+ ## [0.18.0] - 2026-11-16
19
+
20
+ > **Update Lightpanda before upgrading.** This release requires Lightpanda **1.0.4** or a nightly build ≥ 12015. The driver refuses anything older and names the version it found. Pin `1.0.4` for a reproducible browser. On Intel Macs, Lightpanda 1.0.3 crashes on the first HTTPS request; 1.0.4 fixes that.
21
+
22
+ ### Fixed
23
+
24
+ - **`visit` waits for the page's JavaScript.** With a recent Lightpanda, `visit` could return before deferred and module scripts (Stimulus controllers, Turbo) had run, when the page took more than 2 seconds to load. The next `click` or `fill_in` then hit a page whose handlers weren't attached yet and was silently lost. `visit` now waits until those scripts have run.
25
+ - **`send_keys` on a rich-text editor types after the existing text.** On a `contenteditable` element that already held text, `send_keys` used to type in front of it ("xEdit me" instead of "Edit mex"). It now appends, as Chrome and WebDriver do.
26
+ - **A page with an iframe no longer lets `visit` or `click` move on too early.** When an iframe (an embedded widget, a video, a tweet) finished loading before the page itself, `visit` and a `click` that navigated returned while the page's own scripts were still pending, so the next click could do nothing. Seen on Forem: the comment menu never opened. They now wait for the page itself.
27
+ - **Text failure messages say what was searched for.** When no element held the text, `find("li", text: "…")` failed with just `Unable to find css "li"`. It now reads `Unable to find visible css "li" with text "…"`, and `assert_selector` lists the elements it rejected ("Also found …").
28
+
3
29
  ## [0.17.1] - 2026-11-08
4
30
 
5
31
  ### Fixed
data/README.md CHANGED
@@ -57,7 +57,7 @@ driven_by :lightpanda
57
57
  > Lightpanda is a headless agentic browser, not a layout engine. External `<link rel="stylesheet">` **are** fetched and applied (the gem enables this by default), and `@media` / `window.matchMedia()` evaluate against the `window_size` you configure — so a mobile-only CTA gated by `@media (max-width: …)` resolves at the width you ask for. What's missing is *layout*: nothing reflows, `getBoundingClientRect` stays synthetic, and there is no real scroll. Specs that assert on pixel geometry, scrolling, or screenshots can't pass here, nor can the two that catch people out: a second browser tab and a menu revealed purely by CSS `:hover`. See [known limitations](https://navidemad.github.io/capybara-lightpanda/docs/#limits).
58
58
 
59
59
  > [!TIP]
60
- > For reproducible CI, pin the browser: `Capybara::Lightpanda::Binary.required_version = "1.0.3"` (the tagged release the gem's current floor is pinned to — nightly build 11647 is that release's commit). Without a pin the driver tracks Lightpanda's rolling `nightly` tag, which moves under you. See [Pinning the browser version](https://navidemad.github.io/capybara-lightpanda/docs/#pinning).
60
+ > The gem downloads the Lightpanda release it was validated against (currently 1.0.4), so the browser only changes when you upgrade the gem. If your suite stubs HTTP (VCR/WebMock), run `bundle exec capybara-lightpanda install` in `bin/setup` and in CI before the tests. To pick another release or the rolling nightly, see [Choosing the browser version](https://navidemad.github.io/capybara-lightpanda/docs/#pinning).
61
61
 
62
62
  ## Credits
63
63
 
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "capybara/lightpanda/cli"
5
+
6
+ exit Capybara::Lightpanda::CLI.run(ARGV)
@@ -30,19 +30,59 @@ module Capybara
30
30
 
31
31
  DEFAULT_CACHE_TIME = 86_400
32
32
 
33
- # One-liner that re-provisions the binary from a process with no
34
- # HTTP-stubbing loaded (VCR/WebMock guard the test process itself).
35
- # Referenced from the stale-fallback warning and BETA_TESTING.md.
36
- PROVISION_HINT =
37
- "bundle exec ruby -r capybara-lightpanda " \
38
- "-e 'Capybara::Lightpanda::Binary.remove; puts Capybara::Lightpanda::Binary.update'"
33
+ # The release downloaded when nothing else is asked for. Each gem version
34
+ # ships with the Lightpanda release it was validated against, so a
35
+ # `bundle update` moves the browser with the driver: the pin's
36
+ # version-scoped filename (see install_path) changes, the old cached file
37
+ # no longer matches, and the new release is fetched. Tracking the rolling
38
+ # nightly by default did the opposite — a floor bump left a cached
39
+ # sub-floor binary in place and the suite died at driver start, while CI
40
+ # ran whatever upstream published that morning.
41
+ #
42
+ # INVARIANT: never below Process::MINIMUM_RELEASE (binary_test pins it),
43
+ # or a fresh install would download a binary the driver then refuses.
44
+ DEFAULT_VERSION = "1.0.4"
45
+
46
+ # required_version value (or LIGHTPANDA_VERSION) that opts back into the
47
+ # rolling `nightly` tag.
48
+ NIGHTLY = "nightly"
49
+
50
+ # Command that provisions the binary from a process with no HTTP stubbing
51
+ # loaded (VCR/WebMock guard the test process itself). An executable
52
+ # rather than a rake task or a `ruby -r` one-liner: the rake tasks only
53
+ # exist under RAILS_ENV=test in a Rails app, and the executable works
54
+ # from bin/setup, a CI step and a dev shell alike. --force re-downloads
55
+ # even when a file is already cached.
56
+ PROVISION_HINT = "bundle exec capybara-lightpanda install --force"
39
57
 
40
58
  class << self
41
- # Set a specific release tag (e.g. "0.3.0") to pin downloads to that
42
- # release. When nil, the rolling "nightly" tag is used. The pin only
43
- # affects download URL construction — the gem's MINIMUM_NIGHTLY_BUILD
44
- # floor is still enforced at process start.
45
- attr_accessor :required_version
59
+ # The Lightpanda version to download: a release tag ("1.0.4",
60
+ # "1.0.5-rc1") or "nightly" for the rolling tag. Unset (nil), it falls
61
+ # back to LIGHTPANDA_VERSION, then to DEFAULT_VERSION. The version only
62
+ # picks the download — the gem's floor is still enforced at process
63
+ # start.
64
+ attr_writer :required_version
65
+
66
+ def required_version
67
+ version = @required_version.to_s
68
+ version = ENV.fetch("LIGHTPANDA_VERSION", "") if version.empty?
69
+ version.empty? ? DEFAULT_VERSION : version
70
+ end
71
+
72
+ def nightly?
73
+ required_version == NIGHTLY
74
+ end
75
+
76
+ # The release tag in effect, nil on the rolling nightly.
77
+ def pinned_version
78
+ nightly? ? nil : required_version
79
+ end
80
+
81
+ # True when the user (or the environment) chose the version, as opposed
82
+ # to inheriting DEFAULT_VERSION.
83
+ def explicit_version?
84
+ !@required_version.to_s.empty? || !ENV.fetch("LIGHTPANDA_VERSION", "").empty?
85
+ end
46
86
 
47
87
  # Seconds before a cached unpinned binary is re-downloaded. Pinned
48
88
  # binaries are never refreshed on age (they're pinned).
@@ -68,66 +108,70 @@ module Capybara
68
108
  yield self
69
109
  end
70
110
 
71
- # Canonical entrypoint: ensure the binary at install_path is current,
72
- # download if needed, return its path. Pinned (required_version set)
73
- # never re-downloads when present. Unpinned re-downloads when older
74
- # than cache_time. When unpinned and the gem cache is empty/stale,
75
- # an already-installed `lightpanda` on PATH (e.g. via Homebrew) wins
76
- # over re-downloading — keeps test suites running under VCR/WebMock
77
- # from triggering surprise HTTP to github.com.
111
+ # Canonical entrypoint: return the path of a usable binary, downloading
112
+ # one if needed.
113
+ #
114
+ # - A release (the default, or an explicit pin) is used as soon as its
115
+ # version-scoped file exists; it is never refreshed on age.
116
+ # - The nightly is re-downloaded once older than cache_time, or at once
117
+ # when the cached build is below the gem's floor (see cache_usable?).
118
+ # - A `lightpanda` on PATH (Homebrew, a package) wins over downloading
119
+ # unless the version was chosen explicitly — a pin is a version
120
+ # contract PATH can't honor. It keeps a suite under VCR/WebMock from
121
+ # firing surprise HTTP at github.com.
78
122
  def update
79
123
  destination = install_path
80
124
 
81
- if required_version
82
- if File.executable?(destination)
83
- log("Pinned #{required_version} present at #{destination}")
84
- return destination
85
- end
86
- return download
87
- end
88
-
89
- if cached_fresh?(destination)
90
- log("Cached binary at #{destination} is fresh (< #{cache_time}s)")
125
+ if cache_usable?
126
+ log("Cached binary at #{destination} is usable")
91
127
  return destination
92
128
  end
93
129
 
94
- if (system_path = system_binary_path)
130
+ if !(pinned_version && explicit_version?) && (system_path = system_binary_path)
95
131
  log("Using lightpanda from PATH at #{system_path}")
96
132
  return system_path
97
133
  end
98
134
 
99
- # Stale-or-absent cache, nothing on PATH: refresh from the network.
100
- # If that fails (GitHub 5xx, DNS/connect timeouts, SocketError) but a
101
- # usable — if stale — binary is already cached, keep using it rather
102
- # than hard-failing. A cold cache (nothing on disk) still surfaces the
103
- # error. The MINIMUM_NIGHTLY_BUILD floor is enforced downstream in
104
- # Process#start, so a sub-floor binary can't slip in.
135
+ # If the download fails (GitHub 5xx, DNS/connect timeouts, an HTTP
136
+ # stub) but a binary is already cached, keep using it rather than
137
+ # hard-failing; with nothing on disk the error surfaces. The floor is
138
+ # enforced downstream in Process#start, so a sub-floor binary can't
139
+ # slip in.
105
140
  #
106
141
  # Deliberately StandardError, not Exception: WebMock's
107
142
  # NetConnectNotAllowedError descends from Exception so it propagates
108
143
  # through app rescue blocks by design — a test suite that blocks net
109
- # connections SHOULD fail loudly here, not silently fall back. CI
110
- # pre-provisions the binary outside that guard instead (real-apps.yml).
144
+ # connections SHOULD fail loudly here, not silently fall back.
145
+ #
146
+ # Kernel.warn, not log: log() is silent unless LIGHTPANDA_DEBUG or an
147
+ # explicit logger is set, and this is exactly the moment the user
148
+ # needs to hear about — a VCR-guarded suite (whose
149
+ # UnhandledHTTPRequestError is a StandardError) lands here, and
150
+ # without the hint all it sees is VCR's error or, later, a floor
151
+ # error with no trace of the blocked download.
111
152
  begin
112
153
  download
113
154
  rescue StandardError => e
114
- raise unless File.executable?(destination)
115
-
116
- # Kernel.warn, not log: log() is silent unless LIGHTPANDA_DEBUG or
117
- # an explicit logger is set, and this fallback is exactly the
118
- # moment the user needs to hear about — a VCR-guarded suite (whose
119
- # UnhandledHTTPRequestError is a StandardError, unlike raw
120
- # WebMock's Exception) lands here silently, keeps a stale binary,
121
- # and later hits a confusing MINIMUM_NIGHTLY_BUILD floor error
122
- # with no trace of the blocked download.
123
- warn("[capybara-lightpanda] Binary download failed (#{e.class}: #{e.message}); " \
124
- "falling back to the cached binary at #{destination}. " \
155
+ cached = File.executable?(destination)
156
+ warn("[capybara-lightpanda] Binary download failed (#{e.class}: #{e.message})" \
157
+ "#{"; falling back to the cached binary at #{destination}" if cached}. " \
125
158
  "If your suite stubs HTTP (VCR/WebMock), pre-provision from an " \
126
159
  "unstubbed process: #{PROVISION_HINT}")
160
+ raise unless cached
161
+
127
162
  destination
128
163
  end
129
164
  end
130
165
 
166
+ # Make sure the binary for the version in effect sits in the gem's own
167
+ # cache, ignoring PATH: what `capybara-lightpanda install` runs from
168
+ # bin/setup or a CI step, where the point is to fill the cache.
169
+ def install(force: false)
170
+ return install_path if !force && cache_usable?
171
+
172
+ download
173
+ end
174
+
131
175
  # Delete the cached binary. Returns the path that was deleted, or nil
132
176
  # if nothing was there.
133
177
  def remove
@@ -175,7 +219,7 @@ module Capybara
175
219
  # and both rename a complete file — last writer wins, both are valid.
176
220
  def download
177
221
  binary_name = platform_binary
178
- tag = required_version || "nightly"
222
+ tag = required_version
179
223
  url = "#{release_url}/#{tag}/#{binary_name}"
180
224
  destination = install_path
181
225
 
@@ -223,10 +267,10 @@ module Capybara
223
267
  def update_hint(binary_path)
224
268
  if brew_managed?(binary_path)
225
269
  "brew update && brew upgrade lightpanda"
226
- elsif binary_path == install_path && required_version
270
+ elsif binary_path == install_path && pinned_version
227
271
  "Capybara::Lightpanda::Binary.required_version is pinned to " \
228
272
  "#{required_version} — raise the pin to a newer release, " \
229
- "or unset it to track the rolling nightly."
273
+ "or set it to \"nightly\" to track the rolling nightly."
230
274
  elsif binary_path == install_path
231
275
  PROVISION_HINT
232
276
  else
@@ -261,7 +305,7 @@ module Capybara
261
305
  # pin self-verifying and lets several pins coexist in one cache dir.
262
306
  def install_path
263
307
  dir = @install_dir || File.dirname(default_binary_path)
264
- basename = required_version ? "lightpanda-#{required_version}" : "lightpanda"
308
+ basename = pinned_version ? "lightpanda-#{pinned_version}" : "lightpanda"
265
309
 
266
310
  File.join(dir, basename)
267
311
  end
@@ -302,6 +346,18 @@ module Capybara
302
346
  nil
303
347
  end
304
348
 
349
+ # A cached release only has to exist: its filename carries the version.
350
+ # A cached nightly must be young enough AND clear the gem's floor — age
351
+ # alone let a build cached yesterday survive a floor bump for up to
352
+ # cache_time, and the driver then refused to start on a binary the gem
353
+ # itself had just called fresh.
354
+ def cache_usable?
355
+ path = install_path
356
+ return File.executable?(path) if pinned_version
357
+
358
+ cached_fresh?(path) && !below_floor?(path)
359
+ end
360
+
305
361
  def cached_fresh?(path)
306
362
  return false unless File.executable?(path)
307
363
  return true if cache_time.zero?
@@ -309,6 +365,25 @@ module Capybara
309
365
  (Time.now - File.mtime(path)) < cache_time
310
366
  end
311
367
 
368
+ # Only a version the floor check positively rejects counts. A file that
369
+ # can't be run or doesn't answer is left to Process#start, which reports
370
+ # it properly. Process is looked up lazily: binary.rb loads before
371
+ # process.rb, and on its own in the provisioning scripts, where the
372
+ # floor is unknown and nothing is rejected.
373
+ def below_floor?(path)
374
+ return false unless Lightpanda.const_defined?(:Process, false)
375
+
376
+ stdout, _, status = Open3.capture3(path, "version")
377
+ return false unless status.success? && !stdout.strip.empty?
378
+
379
+ Lightpanda::Process.check_version!(stdout) { "" }
380
+ false
381
+ rescue BinaryError
382
+ true
383
+ rescue SystemCallError
384
+ false
385
+ end
386
+
312
387
  def normalize_arch(arch)
313
388
  case arch
314
389
  when /x86_64|amd64/i then "x86_64"
@@ -122,8 +122,13 @@ module Capybara
122
122
 
123
123
  # Common navigation lifecycle shared by `wait_for_page_load` (fresh
124
124
  # `Page.navigate`) and `wait_for_navigation` (reload).
125
- # Subscribes to Page.loadEventFired, runs the trigger, waits briefly for
126
- # the event, falls back to readyState polling for the remaining budget.
125
+ # Subscribes to the main frame's load, runs the trigger, waits briefly
126
+ # for it, falls back to readyState polling for the remaining budget.
127
+ # The load is Page.frameStoppedLoading for the main frame, which
128
+ # Lightpanda sends right after Page.loadEventFired: that one carries no
129
+ # frameId and comes for every frame, so an iframe that loaded first
130
+ # made `visit` return while the page's deferred scripts were pending
131
+ # (forem's comment dropdown; visit_readiness_test.rb).
127
132
  # The handler is unsubscribed via `ensure` so a raising trigger doesn't
128
133
  # leak a subscription onto the next navigation. Returns the deadline so
129
134
  # the caller can decide whether to attempt crash recovery.
@@ -131,8 +136,8 @@ module Capybara
131
136
  starting_url = safe_current_url
132
137
  deadline = monotonic_time + @options.timeout
133
138
  loaded = Utils::Event.new
134
- handler = proc { loaded.set }
135
- @client.on("Page.loadEventFired", &handler)
139
+ handler = proc { |params| loaded.set if params["frameId"] == @target_id }
140
+ @client.on("Page.frameStoppedLoading", &handler)
136
141
 
137
142
  begin
138
143
  yield
@@ -142,7 +147,7 @@ module Capybara
142
147
  poll_ready_state(remaining, loaded_event: loaded, starting_url: starting_url) if remaining.positive?
143
148
  end
144
149
  ensure
145
- @client.off("Page.loadEventFired", handler)
150
+ @client.off("Page.frameStoppedLoading", handler)
146
151
  end
147
152
 
148
153
  deadline
@@ -169,7 +174,18 @@ module Capybara
169
174
  # decide whether the session is recoverable.
170
175
  end
171
176
 
172
- POLL_STATE_JS = "(function(){return{r:document.readyState,u:location.href}})()"
177
+ # `d` says whether DOMContentLoaded has fired, read from the navigation
178
+ # timing entry (null when the page has none). Since Lightpanda #4554
179
+ # (11988) readyState is `interactive` from the end of parsing, while
180
+ # deferred and module scripts (Stimulus, Turbo) are still pending;
181
+ # DOMContentLoaded waits for them. Legacy `performance.timing` can't
182
+ # stand in: Lightpanda keeps every field at 0.
183
+ POLL_STATE_JS = <<~JS.delete("\n")
184
+ (function(){
185
+ var p=window.performance,e=p&&p.getEntriesByType?p.getEntriesByType("navigation")[0]:null;
186
+ return{r:document.readyState,u:location.href,d:e?e.domContentLoadedEventStart>0:null}
187
+ })()
188
+ JS
173
189
  private_constant :POLL_STATE_JS
174
190
 
175
191
  def page_ready?(cmd_timeout, starting_url)
@@ -183,10 +199,19 @@ module Capybara
183
199
  return false unless state
184
200
 
185
201
  url_changed = starting_url.nil? || state["u"] != starting_url
186
- url_changed && %w[complete interactive].include?(state["r"])
202
+ url_changed && ready_state_loaded?(state["r"], state["d"])
187
203
  rescue Error
188
204
  false
189
205
  end
206
+
207
+ # `interactive` still counts once DOMContentLoaded fired: a page whose
208
+ # load event never comes (a hanging subresource) is usable then, and
209
+ # must not cost the whole timeout. Without a timing entry, trust it.
210
+ def ready_state_loaded?(ready_state, dom_content_loaded)
211
+ return true if ready_state == "complete"
212
+
213
+ ready_state == "interactive" && dom_content_loaded != false
214
+ end
190
215
  end
191
216
  end
192
217
  end
@@ -91,8 +91,14 @@ module Capybara
91
91
  evaluate_async(script.to_s.strip, *, frame: frame_stack.last)
92
92
  end
93
93
 
94
- # Selenium's raw-CDP escape hatch, as used by
95
- # `page.driver.browser.execute_cdp("Network.setBlockedURLs", urls: [...])`.
94
+ # Selenium's raw-CDP escape hatch,
95
+ # `page.driver.browser.execute_cdp(method, **params)`. The parameters
96
+ # are Lightpanda's, not Chrome's: a suite's
97
+ # `execute_cdp("Network.setBlockedURLs", urls: [...])` gets InvalidParams,
98
+ # because Lightpanda takes only
99
+ # `urlPatterns: [{ urlPattern: "*.png", block: true }]`. That list is
100
+ # also browser-wide and survives `reset!`, so clear it
101
+ # (`urlPatterns: []`) when the test that set it is done.
96
102
  # Scoped to the page session, matching Selenium — that covers the
97
103
  # Page / Runtime / DOM / Network / Emulation domains a suite would
98
104
  # reach for. Browser-scoped commands (Target.*, Browser.*) still go
@@ -319,6 +319,11 @@ module Capybara
319
319
  return if @page_events_enabled
320
320
 
321
321
  page_command("Page.enable")
322
+ # Page.domContentEventFired and Page.loadEventFired carry no frameId
323
+ # and Lightpanda sends them for every frame: an iframe's load reads
324
+ # as the page's. Page.lifecycleEvent names its frame, so readiness
325
+ # waits use it instead (see #subscribe_to_document_ready).
326
+ page_command("Page.setLifecycleEventsEnabled", enabled: true)
322
327
  @page_events_enabled = true
323
328
  end
324
329
 
@@ -684,9 +689,17 @@ module Capybara
684
689
  end
685
690
 
686
691
  # The new document's context exists before its deferred and module
687
- # scripts have run: this event marks the end of that phase, at
688
- # Page.domContentEventFired or anything later that proves it is over
689
- # (load, the frame stopping, the document request failing).
692
+ # scripts have run: this event marks the end of that phase, at the main
693
+ # frame's DOMContentLoaded or anything later that proves it is over
694
+ # (load, the frame stopping, the document request failing). Only the
695
+ # main frame counts: Page.domContentEventFired/loadEventFired carry no
696
+ # frameId and Lightpanda also sends them for iframes, so an iframe that
697
+ # finished first ended this wait while the page's deferred scripts were
698
+ # still pending (visit_readiness_test.rb). Page.lifecycleEvent names its
699
+ # frame; enable_page_events turns it on.
700
+ MAIN_FRAME_READY_EVENTS = %w[DOMContentLoaded load].freeze
701
+ private_constant :MAIN_FRAME_READY_EVENTS
702
+
690
703
  def subscribe_to_document_ready
691
704
  @document_ready_event = Utils::Event.new
692
705
  @document_ready_event.set
@@ -694,8 +707,11 @@ module Capybara
694
707
  on("Page.frameStartedNavigating") do |params|
695
708
  @document_ready_event.reset if main_frame_navigation_start?(params)
696
709
  end
697
- on("Page.domContentEventFired") { @document_ready_event.set }
698
- on("Page.loadEventFired") { @document_ready_event.set }
710
+ on("Page.lifecycleEvent") do |params|
711
+ next unless params["frameId"] == @target_id
712
+
713
+ @document_ready_event.set if MAIN_FRAME_READY_EVENTS.include?(params["name"])
714
+ end
699
715
  on("Page.frameStoppedLoading") do |params|
700
716
  @document_ready_event.set if params["frameId"] == @target_id
701
717
  end
@@ -0,0 +1,95 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "optparse"
4
+ require_relative "errors"
5
+ require_relative "binary"
6
+ require_relative "process"
7
+
8
+ module Capybara
9
+ module Lightpanda
10
+ # `capybara-lightpanda` executable: provisions the browser binary from a
11
+ # process of its own. The driver otherwise downloads it lazily, inside the
12
+ # test process, where VCR/WebMock block the request — so a setup script or
13
+ # a CI step calls this first and the suite finds the binary already there.
14
+ #
15
+ # Loads only the binary/process files, not the driver: no Capybara, no
16
+ # Rails, and nothing that stubs HTTP.
17
+ class CLI
18
+ USAGE = <<~TEXT
19
+ Usage: capybara-lightpanda COMMAND [options]
20
+
21
+ Commands:
22
+ install [VERSION] Download the Lightpanda binary into the gem's cache
23
+ (VERSION: a release tag or "nightly"; default: the
24
+ release this gem version was validated against)
25
+ version Print the version of the cached binary
26
+ path Print where the binary is (or would be) cached
27
+ remove Delete the cached binary
28
+
29
+ Options:
30
+ TEXT
31
+
32
+ def self.run(argv, out: $stdout, err: $stderr)
33
+ new(out, err).run(argv.dup)
34
+ end
35
+
36
+ def initialize(out, err)
37
+ @out = out
38
+ @err = err
39
+ @force = false
40
+ end
41
+
42
+ # Returns the process exit status.
43
+ def run(argv)
44
+ parser.parse!(argv)
45
+ command, version = argv
46
+ Binary.required_version = version if version
47
+
48
+ case command
49
+ when "install" then install
50
+ when "version" then version_command
51
+ when "path" then @out.puts(Binary.install_path)
52
+ when "remove" then remove
53
+ else
54
+ @err.puts(parser.help)
55
+ return command.nil? ? 0 : 1
56
+ end
57
+ 0
58
+ rescue OptionParser::ParseError, LoadError, Error => e
59
+ @err.puts("capybara-lightpanda: #{e.message}")
60
+ 1
61
+ end
62
+
63
+ private
64
+
65
+ def parser
66
+ @parser ||= OptionParser.new(USAGE) do |opts|
67
+ opts.on("-f", "--force", "install: download even if a binary is already cached") { @force = true }
68
+ # A project that configures Binary (install_dir, required_version,
69
+ # a proxy) in a support file points at it here, so the command and
70
+ # the suite agree on what to download and where.
71
+ opts.on("-r", "--require FILE", "Load FILE first (your Binary.configure block)") do |file|
72
+ require File.expand_path(file)
73
+ end
74
+ end
75
+ end
76
+
77
+ def install
78
+ path = Binary.install(force: @force)
79
+ @out.puts("Lightpanda #{Binary.current_version || Binary.required_version} ready at #{path}")
80
+ end
81
+
82
+ def version_command
83
+ version = Binary.current_version
84
+ raise BinaryNotFoundError, "no cached Lightpanda binary at #{Binary.install_path}" unless version
85
+
86
+ @out.puts(version)
87
+ end
88
+
89
+ def remove
90
+ removed = Binary.remove
91
+ @out.puts(removed ? "Removed #{removed}" : "Nothing to remove at #{Binary.install_path}")
92
+ end
93
+ end
94
+ end
95
+ end
@@ -192,6 +192,8 @@ function visibleText(el) {
192
192
  // indexed loops: an overridden map must never detach cache rows from node IDs.
193
193
  var hintStringify = JSON.stringify;
194
194
  var hintLowerCase = Function.prototype.call.bind(String.prototype.toLowerCase);
195
+ // Candidates kept when none holds the searched text (see findHints).
196
+ var HINT_FAILURE_CANDIDATES = 10;
195
197
 
196
198
  // Capybara keeps Result candidates for lazy enumeration, possibly after the DOM
197
199
  // changes. Only immutable tag names belong in initial_cache; mutable visibility,
@@ -236,6 +238,21 @@ function findHints(nodes, spec) {
236
238
  kept[kept.length] = el;
237
239
  }
238
240
  }
241
+ // No candidate holds the text: hand Capybara the first few anyway. It
242
+ // builds its failure message from the candidates it filtered out itself,
243
+ // so an empty array drops "visible"/"with text" and the "Also found" list.
244
+ // Capybara still rejects each one on its own text check, so results don't
245
+ // change. The cap bounds what a passing negative assertion pays: each kept
246
+ // candidate costs a visibility and a text read.
247
+ if (needles.length && kept.length === 0) {
248
+ var shown = nodes.length < HINT_FAILURE_CANDIDATES ? nodes.length : HINT_FAILURE_CANDIDATES;
249
+ for (var m = 0; m < shown; m++) {
250
+ var node = nodes[m];
251
+ hints[m] = { tag_name: node.nodeType === 11 ? 'ShadowRoot' :
252
+ (node.tagName ? hintLowerCase(node.tagName) : '') };
253
+ kept[m] = node;
254
+ }
255
+ }
239
256
  // Publish only after every read succeeds. Any exception returns the exact
240
257
  // original array, without partial filtering or partially constructed hints.
241
258
  kept.__lightpandaHints = hintStringify(hints);
@@ -1019,6 +1019,13 @@ module Capybara
1019
1019
  # A non-focusable target (focus() is a no-op on those since upstream
1020
1020
  # #3592, build 9646) must not leave the previous field focused, or its
1021
1021
  # keys land there: blur it so they go to the body, as in Chrome.
1022
+ #
1023
+ # An editing host gets the same treatment: Lightpanda's focus() collapses
1024
+ # the caret at the host's first position (upstream #4538), so a draft
1025
+ # already in the editor took the keys in front of it. The caret goes
1026
+ # after the last non-blank text, inside its <p>, the position Chrome
1027
+ # normalizes WebDriver's collapsed end-of-contents range to; a host with
1028
+ # no text gets the end of its children.
1022
1029
  SEND_KEYS_FOCUS_JS = <<~JS
1023
1030
  function() {
1024
1031
  var doc = this.ownerDocument;
@@ -1035,6 +1042,16 @@ module Capybara
1035
1042
  var end = String(this.value || '').length;
1036
1043
  this.setSelectionRange(end, end);
1037
1044
  } catch (e) {}
1045
+ } else if (this.isContentEditable) {
1046
+ var sel = doc.defaultView && doc.defaultView.getSelection();
1047
+ if (!sel) return;
1048
+ var last = null;
1049
+ var walker = doc.createTreeWalker(this, 4 /* NodeFilter.SHOW_TEXT */);
1050
+ while (walker.nextNode()) {
1051
+ if (/\\S/.test(walker.currentNode.data)) last = walker.currentNode;
1052
+ }
1053
+ if (last) sel.collapse(last, last.data.length);
1054
+ else sel.collapse(this, this.childNodes.length);
1038
1055
  }
1039
1056
  }
1040
1057
  JS
@@ -314,7 +314,20 @@ module Capybara
314
314
  # (11012), ShadowRoot hit testing #4184 (11071), same-document
315
315
  # navigateToHistoryEntry #3903 (11113), native isContentEditable #4210
316
316
  # (11229), contenteditable Backspace/Delete/Ctrl+A #4415 (11610).
317
- MINIMUM_NIGHTLY_BUILD = Gem::Version.new("11647")
317
+ #
318
+ # 2026-11-16 bump 11647 -> 12015 (= release 1.0.4, the new lockstep cap;
319
+ # inert-aware hit testing #4548 at 12019 and xhr.upload events #4529 at
320
+ # 12116 stay above it). The reason: 1.0.3's x86_64-macos binary has no
321
+ # CPU baseline and dies with SIGILL on the first HTTPS request on CPUs
322
+ # without ADX (#4433); the baseline #4450 (11672) first ships in 1.0.4.
323
+ # Rides along: bad-port block #4430 (11651), CORS exposed headers #4242
324
+ # (11663), postMessage targetOrigin #4382 (11676), cross-site SameSite
325
+ # cookies #4442 (11688), multi-target CDP #3945 (11844), apple_m1 CPU pin
326
+ # #4533 (11915), readyState `interactive` before deferred scripts #4554
327
+ # (11988), CSS animation events opt-in #4559 (11991). No version gate
328
+ # sat between the two floors, so nothing is retired. Validated on the
329
+ # 1.0.4 aarch64-macos binary: test:all and spec:shared:parallel green.
330
+ MINIMUM_NIGHTLY_BUILD = Gem::Version.new("12015")
318
331
 
319
332
  # Lines of browser output #output keeps (ferrum keeps the same 100).
320
333
  OUTPUT_LINES = 100
@@ -326,16 +339,18 @@ module Capybara
326
339
  # bare "0.3.6" carrying no commit counter at all, and MINIMUM_NIGHTLY_BUILD
327
340
  # has nothing to compare against. Releases are cut from the same trunk, so
328
341
  # a release is acceptable exactly when its own commit count clears the
329
- # nightly floor. 1.0.3 (2026-11-05) is build 11647 — exactly the nightly
342
+ # nightly floor. 1.0.4 (2026-11-13) is build 12015 — exactly the nightly
330
343
  # floor, which is no accident: the floor was raised *to* the release so
331
- # both channels gate the same commit. (1.0.2 = 10965 predates fixes the
332
- # floor exists for.)
344
+ # both channels gate the same commit. (1.0.3 = 11647 predates the
345
+ # x86_64-macos CPU baseline the floor exists for.)
333
346
  #
334
347
  # INVARIANT: every MINIMUM_NIGHTLY_BUILD bump must also move this to the
335
348
  # first release containing that build (`git rev-list --count <tag>` in the
336
349
  # browser repo tells you). Leaving it behind would let the release channel
337
- # silently accept a binary the nightly channel rejects.
338
- MINIMUM_RELEASE = Gem::Version.new("1.0.3")
350
+ # silently accept a binary the nightly channel rejects. Move
351
+ # Binary::DEFAULT_VERSION with it: that is the release a fresh install
352
+ # downloads, and it must clear this floor.
353
+ MINIMUM_RELEASE = Gem::Version.new("1.0.4")
339
354
 
340
355
  # A release-candidate binary: "<x.y.z>-rc<N>.<git rev-list --count>+<hash>".
341
356
  # Captures the commit counter.
@@ -15,7 +15,7 @@ namespace :lightpanda do
15
15
  end
16
16
  end
17
17
 
18
- desc "Download the Lightpanda binary (optionally pinned: rake lightpanda:binary:update[0.3.0])"
18
+ desc "Download the Lightpanda binary (a release tag or nightly: rake lightpanda:binary:update[1.0.4])"
19
19
  task :update, [:version] do |_, args|
20
20
  Capybara::Lightpanda::Binary.required_version = args[:version] if args[:version]
21
21
  path = Capybara::Lightpanda::Binary.update
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Capybara
4
4
  module Lightpanda
5
- VERSION = "0.17.1"
5
+ VERSION = "0.19.0"
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,11 +1,11 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: capybara-lightpanda
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.17.1
4
+ version: 0.19.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Navid Emad
8
- bindir: bin
8
+ bindir: exe
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
@@ -62,7 +62,8 @@ description: A Capybara driver for Lightpanda, the fast headless browser built i
62
62
  and cookie management — ready for real-world Rails test suites.
63
63
  email:
64
64
  - design.navid@gmail.com
65
- executables: []
65
+ executables:
66
+ - capybara-lightpanda
66
67
  extensions: []
67
68
  extra_rdoc_files: []
68
69
  files:
@@ -70,6 +71,7 @@ files:
70
71
  - LICENSE.txt
71
72
  - NOTICE.md
72
73
  - README.md
74
+ - exe/capybara-lightpanda
73
75
  - lib/capybara-lightpanda.rb
74
76
  - lib/capybara/lightpanda/auto_scripts.rb
75
77
  - lib/capybara/lightpanda/binary.rb
@@ -80,6 +82,7 @@ files:
80
82
  - lib/capybara/lightpanda/browser/navigation.rb
81
83
  - lib/capybara/lightpanda/browser/runtime.rb
82
84
  - lib/capybara/lightpanda/browser/selenium_compat.rb
85
+ - lib/capybara/lightpanda/cli.rb
83
86
  - lib/capybara/lightpanda/client.rb
84
87
  - lib/capybara/lightpanda/client/subscriber.rb
85
88
  - lib/capybara/lightpanda/client/web_socket.rb