Class: Capybara::Simulated::Browser
- Inherits:
-
Object
- Object
- Capybara::Simulated::Browser
- Includes:
- RecordedActions
- Defined in:
- lib/capybara/simulated/browser.rb
Defined Under Namespace
Modules: RecordedActions
Constant Summary collapse
- POLLING_GRACE_POLLS =
Sticky window after timers finish: keep polling? true so a setTimeout firing mid-loop doesn’t drop Capybara’s synchronize before its own default_max_wait_time kicks in. Counted in poll calls (not wall time) for determinism under GC/load pressure. 1000 polls × Capybara’s default 0.01 s retry_interval ≈ 10 s.
1000- IDLE_SETTLE_POLLS =
When ‘@timers_active` is true but `@runtime.settle_gen` hasn’t bumped in this many consecutive polls, treat the page as observably idle and let Capybara’s per-find timer give up. See ‘polling?` for the full rationale. 300 polls ≈ 3 s at Capybara’s default 10 ms retry interval — long enough to ride through brief async idle windows during Discourse’s ProseMirror editor boot (which sometimes pauses ~1 s mid-load while a webpack chunk + Glimmer reconcile complete) while still cutting the full 4 s wait on tests destined to fail.
300- POST_NAV_POLL_GRACE_POLLS =
Brief window after a Ruby-side navigate (context rebuild) so Capybara’s outer synchronize gets one retry against the new context.
10- POLL_TICK_STEP_MS =
Deterministic virtual-clock model (replaces the old wall-sync, where each tick advanced by REAL wall-elapsed and so coupled virtual time to JS/Ruby/GC speed — a faster ‘visible_text` shifted WHEN debounces fired, e.g. Avo actions_spec:464). Now each poll advances by a FIXED step; near-future timers on an otherwise-idle page are fast-forwarded to (horizon-gated).
100 ms is empirically the floor that lets a “commit debounce scheduled between two user actions” fire before the next action (Avo actions_spec:464’s ~50-75 ms field-commit flips at step 10/50, fixed at >=75). Group-A transient-catch observability does NOT depend on this step — it comes from the ‘timer_wait_elapsed?` FREQUENCY gate (the first find after an action doesn’t tick, so the pre-debounce state is observed regardless of step size), so a larger step completes Group-B without losing Group-A (verified green at 100 across gem 1579, WPT 660, Forem, Avo, :464 passing). Clamped >=1 so a ‘CSIM_POLL_TICK_STEP_MS=0` misconfig can’t freeze the fixed-step path.
[(ENV['CSIM_POLL_TICK_STEP_MS'] || '100').to_i, 1].max
- FF_HORIZON_MS =
Horizon-gated fast-forward: when the page is observably idle (no timer due now, no background IO) but a timer is parked within this horizon, jump the virtual clock straight to it instead of waiting ~delay/step polls. A timer farther out (ahoy 1000 ms, session-timeout, analytics) is LEFT parked. 600 clears every legit must-fire wait (Backburner/DTextField 500, refetch/chart <=200, image-grid 64) while staying BELOW ahoy’s 1000. ‘=0` disables FF →pure deterministic fixed-step (the fallback model).
(ENV['CSIM_FF_HORIZON_MS'] || '600').to_i
- FF_TRANSIENT_GUARD_POLLS =
Transient guard: hold the page pre-debounce for this many consecutive idle polls before allowing a fast-forward, so “catch the DOM before the 200 ms debounce fires” tests (Discourse refetchForSearch / doubled-filter, Avo filters) still observe the intermediate state across several polls.
(ENV['CSIM_FF_TRANSIENT_GUARD_POLLS'] || '6').to_i
- SETTLE_DRAIN_MS =
32- SETTLE_MAX_ITER =
10- SETTLE_MAX_ITER_TASKS =
Per-‘run_loop_step` task cap (its `maxIter`). Bounds a self-rescheduling timer/microtask storm so one settle iter returns to Ruby; large enough for the heaviest legit chain (Mastodon hydrate, Turbo stream batch).
256- USER_ACTION_DRAIN_MS =
Post-user-action virtual-clock advance. Default 0 — the wall-sync model (each tick_real_time advances by the wall ms elapsed since the last tick) lets Capybara’s outer poll loop drive the clock at the same rate a real browser sees, so debounced chains complete naturally during polling without being pre-emptively flushed past the transient window real-browser tests rely on.
‘CSIM_USER_ACTION_DRAIN_MS=600` restores the pre-wall-sync burst behaviour: post-action, drain everything due in the next 600 ms of virtual time before returning. Costs the transient- state observability the wall-sync model preserves; recovers the ~5-10 % wall on action-heavy suites where Capybara would otherwise poll N times to catch a single debounce.
(ENV['CSIM_USER_ACTION_DRAIN_MS'] || '0').to_i
- USER_AGENT =
Sent on every driver-originated Rack call. ‘HTTP_USER_AGENT` must lead with `Mozilla/5.0` so server-side bot detectors (ahoy_matey’s ‘Browser.new(ua).bot?`) treat us as a real client. `REMOTE_ADDR` has to be a non-empty, parseable IP —Devise’s ‘trackable` mixin runs `IPAddr.new(request.remote_ip)` during `set_user`/sign-in, and an empty string trips `IPAddr::AddressFamilyError`. Keep `USER_AGENT` in sync with `navigator.userAgent` in `lib/capybara/simulated/js/bridge.js` — the JS side ships in the V8 snapshot, so injecting from Ruby at boot would defeat snapshot warmth. Discourse’s ‘non_crawler_user_agents` adds a “Rails Testing” bypass in test mode (see lib/crawler_detection.rb); without one of its bypass tokens here Discourse serves a no-JS crawler-only HTML view. Putting “Rails Testing” in the UA satisfies that without claiming a specific real-browser engine (which would send Turbo / Stimulus down chrome-specific code paths Avo’s tests don’t exercise).
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 capybara-simulated'- REMOTE_ADDR_IPV4 =
Approximate Chrome’s resolution: when connecting to ‘localhost`, Linux glibc returns IPv6 (::1) first and the server sees the client at `::1`; for any literal IP (or a non-localhost name), the server keeps IPv4. Match that so Discourse system specs (`expect(event).to eq(’::1’)‘) line up with what they would see under selenium.
'127.0.0.1'- REMOTE_ADDR_IPV6 =
'::1'- RECENT_URLS_STALE_AGE_MS =
Queued URLs older than this (real wall clock) are treated as stale and dropped on the next ‘current_url` read. Capybara’s default polling interval is 50 ms, so a ‘have_current_path` walk runs through its iterations well under this threshold; a `page.current_url` read between unrelated user actions arrives long after the prior action’s settle pushed intermediates, falls past the cutoff, and surfaces the current URL directly.
250- FIND_PRE_TICK_MIN_S =
Minimum wall-clock gap before find() re-ticks. The smoke contract is “first find returns the current DOM without firing pending timers” — apps assert ‘have_selector` on a `<div>` whose constructor schedules a `setTimeout(0)` to remove it, expecting to catch the div before removal. Keep this above one Ruby boundary so a single visit+find pair doesn’t accidentally tick.
0.05- MODIFIER_KEYS =
{ shift: 'shiftKey', control: 'ctrlKey', ctrl: 'ctrlKey', alt: 'altKey', option: 'altKey', meta: 'metaKey', command: 'metaKey' }.freeze
- MODIFIER_KEY_NAMES =
MODIFIER_KEYS.keys.to_set.freeze
- CONSOLE_STDERR =
Resolved once — log_console fires for every page console.* line (CLAUDE.md rule 3: no per-call ENV reads on hot paths).
ENV['CSIM_CONSOLE_STDERR'] == '1'
- ANNOTATABLE_SEVERITIES =
info/debug/log lines almost never carry stack traces — keep them out of the regex pass so per-call cost stays at the severity gate.
%w[error warning warn].freeze
- ASSET_SRC_MAX =
4096- HIJACK_PIPE_MAX_WAIT_S =
MessageBus’s ‘long_polling_interval` defaults to 25 s — its `cleanup_timer` fires after that interval, closing the hijacked connection with an empty `[]` write. Pick a slightly larger wall cap so the close reaches us before our pipe read gives up. Other hijack-using middleware likely behaves similarly; if any need much longer waits, this becomes a per- request option.
30- MAX_FETCH_REDIRECTS =
20- TEXT_CONTENT_TYPE_PREFIXES =
Content types whose bytes are already representable in the UTF-8 string that ships back to JS — base64 wouldn’t add anything and ‘Base64.strict_encode64` is ~1 % of suite wall time on Discourse. Binary types (images, octet-stream, gzipped traineddata, etc.) still need `body_b64` because V8 / QuickJS mangle bytes 0x80-0xFF over the UTF-8 string boundary. `fetch.js#_decodeBytes` and `xhr.js` both fall back to the text body when `body_b64` is absent.
%w[text/ application/json application/javascript application/ecmascript application/xml image/svg+xml].freeze
- @@asset_cache =
Process-wide HTTP/1.1 response cache for ‘rack_fetch`. Real browsers (cuprite / selenium) reuse fetched assets across the suite — without this, Simulated re-fetches every <script src> on every visit (Redmine baseline: ~6× more requests than selenium). Honors `Cache-Control` / `Expires` / `ETag` / `Last-Modified` per RFC 9111.
AssetCache.new
- @@asset_src =
Cross-visit cache of external asset bodies (classic ‘<script src>` bundles AND linked `<link rel=stylesheet>` CSS), url → [body, fresh_until]. A fresh VM per visit (`reset_page` → `clear_volatile`) would otherwise re-fetch the same fingerprinted app assets (avo.base.js, avo.base.css, …) on every visit — a real browser HTTP-caches them once. Safety: only responses the server marks durably cacheable (`fresh_until` from max-age) are stored, and these are content-stable assets at content-hashed URLs (a change yields a new URL = cache miss), so a stale body can’t shadow a later test. Survives ‘clear_volatile` (that is the point); size-capped.
{}
- @@asset_src_lock =
Mutex.new
Instance Attribute Summary collapse
-
#context_gen ⇒ Object
readonly
Returns the value of attribute context_gen.
-
#default_user_agent ⇒ Object
Capybara’s ‘current_window.resize_to(w, h)` lands here; the ahoy hamburger test (mobile breakpoint at 425×694) and any responsive-utility-aware test (Tailwind `m:` show / hide, bootstrap `.d-md-flex`, …) depends on this surfacing through the JS-side `innerWidth` / `innerHeight` so the cascade’s ‘mediaMatches` and `matchMedia()` evaluate against the test’s chosen viewport instead of the 1024×768 default.
-
#default_viewport ⇒ Object
Capybara’s ‘current_window.resize_to(w, h)` lands here; the ahoy hamburger test (mobile breakpoint at 425×694) and any responsive-utility-aware test (Tailwind `m:` show / hide, bootstrap `.d-md-flex`, …) depends on this surfacing through the JS-side `innerWidth` / `innerHeight` so the cascade’s ‘mediaMatches` and `matchMedia()` evaluate against the test’s chosen viewport instead of the 1024×768 default.
-
#pending_trace ⇒ Object
readonly
Returns the value of attribute pending_trace.
-
#timers_active ⇒ Object
writeonly
Sets the attribute timers_active.
-
#trace ⇒ Object
readonly
Returns the value of attribute trace.
-
#trace_mode ⇒ Object
readonly
Returns the value of attribute trace_mode.
Class Method Summary collapse
-
.default_host ⇒ Object
Fallback origin for ‘visit(’/foo’)‘ and friends when no current page is loaded yet.
- .remote_addr_for(host) ⇒ Object
Instance Method Summary collapse
- #active_element_handle ⇒ Object
- #advance_virtual_clock_ms(ms) ⇒ Object
-
#all_text(handle) ⇒ Object
Capybara::Driver::Node surface — Node calls ‘check_stale` before each read, and that advances the virtual clock.
- #annotate_console_message(severity, message) ⇒ Object
- #append_multipart_part(body, boundary, name, content, filename: nil, content_type: nil) ⇒ Object
-
#apply_request_headers(env, headers) ⇒ Object
CGI convention: ‘Content-Type` and `Content-Length` land in env without the HTTP_ prefix.
-
#async_io_pending? ⇒ Boolean
Cheap O(1) gate: is there any non-timer async channel with traffic that ‘tick_real_time` would drain? `tick_real_time` itself runs exactly when `worker_pending? || event_source_pending? || hijack_fetch_pending?` (plus `@timers_active`), and each of those predicates is a single `.empty?` / counter check.
- #attr(handle, name) ⇒ Object
- #blob_register(url, body_b64) ⇒ Object
- #blob_resolve(url) ⇒ Object
- #blob_unregister(url) ⇒ Object
- #build_multipart_body(fields, file_inputs) ⇒ Object
- #build_runtime(engine) ⇒ Object
-
#cached_find(kind, arg, ctx) ⇒ Object
Single-slot cache for the most recent find_xpath / find_css / find_first_css result.
- #check_stale(handle, initial, gen = nil) ⇒ Object
- #clear_trace! ⇒ Object
- #click(handle, keys = [], **opts) ⇒ Object
-
#click_event_init(handle, keys, opts) ⇒ Object
Resolve click offset against the element’s CSS-declared box.
- #coerce_set_value(v) ⇒ Object
- #computed_style(handle, names) ⇒ Object
-
#consume_pending_download ⇒ Object
‘<a download>` clicked synthetically (file-saver’s saveAs ships a freshly-created anchor through ‘dispatchEvent(MouseEvent ’click’)‘).
-
#consume_pending_form_submit ⇒ Object
Read the form-submit pending intent set by JS-side ‘form.submit()` / `form.requestSubmit()`.
- #consume_pending_history_traverse ⇒ Object
- #consume_pending_location ⇒ Object
-
#consume_pending_navigation ⇒ Object
Read the anchor-navigation pending intent set by JS-side ‘el.click()` (Element.prototype.click) on an `<a href>`.
- #consume_pending_reload ⇒ Object
- #current_path ⇒ Object
- #current_referer ⇒ Object
- #current_url ⇒ Object
-
#decode_image(b64_bytes, max_w = nil, max_h = nil) ⇒ Object
── Image decode (libvips) ─────────────────────────────────────.
-
#decode_response_bom(s) ⇒ Object
Strip + decode a single leading byte-order mark, mapping the body to a UTF-8 Ruby string.
-
#decode_video_frame(b64_bytes) ⇒ Object
── Video decode (ffprobe + ffmpeg) ────────────────────────────.
-
#deliver_event_source_events ⇒ Object
Drain any queued events into the VM.
- #deliver_hijacked_fetches ⇒ Object
- #deliver_worker_messages ⇒ Object
-
#describe_node_handle(handle) ⇒ Object
‘tag#id.class` short description of the handle, for trace `description` fields.
- #disabled?(handle) ⇒ Boolean
- #dispatch_event(handle, type, init = {}) ⇒ Object
-
#document_cookie ⇒ Object
‘document.cookie` is TEXT; jar entries parsed out of Rack’s Set-Cookie headers can carry the BINARY tag, which would make the joined string cross into JS as a Uint8Array (‘document.cookie.match is not a function`).
- #double_click(handle, keys = [], **opts) ⇒ Object
- #download_link(url, filename_hint = '') ⇒ Object
-
#drag_to(source_handle, target_handle, **_opts) ⇒ Object
Element-to-element drag.
-
#drain_after_user_action ⇒ Object
Every user-action entry point (set / send_keys / select / unselect) ends in this trio: drain any pending form submit, drain any pending Element.click anchor activation, then settle the page.
- #drain_pending_navigation ⇒ Object
-
#drop(handle, args) ⇒ Object
HTML5 drag-and-drop simulation.
- #drop_items(arg) ⇒ Object
-
#durable_source(url) ⇒ Object
Fetch a source body and report how long it stays safely reusable per its OWN response headers — an absolute freshness deadline (Time), or nil when the response is not durably cacheable (no-store / no-cache / max-age=0 / dynamic with no freshness).
- #empty_find_result?(result) ⇒ Boolean
- #encode_image(pixels_ref, width, height, mime_type = 'image/png', quality = 90) ⇒ Object
-
#ensure_alive_after_tick(handle) ⇒ Object
‘tick_real_time` may have rebuilt the DOM (Ember route hydration finishing on its first idle tick replaces server-rendered nodes with fresh ones).
-
#eval_esm_module(url, src = nil) ⇒ Object
Native ESM entry point.
- #evaluate_async_script(code, args = []) ⇒ Object
- #evaluate_script(code, args = []) ⇒ Object
- #event_source_close(id) ⇒ Object
-
#event_source_open(url) ⇒ Object
── EventSource (SSE) ──────────────────────────────────────────.
- #event_source_pending? ⇒ Boolean
- #event_source_poll ⇒ Object
-
#execute_script(code, args = []) ⇒ Object
Fire-and-forget variant: runs the script but never returns its value to Ruby.
-
#external_asset_source(url) ⇒ Object
Body of an external durably-cacheable asset (classic script or stylesheet), served from the cross-visit cache when still fresh, else fetched (which read-throughs the per-visit asset cache) and cached iff durably cacheable.
- #file_input?(handle) ⇒ Boolean
- #file_picks_for(handle) ⇒ Object
- #find_css(css, context_handle = nil) ⇒ Object
- #find_first_css(css, context_handle = nil) ⇒ Object
- #find_with_timer_fallback(kind, arg, ctx) ⇒ Object
-
#find_xpath(xpath, context_handle = nil) ⇒ Object
XPath is evaluated inside V8 against the live JS DOM via the xpathway engine (bundled, installed at snapshot build).
-
#finish_trace_to(path, trace = (@trace || @pending_trace)) ⇒ Object
Persist ‘trace` (defaults to live or pending) to `path` and return the path.
- #format_temporal_value(v, handle) ⇒ Object
-
#geolocation_state_json ⇒ Object
Backs the ‘__csimGeolocationState` host fn.
-
#go_back ⇒ Object
Capybara-initiated ‘page.go_back` runs from Ruby, not inside a JS call, so it’s safe to rebuild the Context synchronously.
- #go_forward ⇒ Object
-
#handle_modal(type, message, default_value) ⇒ Object
JS-side ‘alert(…)` / `confirm(…)` / `prompt(…)` route here.
- #hijack_fetch_pending? ⇒ Boolean
-
#history_go(delta, force: false) ⇒ Object
Move through the history stack by ‘delta`.
-
#history_length ⇒ Object
Total history entries (after forward-tail truncation), surfaced to JS ‘history.length` via the `__historyLength` host fn.
-
#history_push(url, state = nil) ⇒ Object
‘history.pushState(state, _, url)` from SPA navigation (Turbo Visit, InstantClick, …) appends a new browser-history entry.
-
#history_state(url, state = nil) ⇒ Object
‘history.pushState(state, ”, ’/path’)‘ ships the URL through `__setCurrentUrl` and lands here.
-
#horizon_fast_forward_step ⇒ Object
This tick’s deterministic virtual-clock advance (ms).
- #hover(handle) ⇒ Object
- #html ⇒ Object
-
#initialize(app, driver: nil, js_engine: nil, cookies: nil, local_storage: nil) ⇒ Browser
constructor
A new instance of Browser.
- #inner_html(handle) ⇒ Object
-
#invalidate_find_cache ⇒ Object
Any operation that may have mutated the DOM (click, set, send_keys, navigate, hover, …) must call this so the next find falls through to a fresh V8 query.
-
#location_assign(url) ⇒ Object
Defer the navigation: doing it from inside the running V8 call would dispose the Context mid-call.
-
#location_reload ⇒ Object
Mirror of ‘location_assign`’s deferral for ‘location.reload()`: the JS call lands here from `__locationReload`; running `browser.refresh` directly would `navigate` (rebuilding the Context) while we’re still inside the V8 call, which V8 terminates with a ‘ScriptTerminatedError`.
- #log_console(severity, message) ⇒ Object
- #log_network(method, url, status) ⇒ Object
- #lookup_node(handle) ⇒ Object
-
#mark_action_baseline ⇒ Object
Pin the URL the page is at as a user action BEGINS — the FIRST line of every action entry (click / double_click / right_click / hover / set / send_keys / select / unselect).
-
#marshal_args(args) ⇒ Object
Capybara passes Node instances directly as script args (‘session.evaluate_script(’arguments.click()‘, some_node)`).
- #mime_type_for_path(path) ⇒ Object
- #modifier_flags(keys) ⇒ Object
- #navigate_post(url, body, content_type, depth: 0, from_history: false) ⇒ Object
- #node_path(handle) ⇒ Object
-
#option_selected?(h) ⇒ Boolean
HTML spec: ‘<option>.selected` IDL is true when the `selected` attribute is set OR when no sibling option has `selected` and this is the first non-disabled option of a single-select `<select>` (implicit default).
- #outer_html(handle) ⇒ Object
- #parse_trace_mode(raw) ⇒ Object
-
#polling? ⇒ Boolean
Capybara polls find / has_? via ‘synchronize` while `Driver#wait?` is true.
- #pure_fragment_navigation?(url) ⇒ Boolean
- #push_user_agent_to_js ⇒ Object
-
#rack_fetch(method, url, body, headers, redirect_mode, env_extras: nil) ⇒ Object
URLs we won’t even try to route through Rack: anything that isn’t http(s) (data: / mailto: / about:) plus pseudo-tokens like V8’s ‘<snapshot>` that sourcemap libraries pull out of error stacks and feed straight to `fetch()` / `xhr.open()`.
-
#rack_fetch_async(method, url, body, headers_json) ⇒ Object
── Hijack-aware async XHR ─────────────────────────────────────.
- #rack_fetch_async_abort(id) ⇒ Object
-
#rack_fetch_body(url) ⇒ Object
── Host-fn callbacks invoked by bridge.js ──────────────────.
-
#read_file_pick(handle, index, start = nil, finish = nil) ⇒ Object
JS-side ‘__HostBackedFile.text()` / `arrayBuffer()` route through this to read attached file bytes on demand — ActiveStorage’s ‘DirectUpload` MD5-chunks the file via FileReader before POSTing to `/rails/active_storage/direct_uploads`.
-
#read_rack_body(body) ⇒ Object
Rack response bodies must respond to ‘each` (or be an Array of strings).
-
#record_action(kind, description) ⇒ Object
Wraps a driver action so the trace records description, urls, console / network activity, and (on action error / full mode) a post-action DOM snapshot.
- #record_history(entry) ⇒ Object
- #record_response(status, headers) ⇒ Object
-
#record_url_transition(new_url) ⇒ Object
Called whenever ‘@current_url` is about to be set to a new value during a page-load drain or a settle tick driven by a user action; queues the prior URL for surface-via- `current_url` so a polling matcher walks the intermediate chain.
-
#refresh ⇒ Object
is just a re-GET.
- #replay_history_entry(entry) ⇒ Object
- #reset! ⇒ Object
- #reset_event_sources ⇒ Object
- #reset_hijacked_fetches ⇒ Object
-
#reset_timer_state ⇒ Object
Re-sync the Ruby-side timer mirror with a freshly-rebuilt JS context.
- #reset_workers ⇒ Object
- #resolve_against(url, base) ⇒ Object
- #resolve_module_specifier(specifier, base_url) ⇒ Object
- #resolve_visit_url(url) ⇒ Object
- #response_hash(status, headers, body, url, redirected) ⇒ Object
-
#response_headers ⇒ Object
Rack 3 lowercases header names; Capybara tests do ‘[’Content-Type’]‘.
- #right_click(handle, keys = [], **opts) ⇒ Object
-
#same_document_traversal?(from, to) ⇒ Boolean
Same-document = every entry between ‘from` and `to` (inclusive) is a `:push_state` entry (or the boundary just changed state on the current URL).
- #select_option(handle) ⇒ Object
-
#send_keys(handle, keys) ⇒ Object
Capybara’s ‘send_keys` accepts Strings and Symbols (special keys: `:enter`, `:tab`, `:backspace`, …) and Array combos (modifier + key).
- #send_session_key(key) ⇒ Object
-
#send_session_keys(keys) ⇒ Object
Session-level keystroke.
-
#set_geolocation(latitude: nil, longitude: nil, accuracy: 10, denied: false, **rest) ⇒ Object
CDP-ish shim: override navigator.geolocation (like CDP’s ‘Emulation.setGeolocationOverride`).
- #set_header(name, value) ⇒ Object
-
#set_importmap(json) ⇒ Object
JS-side ‘ingestImportmaps` calls this through the host fn so Ruby-side `resolve_module_specifier` agrees with the bare- specifier map shipped by `<script type=“importmap”>`.
- #set_value_with_events(handle, value) ⇒ Object
- #set_viewport(w, h) ⇒ Object
-
#settle ⇒ Object
Yield on the first observable change.
- #shadow_root_handle(handle) ⇒ Object
- #stack_resolver ⇒ Object
- #start_trace(metadata = {}) ⇒ Object
- #status_code ⇒ Object
- #storage_clear(kind) ⇒ Object
-
#storage_get(kind, key) ⇒ Object
Web Storage host-fn shims.
- #storage_key(kind, index) ⇒ Object
- #storage_length(kind) ⇒ Object
- #storage_remove(kind, key) ⇒ Object
- #storage_set(kind, key, value) ⇒ Object
-
#submit_form(handle) ⇒ Object
‘Node#submit(*)` (Capybara DSL) hits here.
-
#submit_form_handle(form_handle, submitter_handle) ⇒ Object
Pulls the serialised form-state out of JS, encodes it, and drives the Rack app via ‘navigate` (for GET) or a POST.
-
#syntax_or_invalid_selector_error?(e) ⇒ Boolean
JS-side selector parser throws a ‘DOMException(’csim: …‘, ’SyntaxError’)‘.
- #tag(handle) ⇒ Object
- #tag_name(handle) ⇒ Object
- #text(handle) ⇒ Object
- #text_response?(headers) ⇒ Boolean
-
#tick_real_time(step_ms: nil) ⇒ Object
Advance the virtual JS clock and fire timers that came due.
- #timer_wait_elapsed? ⇒ Boolean
- #title ⇒ Object
- #transfer_buffer_fetch(id) ⇒ Object
-
#transfer_buffer_fetch_for_js(id) ⇒ Object
Wraps the raw bytes in whatever binary shape the ACTIVE runtime can marshal to a JS Uint8Array (V8: the BINARY-tagged string itself — tag-driven marshalling crosses it as a Uint8Array; QuickJS: base64 that the JS shim’s ‘fetchedToBytes` atob’s — it has no binary marshaller).
-
#transfer_buffer_stash(bytes) ⇒ Object
── postMessage transferable-buffer registry ───────────────────.
- #unselect_option(handle) ⇒ Object
- #update_current_hash(url) ⇒ Object
- #value(handle) ⇒ Object
- #viewport_height ⇒ Object
- #viewport_width ⇒ Object
- #visible?(handle) ⇒ Boolean
- #visible_text(handle) ⇒ Object
-
#visit(url) ⇒ Object
Address-bar navigation: no Referer, and relative paths resolve against the host root (not the current page’s directory).
- #webauthn ⇒ Object
-
#with_modal(handler) ⇒ Object
Push a one-shot handler onto the modal-dialog stack — the next modal that fires consumes the topmost handler.
- #worker_pending? ⇒ Boolean
- #worker_post_to_worker(handle, data) ⇒ Object
-
#worker_spawn(url) ⇒ Object
── Web Workers ────────────────────────────────────────────────.
- #worker_terminate(handle) ⇒ Object
- #write_document_cookie(s) ⇒ Object
- #xpath_shaped?(s) ⇒ Boolean
Constructor Details
#initialize(app, driver: nil, js_engine: nil, cookies: nil, local_storage: nil) ⇒ Browser
Returns a new instance of Browser.
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 |
# File 'lib/capybara/simulated/browser.rb', line 162 def initialize(app, driver: nil, js_engine: nil, cookies: nil, local_storage: nil) @app = app @driver = driver @runtime = build_runtime(js_engine) # Per-poll clock decisions cached at construction (CLAUDE.md rule 3 — the # runtime type + env are fixed for the session): the wall-sync escape # hatch and whether the runtime exposes the fast-forward timer query. @clock_wall = !ENV['CSIM_CLOCK_WALL'].nil? @runtime_supports_ff = @runtime.respond_to?(:next_timer_delay_ms) @current_url = nil # Real browsers yield control between asynchronous URL # transitions (XHR-driven model loads, then `replaceWith` to a # child route), so Capybara polls catch the intermediate URL — # e.g. Discourse's `/wizard` → `/wizard/steps/setup` flow holds # at `/wizard` while `Wizard.load()` runs. Our env drains # microtasks synchronously and only the final URL is reachable # by the time Ruby regains control. Queue URLs we transitioned # through; `current_url` shifts one out per call so a polling # `assert_current_path` walks the same set the real browser # would have observed. @recent_urls = [] @recent_urls_last_push_at = nil # The URL the page was at when the current user-action drain began. # It's the *starting point* of the action, not an intermediate the # action transitioned through, so a pushState/replaceState back to a # fresh URL during the drain (a Turbo Drive Visit triggered by the # action) must NOT queue it into `@recent_urls` — otherwise a one-shot # `current_url` read after the action returns the pre-action URL # instead of the navigated-to one (Avo filter `encoded_filters`). @action_url_baseline = nil # The URL of the page that navigated to the current document — # HTTP `Referer` header on the response that loaded the page, # exposed to JS as `document.referrer`. Tracked by `navigate` # so post-auth flows (Discourse login: `cookie('destination_url', # referrer)` when navigating from `/t/N` → `/login` via link # click) can reconstruct the origin URL. @current_referer = '' # Cookies + localStorage are origin-shared in real browsers — # the Driver injects the jars so aux windows (per-window VMs) # see the same auth state and storage as the primary. Tests # without a Driver (gem-internal callers) get fresh jars. @cookies = || {} @local_storage = local_storage || {} @session_storage = {} @sticky_headers = {} @timers_active = false # Capybara config is set once per suite; cache the derived # origin so the per-request fallback path doesn't re-dispatch # `Capybara.app_host` / `server_host` / `server_port` on every # rack call (CLAUDE.md: cache env decisions at construction). @default_host = self.class.default_host # Handle IDs are per-Context integer sequences: a handle from # a pre-rebuild context could collide with a fresh node's id # in the new context. Node captures this on construction; # `check_stale` rejects on mismatch. @context_gen = 0 @find_cache_dirty = true @find_cache_kind = nil @find_cache_arg = nil @find_cache_ctx = nil @find_cache_value = nil @document_handle = 0 @last_tick_ts = Process.clock_gettime(Process::CLOCK_MONOTONIC) @polling_grace = nil @last_polled_gen = nil @idle_settle_polls = 0 @ticking = false @history = [] @history_idx = -1 @modal_handlers = [] # Geolocation override (CDP-ish). nil = no override configured → # navigator.geolocation reports POSITION_UNAVAILABLE. Ruby-backed so # it survives the per-call VM rebuilds, like web storage. Read by the # `__csimGeolocationState` host fn. @geolocation = nil # Per-test action trace. `@trace` is the live recorder; `reset!` # moves it to `@pending_trace` so an after-hook running after # session reset still has access. `@trace_mode` is cached at # construction so `record_action`'s hot path doesn't pay an # ENV lookup. # # `CSIM_TRACE=off|on-failure|full` (default `on-failure`): # - `off` — no recording at all; `record_action` early-exits. # - `on-failure` — record kind/url/console/network in-memory; # snapshot `dom_after` only on action error. # - `full` — record + snapshot DOM after every action # (debug-heavy). # File output is orthogonal — `CSIM_TRACE_DIR=path` makes the # test-runner hook persist the trace JSON there; unset means # in-memory only (no files written without explicit opt-in). @trace = nil @pending_trace = nil @recording_action = false @trace_mode = parse_trace_mode(ENV['CSIM_TRACE']) # EventSource (SSE) — per-Browser handle counter, background # reader threads, and a thread-safe Queue of parsed events # awaiting delivery into the VM. Threads do the long-lived # HTTP read; the main thread polls the Queue in `settle` and # dispatches via `__csim_deliverEventSourceEvents`. @event_source_seq = 0 @event_source_threads = {} @event_source_queue = Thread::Queue.new # Hijacked-XHR delivery — per-Browser handle counter, # background threads, and a Queue of completed responses for # Rack calls where the middleware used `rack.hijack` to hold # the connection open (the contract `message_bus`'s long-poll # uses to push publishes immediately rather than waiting for # the next client poll). Same shape as SSE: the thread reads # the hijacked pipe; main settle drains the Queue and # dispatches via `__csim_deliverHijackedFetches`. @hijack_fetch_seq = 0 @hijack_fetch_threads = {} @hijack_fetch_queue = Thread::Queue.new # Web Workers — per-Browser handle counter, per-worker # {thread, inbox} pair, and a shared outbox the main settle # drains via `__csim_deliverWorkerMessages`. Each worker # thread owns its own V8 Context / QuickJS VM (real isolate); # cross-isolate messaging is JSON-marshalled. @worker_seq = 0 @workers = {} @worker_outbox = Thread::Queue.new # Outstanding posts-to-worker; `polling?` stays true while > 0 # so long-running compute (e.g. mozjpeg over an 8900×8900 frame) # isn't starved by the settle_gen idle gate. @worker_in_flight = 0 # Cross-isolate `blob:` store. Worker isolates can't see the # main scope's `__csimBlobs` Map, so we mirror bytes here and # workers resolve them through a host fn. @blob_registry = {} @blob_registry_lock = Mutex.new # Postmessage transferable-buffer store. Large Uint8Array / # ArrayBuffer payloads cross isolates as a Ruby-side byte ID # rather than a JSON base64 string, so peak JS heap stays flat. @transfer_buffer_lock = Mutex.new @transfer_buffers = {} @transfer_buffer_seq = 0 end |
Instance Attribute Details
#context_gen ⇒ Object (readonly)
Returns the value of attribute context_gen.
1872 1873 1874 |
# File 'lib/capybara/simulated/browser.rb', line 1872 def context_gen @context_gen end |
#default_user_agent ⇒ Object
Capybara’s ‘current_window.resize_to(w, h)` lands here; the ahoy hamburger test (mobile breakpoint at 425×694) and any responsive-utility-aware test (Tailwind `m:` show / hide, bootstrap `.d-md-flex`, …) depends on this surfacing through the JS-side `innerWidth` / `innerHeight` so the cascade’s ‘mediaMatches` and `matchMedia()` evaluate against the test’s chosen viewport instead of the 1024×768 default. Sticky defaults applied at ‘reset!`. Used by the driver to carry mobile viewport / user-agent across per-test resets —without these the second mobile-tagged spec sees the desktop default. The user-agent also flows into `navigator.userAgent` on every VM rebuild so JS-side UA branches (Discourse’s ‘viewport_based_mobile_mode = false` path) resolve correctly.
1329 1330 1331 |
# File 'lib/capybara/simulated/browser.rb', line 1329 def default_user_agent @default_user_agent end |
#default_viewport ⇒ Object
Capybara’s ‘current_window.resize_to(w, h)` lands here; the ahoy hamburger test (mobile breakpoint at 425×694) and any responsive-utility-aware test (Tailwind `m:` show / hide, bootstrap `.d-md-flex`, …) depends on this surfacing through the JS-side `innerWidth` / `innerHeight` so the cascade’s ‘mediaMatches` and `matchMedia()` evaluate against the test’s chosen viewport instead of the 1024×768 default. Sticky defaults applied at ‘reset!`. Used by the driver to carry mobile viewport / user-agent across per-test resets —without these the second mobile-tagged spec sees the desktop default. The user-agent also flows into `navigator.userAgent` on every VM rebuild so JS-side UA branches (Discourse’s ‘viewport_based_mobile_mode = false` path) resolve correctly.
1329 1330 1331 |
# File 'lib/capybara/simulated/browser.rb', line 1329 def @default_viewport end |
#pending_trace ⇒ Object (readonly)
Returns the value of attribute pending_trace.
1483 1484 1485 |
# File 'lib/capybara/simulated/browser.rb', line 1483 def pending_trace @pending_trace end |
#timers_active=(value) ⇒ Object (writeonly)
Sets the attribute timers_active
54 55 56 |
# File 'lib/capybara/simulated/browser.rb', line 54 def timers_active=(value) @timers_active = value end |
#trace ⇒ Object (readonly)
Returns the value of attribute trace.
1483 1484 1485 |
# File 'lib/capybara/simulated/browser.rb', line 1483 def trace @trace end |
#trace_mode ⇒ Object (readonly)
Returns the value of attribute trace_mode.
1483 1484 1485 |
# File 'lib/capybara/simulated/browser.rb', line 1483 def trace_mode @trace_mode end |
Class Method Details
.default_host ⇒ Object
Fallback origin for ‘visit(’/foo’)‘ and friends when no current page is loaded yet. Track Capybara’s idea of the test server (‘app_host` if set, else explicitly-configured `server_host` / `server_port`) so the host header reaching the Rack app matches what host-specific helpers expect — Discourse’s ‘setup_system_test` sets `SiteSetting.force_hostname = Capybara.server_host` / `port = Capybara.server_port`, and the request-tracker specs assert `event == Discourse.base_url_no_prefix + path`, which derives from the same SiteSetting pair. We only consult `server_host` when it was explicitly set: Capybara’s getter returns ‘’127.0.0.1’‘ when unset, but Rack::Test’s hardcoded default origin is ‘www.example.com` and capybara’s own shared specs hard-code that literal — fall back to it when no suite-side configuration is in play.
38 39 40 41 42 43 44 |
# File 'lib/capybara/simulated/browser.rb', line 38 def self.default_host return ::Capybara.app_host if ::Capybara.app_host host = ::Capybara.server_host return 'http://www.example.com' if host == '127.0.0.1' port = ::Capybara.server_port.to_i port > 0 ? "http://#{host}:#{port}" : "http://#{host}" end |
.remote_addr_for(host) ⇒ Object
153 154 155 156 |
# File 'lib/capybara/simulated/browser.rb', line 153 def self.remote_addr_for(host) = host.to_s.downcase.sub(/:\d+\z/, '').sub(/\A\[(.+)\]\z/, '\1') == 'localhost' ? REMOTE_ADDR_IPV6 : REMOTE_ADDR_IPV4 end |
Instance Method Details
#active_element_handle ⇒ Object
1450 1451 1452 1453 1454 |
# File 'lib/capybara/simulated/browser.rb', line 1450 def active_element_handle tick_real_time h = @runtime.call('__csimActiveElement').to_i h.zero? ? nil : h end |
#advance_virtual_clock_ms(ms) ⇒ Object
1850 1851 1852 1853 |
# File 'lib/capybara/simulated/browser.rb', line 1850 def advance_virtual_clock_ms(ms) ms = ms.to_i tick_real_time(step_ms: ms) if ms > 0 end |
#all_text(handle) ⇒ Object
Capybara::Driver::Node surface — Node calls ‘check_stale` before each read, and that advances the virtual clock.
584 |
# File 'lib/capybara/simulated/browser.rb', line 584 def all_text(handle) = text(handle) |
#annotate_console_message(severity, message) ⇒ Object
1567 1568 1569 1570 1571 |
# File 'lib/capybara/simulated/browser.rb', line 1567 def (severity, ) return unless ANNOTATABLE_SEVERITIES.include?(severity.to_s) return unless .is_a?(String) && .include?('://') stack_resolver.annotate() end |
#append_multipart_part(body, boundary, name, content, filename: nil, content_type: nil) ⇒ Object
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 |
# File 'lib/capybara/simulated/browser.rb', line 1933 def append_multipart_part(body, boundary, name, content, filename: nil, content_type: nil) body << "--#{boundary}\r\n" disposition = %[form-data; name="#{name}"] disposition += %[; filename="#{filename}"] if filename body << "Content-Disposition: #{disposition}\r\n" body << "Content-Type: #{content_type}\r\n" if content_type body << "\r\n" body << content.to_s.b body << "\r\n" end |
#apply_request_headers(env, headers) ⇒ Object
CGI convention: ‘Content-Type` and `Content-Length` land in env without the HTTP_ prefix. Rails / Rack params parsing reads `CONTENT_TYPE` and dispatches JSON / multipart parsers off it; sending it as `HTTP_CONTENT_TYPE` lets the request through but with the default `text/plain`, so JSON bodies from `@rails/request.js` never deserialise and the server reads an empty params hash.
2925 2926 2927 2928 2929 2930 2931 2932 2933 |
# File 'lib/capybara/simulated/browser.rb', line 2925 def apply_request_headers(env, headers) headers.each {|k, v| name = k.to_s.upcase.tr('-', '_') case name when 'CONTENT_TYPE', 'CONTENT_LENGTH' then env[name] = v.to_s else env["HTTP_#{name}"] = v.to_s end } end |
#async_io_pending? ⇒ Boolean
Cheap O(1) gate: is there any non-timer async channel with traffic that ‘tick_real_time` would drain? `tick_real_time` itself runs exactly when `worker_pending? || event_source_pending? || hijack_fetch_pending?` (plus `@timers_active`), and each of those predicates is a single `.empty?` / counter check. Reusing them here lets an attribute poll whose value is delivered only by a Worker / SSE / hijacked-fetch message (with no active timer) still drain that channel, without paying an unconditional drain on timer-driven runloop pages.
537 538 539 |
# File 'lib/capybara/simulated/browser.rb', line 537 def async_io_pending? worker_pending? || event_source_pending? || hijack_fetch_pending? end |
#attr(handle, name) ⇒ Object
574 |
# File 'lib/capybara/simulated/browser.rb', line 574 def attr(handle, name) = @runtime.call('__csimAttr', handle, name.to_s) |
#blob_register(url, body_b64) ⇒ Object
2622 2623 2624 2625 |
# File 'lib/capybara/simulated/browser.rb', line 2622 def blob_register(url, body_b64) @blob_registry_lock.synchronize { @blob_registry[url.to_s] = body_b64.to_s } nil end |
#blob_resolve(url) ⇒ Object
2627 2628 2629 |
# File 'lib/capybara/simulated/browser.rb', line 2627 def blob_resolve(url) @blob_registry_lock.synchronize { @blob_registry[url.to_s] } end |
#blob_unregister(url) ⇒ Object
2631 2632 2633 2634 |
# File 'lib/capybara/simulated/browser.rb', line 2631 def blob_unregister(url) @blob_registry_lock.synchronize { @blob_registry.delete(url.to_s) } nil end |
#build_multipart_body(fields, file_inputs) ⇒ Object
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 |
# File 'lib/capybara/simulated/browser.rb', line 1911 def build_multipart_body(fields, file_inputs) boundary = "csim-#{SecureRandom.hex(8)}" body = String.new.force_encoding(Encoding::ASCII_8BIT) fields.each do |name, value| append_multipart_part(body, boundary, name, value.to_s) end file_inputs.each do |fi| picks = @file_picks && @file_picks[fi['handle'].to_i] || [] if picks.empty? append_multipart_part(body, boundary, fi['name'].to_s, '', filename: '') else picks.each do |path| append_multipart_part(body, boundary, fi['name'].to_s, File.binread(path), filename: File.basename(path), content_type: Rack::Mime.mime_type(File.extname(path))) end end end body << "--#{boundary}--\r\n" {content_type: "multipart/form-data; boundary=#{boundary}", body: body} end |
#build_runtime(engine) ⇒ Object
313 314 315 316 317 318 319 320 321 322 323 324 325 |
# File 'lib/capybara/simulated/browser.rb', line 313 def build_runtime(engine) engine ||= detect_js_engine case engine when :v8 require_relative 'v8_runtime' V8Runtime.new(self) when :quickjs require_relative 'quickjs_runtime' QuickJSRuntime.new(self) else raise ArgumentError, "unknown CSIM_JS_ENGINE #{engine.inspect}; expected one of #{JS_ENGINES.inspect}" end end |
#cached_find(kind, arg, ctx) ⇒ Object
Single-slot cache for the most recent find_xpath / find_css / find_first_css result. Capybara’s ‘synchronize` retry loop re-issues the same find on every poll while waiting for an element to appear or disappear; if no DOM-mutating event has happened since the last call (no timer fired, no click / set / navigate), the result is guaranteed identical and we can skip the V8 round-trip + xpathway traversal.
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 |
# File 'lib/capybara/simulated/browser.rb', line 548 def cached_find(kind, arg, ctx) if !@find_cache_dirty && @find_cache_kind == kind && @find_cache_ctx == ctx && @find_cache_arg == arg return @find_cache_value end result = yield @find_cache_kind = kind @find_cache_arg = arg @find_cache_ctx = ctx @find_cache_value = result @find_cache_dirty = false result end |
#check_stale(handle, initial, gen = nil) ⇒ Object
615 616 617 618 619 620 621 622 |
# File 'lib/capybara/simulated/browser.rb', line 615 def check_stale(handle, initial, gen = nil) return if initial && (gen.nil? || gen == @context_gen) && @runtime.call('__csimAlive', handle) tick_real_time return if initial && (gen.nil? || gen == @context_gen) && @runtime.call('__csimAlive', handle) raise Capybara::Simulated::StaleElement, "Element with handle #{handle} is no longer attached to the document" end |
#clear_trace! ⇒ Object
1506 1507 1508 1509 1510 |
# File 'lib/capybara/simulated/browser.rb', line 1506 def clear_trace! @trace = nil @pending_trace = nil @runtime.call('__csimSetTraceActive', false) end |
#click(handle, keys = [], **opts) ⇒ Object
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 |
# File 'lib/capybara/simulated/browser.rb', line 637 def click(handle, keys = [], **opts) mark_action_baseline tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) init = click_event_init(handle, keys, opts) delay = opts[:delay].to_f action = if delay > 0 # Wall-sleep between mousedown and mouseup so click handlers # reading `Date.now()` see the elapsed gap (selenium parity). init['mouseDownOnly'] = true partial = @runtime.call('__csimClickResolve', handle, init) sleep delay @runtime.call('__csimClickFinish', handle, partial.is_a?(Hash) ? partial['base'] : init) else @runtime.call('__csimClickResolve', handle, init) end unless action.is_a?(Hash) settle # Drain the download intent the click chain may have queued. # Avo's action-download path: form submit → Turbo applies a # turbo-stream → `StreamActions.download` → file-saver's # `saveAs` → `setTimeout(() => click(<a download>), 0)` → # our dispatchEvent default-action sets # `__csimPendingDownload`. Settle bails on the first # observable change (the stream-render mutation), so the # await-chain inside the stream's `connectedCallback` # (`await nextRepaint(); await performAction()` → # `setTimeout(click(a), 0)`) hasn't reached saveAs yet — # nudge it forward with a few alternating microtask / # timer drain rounds, then consume directly. (Can't route # via `tick_real_time`: post-drain `@timers_active` is # false and it bails before its own consume_pending_* # drains.) if @runtime.respond_to?(:drain_microtasks) && @runtime.respond_to?(:drain_timers) # Most clicks don't queue any timers; bail as soon as a # round drains nothing rather than burning the full 8 engine # round-trips. Profile (Avo actions_spec / V8): the # unconditional loop cost ~7.7 % of wall time. 8.times do @runtime.drain_microtasks break if @runtime.drain_timers(50).to_i.zero? end end consume_pending_download # Discourse's `lib/click-track.js` preventDefaults link # clicks and routes navigation through `DiscourseURL # .redirectTo → window.location = href`, which our setter # parks on `@pending_location`. Drain it here so attachment # downloads from `click_link` complete inside the click # action. consume_pending_location return end case action['kind'] when 'navigate' url = action['url'].to_s target = action['target'].to_s # `target="_blank"` (or any non-_self/_top/_parent name) opens # in a new browsing context. URL-only multi-window mode # records the URL against a fresh aux handle; the primary # stays put (per HTML spec — original window is unaffected). if !target.empty? && !%w[_self _top _parent].include?(target.downcase) && @driver.respond_to?(:open_aux_window) @driver.open_aux_window(resolve_against_current(url, use_base: true)) # In-page anchor links (`#frag` / current-page + `#frag`) move # the hash but don't fetch a new document. Pure-fragment also # short-circuits the `<a>`s test fixtures use as click sinks. elsif (url) update_current_hash(url) else # Drain any work the click handler queued before the VM gets # rebuilt — analytics libraries (Ahoy / segment / GA) queue # the event into a setTimeout-driven flush and rely on the # browser firing it before navigation tears their context # down. Without this drain the tracking POST is lost on # every internal link click. tick_real_time # Link clicks honour `<base href>` (HTML spec); `visit` # does not — that's address-bar navigation. navigate(resolve_against_current(url, use_base: true)) end when 'submit' # Drain any work the click handler queued before the form # submission. Mastodon's logout flow: submit-button click # fires the form handler, which kicks off an axios DELETE for # `/auth/sign_out`; the response sets # `window.location.href = '/auth/sign_in'`. Without the # drain, we'd submit the form (no `action` attr → current # URL, e.g. `/start`) before the XHR resolves, landing on # the wrong page. Loop matches the navigate branch — bail # as soon as a drain round fires nothing. submit_baseline_url = @current_url if @runtime.respond_to?(:drain_microtasks) && @runtime.respond_to?(:drain_timers) 8.times do @runtime.drain_microtasks break if @runtime.drain_timers(50).to_i.zero? end end # If the drain queued or consumed a `location.assign`, that # navigation supersedes the form's default submit. Honour # pending; if `@current_url` already changed mid-drain (the # navigate landed during a timer fire), skip the form submit # entirely — its form handle is in a stale VM by now. if @pending_location consume_pending_location elsif @current_url != submit_baseline_url # Already navigated; nothing more to do. else submit_form_handle(action['formHandle'], action['submitter']) end when 'download' download_link(resolve_against_current(action['url'].to_s), action['filename'].to_s) end end |
#click_event_init(handle, keys, opts) ⇒ Object
Resolve click offset against the element’s CSS-declared box. ‘opts == :center` means “x/y is relative to the element’s centre” (Capybara’s w3c_click_offset semantics); otherwise the offset is relative to the top-left. We don’t run a real layout engine — ‘__csimElementRect` reads top / left / width / height from the cascade so tests that declare those values via CSS see honest coordinates.
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 |
# File 'lib/capybara/simulated/browser.rb', line 1013 def click_event_init(handle, keys, opts) out = modifier_flags(keys) has_xy = opts[:x] || opts[:y] center = opts[:offset] == :center || !has_xy if has_xy || center rect = @runtime.call('__csimElementRect', handle) base_x = rect['x'].to_f + (center ? rect['width'].to_f / 2.0 : 0.0) base_y = rect['y'].to_f + (center ? rect['height'].to_f / 2.0 : 0.0) out['clientX'] = base_x + opts[:x].to_f out['clientY'] = base_y + opts[:y].to_f end out end |
#coerce_set_value(v) ⇒ Object
869 870 871 872 873 874 875 |
# File 'lib/capybara/simulated/browser.rb', line 869 def coerce_set_value(v) case v when Pathname then v.to_s when Array then v.map {|x| x.is_a?(Pathname) ? x.to_s : x.to_s } else v end end |
#computed_style(handle, names) ⇒ Object
603 604 605 606 607 608 |
# File 'lib/capybara/simulated/browser.rb', line 603 def computed_style(handle, names) tick_real_time result = @runtime.call('__csimComputedStyle', handle, names.map(&:to_s)) return names.to_h {|n| [n, ''] } unless result.is_a?(Hash) result.transform_keys(&:to_s) end |
#consume_pending_download ⇒ Object
‘<a download>` clicked synthetically (file-saver’s saveAs ships a freshly-created anchor through ‘dispatchEvent(MouseEvent ’click’)‘). The bridge queues `filename` on __csimPendingDownload during the click default-action; we drain here at every tick so the file lands in `downloads_directory` before Capybara’s ‘wait_for_download` polls.
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 |
# File 'lib/capybara/simulated/browser.rb', line 1265 def consume_pending_download pending = @runtime.call('__csimTakePendingDownload') return unless pending.is_a?(Hash) && pending['url'] url = pending['url'].to_s filename = pending['filename'].to_s if url.start_with?('blob:') b64 = @runtime.call('__csimReadBlobBase64', url) return if b64.nil? content = Base64.decode64(b64.to_s) name = filename.empty? ? 'download' : filename dir = downloads_directory FileUtils.mkdir_p(dir) File.binwrite(File.join(dir, name), content) else download_link(resolve_against_current(url, use_base: true), filename) end end |
#consume_pending_form_submit ⇒ Object
Read the form-submit pending intent set by JS-side ‘form.submit()` / `form.requestSubmit()`. Called by user-action entry points (click is the primary, but a `<select onchange=“$ (’#form’).submit()”>‘ pattern reaches here through select_option). Without this hop the intent sits on the slot forever and the form never actually navigates / POSTs.
1151 1152 1153 1154 1155 |
# File 'lib/capybara/simulated/browser.rb', line 1151 def consume_pending_form_submit pending = @runtime.call('__csimTakePendingFormSubmit') return unless pending.is_a?(Hash) && pending['formHandle'] submit_form_handle(pending['formHandle'].to_i, pending['submitterHandle']) end |
#consume_pending_history_traverse ⇒ Object
1415 1416 1417 1418 1419 |
# File 'lib/capybara/simulated/browser.rb', line 1415 def consume_pending_history_traverse return unless (target = @pending_history_traverse) @pending_history_traverse = nil perform_history_traverse(target) end |
#consume_pending_location ⇒ Object
3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 |
# File 'lib/capybara/simulated/browser.rb', line 3011 def consume_pending_location return unless (url = @pending_location) @pending_location = nil # A `location.href`/`assign`/`hash` set to a same-document # fragment (e.g. `location.hash = ''`) is NOT a document fetch — # move the hash without rebuilding the VM, matching the anchor- # click navigate branch. Without this a hash assignment reloaded # the page, discarding all JS state. if (url) update_current_hash(url) else navigate(url) end end |
#consume_pending_navigation ⇒ Object
Read the anchor-navigation pending intent set by JS-side ‘el.click()` (Element.prototype.click) on an `<a href>`. Avo’s boolean-filter / select-filter controllers respond to ‘input` events by building the filtered URL and calling `urlRedirectTarget.click()` on a hidden anchor; the click chain starts from Ruby’s ‘set_value_with_events` rather than `click`, so without a parallel drain here the navigation stays queued and the page never reloads.
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 |
# File 'lib/capybara/simulated/browser.rb', line 1244 def pending = @runtime.call('__csimTakePendingNavigation') return unless pending.is_a?(Hash) && pending['url'] url = pending['url'].to_s target = pending['target'].to_s if !target.empty? && !%w[_self _top _parent].include?(target.downcase) && @driver.respond_to?(:open_aux_window) @driver.open_aux_window(resolve_against_current(url, use_base: true)) elsif (url) update_current_hash(url) else tick_real_time navigate(resolve_against_current(url, use_base: true)) end end |
#consume_pending_reload ⇒ Object
3032 3033 3034 3035 3036 |
# File 'lib/capybara/simulated/browser.rb', line 3032 def consume_pending_reload return unless @pending_reload @pending_reload = false refresh end |
#current_path ⇒ Object
1685 1686 1687 1688 1689 1690 1691 |
# File 'lib/capybara/simulated/browser.rb', line 1685 def current_path tick_real_time return '' if @current_url.nil? || @current_url.empty? URI.parse(@current_url).path rescue URI::InvalidURIError '' end |
#current_referer ⇒ Object
3094 |
# File 'lib/capybara/simulated/browser.rb', line 3094 def current_referer ; @current_referer.to_s ; end |
#current_url ⇒ Object
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 |
# File 'lib/capybara/simulated/browser.rb', line 376 def current_url tick_real_time # `tick_real_time` may have queued URL transitions via # `record_url_transition`. A polling matcher # (`have_current_path`) calls here once per ~50 ms iteration # and shifts one entry per call so it walks the same # intermediate-URL chain a real browser would have observed # before microtasks all collapsed onto the final URL — the # finish_installation_spec wizard chain depends on this for # the `/wizard` step before the JS replaceWith to # `/wizard/steps/setup` lands. A non-polling read # (`topic_url = page.current_url` long after the prior # action's settle) just wants the current URL; drop entries # older than the polling-cadence window so they don't leak # into an unrelated call (tags_spec:221's composer-submit # leaves `/new-topic` queued, and the read happens minutes # of test wall-clock later). if @recent_urls_last_push_at && @recent_urls.any? age_ms = Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond) - @recent_urls_last_push_at @recent_urls.clear if age_ms > RECENT_URLS_STALE_AGE_MS end return @recent_urls.shift if @recent_urls.any? @current_url || '' end |
#decode_image(b64_bytes, max_w = nil, max_h = nil) ⇒ Object
── Image decode (libvips) ─────────────────────────────────────
Called by the JS bridge whenever a Canvas / OffscreenCanvas path needs raw RGBA pixels — ‘drawImage(image, …)` whose source is an HTMLImageElement / Blob / ImageBitmap with encoded bytes still on the wire. ruby-vips decodes any format libvips supports (PNG, JPEG, WebP, GIF, …) into a contiguous row-major RGBA buffer. Returns `height, refId` — the raw bytes land in the transfer-buffer registry so the JS side fetches them as a `Uint8Array` (tag-driven binary marshalling) rather than building a 423 MB latin-1 + base64 intermediate for the 8900×8900 frames Discourse uploads exercise. Optional `max_w`/`max_h` lets the caller pre-shrink for cheap OCR-style “downscale before pixel-touch” flows.
2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 |
# File 'lib/capybara/simulated/browser.rb', line 2576 def decode_image(b64_bytes, max_w = nil, max_h = nil) host_image_op('decode_image') { require 'vips' unless defined?(Vips) bytes = Base64.decode64(b64_bytes.to_s) # `access: :sequential` keeps libvips from applying the # source's ICC profile mid-stream (changes RGBA values by ±2 # vs raw decode). `colourspace('srgb')` is the same ICC # transform Chrome's createImageBitmap runs, but rounding # differs by a few ulp; only convert when libvips reports # a non-sRGB interpretation, otherwise trust the bytes. img = Vips::Image.new_from_buffer(bytes, '', access: :sequential) img = img.colourspace('srgb') unless img.interpretation == :srgb || img.interpretation == :rgb img = img.bandjoin(255) if img.bands < 4 if max_w && max_h && max_w.to_i > 0 && max_h.to_i > 0 && (img.width > max_w.to_i || img.height > max_h.to_i) shrink_x = img.width.to_f / max_w.to_i shrink_y = img.height.to_f / max_h.to_i shrink = [shrink_x, shrink_y].max img = img.resize(1.0 / shrink) if shrink > 1 end raw = img.write_to_memory {'width' => img.width, 'height' => img.height, 'refId' => transfer_buffer_stash(raw)} } end |
#decode_response_bom(s) ⇒ Object
Strip + decode a single leading byte-order mark, mapping the body to a UTF-8 Ruby string. No BOM → return the bytes untouched (the hot path: just a 2–3 byte prefix check). One BOM is consumed; any further BOMs are ordinary U+FEFF characters in the decoded text (per spec the parser does not strip them again).
2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 |
# File 'lib/capybara/simulated/browser.rb', line 2972 def decode_response_bom(s) b = s.b if b.start_with?("\xEF\xBB\xBF".b) b.byteslice(3..).force_encoding(Encoding::UTF_8) elsif b.start_with?("\xFF\xFE".b) || b.start_with?("\xFE\xFF".b) # Generic UTF-16: the BOM picks endianness and is dropped by the decoder. # Replace malformed units rather than raising (a truncated/odd-length # body still yields readable UTF-8 instead of falling back to raw bytes). b.force_encoding(Encoding::UTF_16).encode(Encoding::UTF_8, invalid: :replace, undef: :replace) else s end rescue StandardError s end |
#decode_video_frame(b64_bytes) ⇒ Object
── Video decode (ffprobe + ffmpeg) ────────────────────────────
Called from the JS bridge when a ‘<video>` element’s ‘src` is assigned a `blob:` URL. ffprobe extracts dimensions + duration, ffmpeg extracts the first frame as raw RGBA. JS caches both so `canvas.drawImage(video, …)` blits like any ImageBitmap.
2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 |
# File 'lib/capybara/simulated/browser.rb', line 2674 def decode_video_frame(b64_bytes) host_image_op('decode_video_frame') { bytes = Base64.decode64(b64_bytes.to_s) next nil if bytes.empty? require 'tempfile' require 'json' Tempfile.create(['csim-video', '.bin'], binmode: true) do |f| f.write(bytes) f.flush info = ffprobe_stream(f.path) or break nil width = info['width'].to_i height = info['height'].to_i break nil if width <= 0 || height <= 0 raw = ffmpeg_first_frame_rgba(f.path) duration = (info['duration'] || info.dig('format_duration')).to_f result = {'width' => width, 'height' => height, 'duration' => duration} result['refId'] = transfer_buffer_stash(raw) if raw && !raw.empty? result end } end |
#deliver_event_source_events ⇒ Object
Drain any queued events into the VM. Cheap when no SSE connection is active (no threads → no queue items → empty return). Returns the number of events delivered so settle can tell whether progress was made.
2164 2165 2166 2167 2168 2169 2170 |
# File 'lib/capybara/simulated/browser.rb', line 2164 def deliver_event_source_events return 0 if @event_source_threads.empty? && @event_source_queue.empty? events = event_source_poll return 0 if events.empty? @runtime.call('__csim_deliverEventSourceEvents', events) events.size end |
#deliver_hijacked_fetches ⇒ Object
2411 2412 2413 2414 2415 2416 2417 |
# File 'lib/capybara/simulated/browser.rb', line 2411 def deliver_hijacked_fetches return 0 if @hijack_fetch_threads.empty? && @hijack_fetch_queue.empty? responses = drain_queue(@hijack_fetch_queue) return 0 if responses.empty? @runtime.call('__csim_deliverHijackedFetches', responses) responses.size end |
#deliver_worker_messages ⇒ Object
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 |
# File 'lib/capybara/simulated/browser.rb', line 2549 def return 0 if @workers.empty? && @worker_outbox.empty? events = drain_queue(@worker_outbox) return 0 if events.empty? # `__error` postbacks don't correspond to a prior post, so # bottom out at zero. @worker_in_flight = [0, @worker_in_flight - events.size].max @runtime.call('__csim_deliverWorkerMessages', events) events.size end |
#describe_node_handle(handle) ⇒ Object
‘tag#id.class` short description of the handle, for trace `description` fields. One V8 round-trip; only paid when a step is actively being recorded (`record_action` lazy-evaluates the description Proc).
1583 1584 1585 1586 1587 1588 1589 1590 1591 |
# File 'lib/capybara/simulated/browser.rb', line 1583 def describe_node_handle(handle) return "handle=#{handle}" if handle.nil? || handle.zero? info = @runtime.call('__csimDescribeNode', handle) return "handle=#{handle}" unless info.is_a?(Hash) s = info['tag'].to_s s += "##{info['id']}" unless info['id'].to_s.empty? s += ".#{info['cls']}" unless info['cls'].to_s.empty? s end |
#disabled?(handle) ⇒ Boolean
588 589 590 591 592 593 594 595 596 597 |
# File 'lib/capybara/simulated/browser.rb', line 588 def disabled?(handle) = @runtime.call('__csimDisabled', handle) # HTML spec: `<option>.selected` IDL is true when the `selected` # *attribute* is set OR when no sibling option has `selected` and # this is the first non-disabled option of a single-select # `<select>` (implicit default). Capybara's `have_select(selected: # "Choose an option")` filter calls `selected?` on each option; # without the implicit-default branch, a select with no explicit # `<option selected>` reports no selected options and the matcher # fails even though the first option *is* the currently chosen # one in real browsers. |
#dispatch_event(handle, type, init = {}) ⇒ Object
1044 1045 1046 1047 1048 1049 |
# File 'lib/capybara/simulated/browser.rb', line 1044 def dispatch_event(handle, type, init = {}) tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) @runtime.call('__csimDispatchEvent', handle, type.to_s, init) end |
#document_cookie ⇒ Object
‘document.cookie` is TEXT; jar entries parsed out of Rack’s Set-Cookie headers can carry the BINARY tag, which would make the joined string cross into JS as a Uint8Array (‘document.cookie.match is not a function`). Cookies are ASCII per RFC 6265.
3091 3092 3093 |
# File 'lib/capybara/simulated/browser.rb', line 3091 def RuntimeShared.utf8_text(@cookies.map {|k, v| "#{k}=#{v}" }.join('; ')) end |
#double_click(handle, keys = [], **opts) ⇒ Object
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 |
# File 'lib/capybara/simulated/browser.rb', line 970 def double_click(handle, keys = [], **opts) mark_action_baseline tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) # UI Events spec: two full mousedown→mouseup→click chains # before the trailing `dblclick`. Jspreadsheet (table-builder's # `.jss_worksheet`) enters edit mode on the inner mousedown. 2.times { @runtime.call('__csimClickResolve', handle, opts) } init = {'bubbles' => true, 'cancelable' => true}.merge(click_event_init(handle, keys, opts)) @runtime.call('__csimDispatchEvent', handle, 'dblclick', init) # Real browsers' default-action on dblclick selects the word # under the cursor — ProseMirror / Tiptap "paste URL over # selection wraps with link" tests rely on the word being # selected before the paste. @runtime.call('__csimSelectWordAt', handle) settle end |
#download_link(url, filename_hint = '') ⇒ Object
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 |
# File 'lib/capybara/simulated/browser.rb', line 753 def download_link(url, filename_hint = '') env = Rack::MockRequest.env_for(url, method: 'GET') env['HTTP_USER_AGENT'] = @default_user_agent || USER_AGENT env['REMOTE_ADDR'] = self.class.remote_addr_for(env['HTTP_HOST'] || env['SERVER_NAME']) env['HTTP_COOKIE'] = unless @cookies.empty? env['HTTP_REFERER'] = @current_url unless @current_url.nil? || @current_url.empty? status, headers, body = @app.call(env) return unless status.to_i == 200 # Fall back to the link's `download="filename"` value or the # URL path tail when Content-Disposition is absent — `<a download>` # is the spec hook for naming a download independently of the # response headers. forced_headers = headers.dup if content_disposition_header(forced_headers).to_s.empty? name = filename_hint.empty? ? File.basename(URI.parse(url).path.to_s) : filename_hint forced_headers['Content-Disposition'] = %(attachment; filename="#{name}") unless name.empty? end save_downloaded_response(url, forced_headers, body) end |
#drag_to(source_handle, target_handle, **_opts) ⇒ Object
Element-to-element drag. Capybara’s ‘Element#drag_to(target, delay: …)` lands here. Fires the HTML5 drag event sequence on the source / target pair (mousedown → dragstart → dragenter →dragover → drop → dragend) with a shared DataTransfer. Discourse sidebar reorder + Avo Sortable-shaped widgets read the `event.offsetY` to decide “above vs below”; without a layout engine we report 0, which routes drops above the target.
947 948 949 950 951 952 953 954 955 |
# File 'lib/capybara/simulated/browser.rb', line 947 def drag_to(source_handle, target_handle, **_opts) mark_action_baseline tick_real_time invalidate_find_cache ensure_alive_after_tick(source_handle) ensure_alive_after_tick(target_handle) @runtime.call('__csimDragOnto', source_handle, target_handle) drain_after_user_action end |
#drain_after_user_action ⇒ Object
Every user-action entry point (set / send_keys / select / unselect) ends in this trio: drain any pending form submit, drain any pending Element.click anchor activation, then settle the page. Missing one site silently breaks the Stimulus filter pattern that wires ‘link.click()` into input/change/keypress listeners.
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 |
# File 'lib/capybara/simulated/browser.rb', line 1179 def drain_after_user_action consume_pending_form_submit settle # Settle bails on first observable change, but Backburner-style # 500 ms debounces park behind a setTimeout that hasn't fired # yet. Drain one 600 ms window so input → debounce → parent # state propagation completes before the next Capybara call. @runtime.drain_timers(USER_ACTION_DRAIN_MS) if @timers_active && @runtime.respond_to?(:drain_timers) end |
#drain_pending_navigation ⇒ Object
3037 3038 3039 3040 3041 |
# File 'lib/capybara/simulated/browser.rb', line 3037 def consume_pending_location consume_pending_reload consume_pending_history_traverse end |
#drop(handle, args) ⇒ Object
HTML5 drag-and-drop simulation. Capybara routes ‘Element#drop` here with a flat list of paths / Pathnames / Hashes; build a DataTransfer-shaped object and dispatch dragenter / dragover / drop in sequence.
932 933 934 935 936 937 938 |
# File 'lib/capybara/simulated/browser.rb', line 932 def drop(handle, args) tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) items = args.flat_map {|arg| drop_items(arg) } @runtime.call('__csimDropOnto', handle, items) end |
#drop_items(arg) ⇒ Object
956 957 958 959 960 961 962 963 964 965 966 967 968 |
# File 'lib/capybara/simulated/browser.rb', line 956 def drop_items(arg) case arg when Hash arg.map {|type, value| {'kind' => 'string', 'type' => type.to_s, 'value' => value.to_s} } when ->(x) { x.respond_to?(:to_path) } path = arg.to_path [{'kind' => 'file', 'name' => File.basename(path), 'path' => path}] when String [{'kind' => 'file', 'name' => File.basename(arg), 'path' => arg}] else [] end end |
#durable_source(url) ⇒ Object
Fetch a source body and report how long it stays safely reusable per its OWN response headers — an absolute freshness deadline (Time), or nil when the response is not durably cacheable (no-store / no-cache / max-age=0 / dynamic with no freshness). This lets a loader persist the body across visits and skip the round-trip next time, driven by the server’s cache directives (RFC 9111 §5.2.2 / §4.2.2 heuristic) — NOT a URL-shape guess. ‘clear_volatile` drops the body from the volatile per-visit asset cache, but a content-hashed asset’s source is content-stable while fresh, so a loader’s own cross-visit cache can hold it for ‘fresh_until`. Used by the external-asset cache (`external_asset_source`, scripts + stylesheets); name is generic.
2057 2058 2059 2060 2061 2062 2063 |
# File 'lib/capybara/simulated/browser.rb', line 2057 def durable_source(url) body = rack_fetch_body(url) return [nil, nil] unless body entry = @@asset_cache.lookup(url) fresh_until = entry && entry.fresh? && entry.max_age ? entry.stored_at + entry.max_age : nil [body, fresh_until] end |
#empty_find_result?(result) ⇒ Boolean
511 512 513 |
# File 'lib/capybara/simulated/browser.rb', line 511 def empty_find_result?(result) result.nil? || (result.respond_to?(:empty?) && result.empty?) end |
#encode_image(pixels_ref, width, height, mime_type = 'image/png', quality = 90) ⇒ Object
2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 |
# File 'lib/capybara/simulated/browser.rb', line 2735 def encode_image(pixels_ref, width, height, mime_type = 'image/png', quality = 90) host_image_op('encode_image') { require 'vips' unless defined?(Vips) raw = transfer_buffer_fetch(pixels_ref).to_s w = width.to_i h = height.to_i next nil if w <= 0 || h <= 0 || raw.bytesize < w * h * 4 img = Vips::Image.new_from_memory_copy(raw, w, h, 4, :uchar) ext = MIME_TO_VIPS_EXT[mime_type.to_s.downcase] || '.png' opts = (ext == '.jpg' || ext == '.webp') ? {Q: quality.to_i} : {} {'refId' => transfer_buffer_stash(img.write_to_buffer(ext, **opts))} } end |
#ensure_alive_after_tick(handle) ⇒ Object
‘tick_real_time` may have rebuilt the DOM (Ember route hydration finishing on its first idle tick replaces server-rendered nodes with fresh ones). `Node` ran check_stale before calling here, but that was BEFORE the tick — re-verify after so Capybara catches the now-stale handle and retries the find. Otherwise `__csim*` lookups would return null and the operation would silently no-op (or, in the case of `__csimClickResolve`, dispatch on a detached node whose listeners no longer matter).
632 633 634 635 |
# File 'lib/capybara/simulated/browser.rb', line 632 def ensure_alive_after_tick(handle) return if @runtime.call('__csimAlive', handle) raise Capybara::Simulated::StaleElement, "Element with handle #{handle} is no longer attached to the document" end |
#eval_esm_module(url, src = nil) ⇒ Object
Native ESM entry point. QuickJS uses its ‘vm.module_loader`; V8 uses `Context#compile_module` + `Module#instantiate` / `#evaluate` + `Context#dynamic_import_resolver=`. Both runtimes expose `eval_esm_module`.
2113 2114 2115 |
# File 'lib/capybara/simulated/browser.rb', line 2113 def eval_esm_module(url, src = nil) @runtime.eval_esm_module(url, src) end |
#evaluate_async_script(code, args = []) ⇒ Object
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 |
# File 'lib/capybara/simulated/browser.rb', line 1666 def evaluate_async_script(code, args = []) tick_real_time invalidate_find_cache @runtime.call('__evalAsyncScript', code.to_s, marshal_args(args || [])) # Pump virtual time so any setTimeout-driven completion lands. # Capybara's polling can't help here — we're inside one session # call, not a retry loop. deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + Capybara.default_max_wait_time.to_f loop do result = @runtime.call('__pollAsyncResult') return result['value'] if result.is_a?(Hash) && result.key?('value') break if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline sleep 0.01 tick_real_time end nil end |
#evaluate_script(code, args = []) ⇒ Object
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 |
# File 'lib/capybara/simulated/browser.rb', line 1592 def evaluate_script(code, args = []) # Drain timers first so ready handlers (jQuery `$(handler)`, # framework `DOMContentLoaded` listeners) run before the # user's script. Without this, `execute_script` can fire # *before* the page's own setup code that the test expects # to be active. tick_real_time invalidate_find_cache result = @runtime.call('__csimEvalScript', code.to_s, marshal_args(args || [])) result end |
#event_source_close(id) ⇒ Object
2148 2149 2150 2151 2152 |
# File 'lib/capybara/simulated/browser.rb', line 2148 def event_source_close(id) thread = @event_source_threads.delete(id.to_i) thread&.kill nil end |
#event_source_open(url) ⇒ Object
── EventSource (SSE) ──────────────────────────────────────────
Mastodon (and any app using Server-Sent Events) opens an ‘EventSource` to a streaming endpoint and expects pushed events to fire `message`/typed listeners on the live instance. Our implementation:
1. JS-side `new EventSource(url)` calls `__csim_eventSourceOpen`
which returns an integer handle and spawns a Ruby thread.
2. The thread holds a chunked-read HTTP connection open and
parses the SSE event-stream wire format, pushing each
`{id:, type:, data:, lastEventId:}` (or `{type: '__open'}`
/ `{type: '__error', message:}` sentinel) onto a
thread-safe queue.
3. Settle's drain loop calls `deliver_event_source_events`
which polls the queue and hands the batch to
`__csim_deliverEventSourceEvents` for dispatch.
rusty_racer / quickjs.rb VMs are single-threaded; only the main thread ever enters the VM. Background threads only touch the Queue. ‘reset!` and per-visit context rebuilds kill all open threads — the new VM gets a fresh handle space.
2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 |
# File 'lib/capybara/simulated/browser.rb', line 2137 def event_source_open(url) id = (@event_source_seq += 1) queue = @event_source_queue thread = Thread.new do Thread.current.report_on_exception = false run_event_source_reader(id, url.to_s, queue) end @event_source_threads[id] = thread id end |
#event_source_pending? ⇒ Boolean
2158 |
# File 'lib/capybara/simulated/browser.rb', line 2158 def event_source_pending? = !@event_source_queue.empty? |
#event_source_poll ⇒ Object
2154 2155 2156 |
# File 'lib/capybara/simulated/browser.rb', line 2154 def event_source_poll drain_queue(@event_source_queue) end |
#execute_script(code, args = []) ⇒ Object
Fire-and-forget variant: runs the script but never returns its value to Ruby. Lets execute_script handle scripts whose return is a complex JS object (jQuery chainable, DOM tree, …) that the marshaller would recurse into.
1609 1610 1611 1612 1613 1614 1615 |
# File 'lib/capybara/simulated/browser.rb', line 1609 def execute_script(code, args = []) tick_real_time invalidate_find_cache @runtime.call('__csimExecScript', code.to_s, marshal_args(args || [])) nil end |
#external_asset_source(url) ⇒ Object
Body of an external durably-cacheable asset (classic script or stylesheet), served from the cross-visit cache when still fresh, else fetched (which read-throughs the per-visit asset cache) and cached iff durably cacheable. Returns nil on 4xx / fetch failure so the JS caller skips it exactly as the old ‘__rackFetch` branch did.
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 |
# File 'lib/capybara/simulated/browser.rb', line 2083 def external_asset_source(url) key = resolve_against_current(url.to_s) return nil unless key.is_a?(String) @@asset_src_lock.synchronize do if (e = @@asset_src[key]) return e[0] if e[1].nil? || Time.now < e[1] @@asset_src.delete(key) end end # `durable_source` already does the spec-compliant fetch + header-driven # freshness (RFC 9111 max-age → absolute deadline); reuse it instead of # re-deriving `fresh_until` here. body, fresh_until = durable_source(key) return nil unless body # Script / stylesheet source is TEXT, but the raw Rack / binread body # arrives BINARY-tagged (see `RuntimeShared.utf8_text`). body = RuntimeShared.utf8_text(body) if fresh_until @@asset_src_lock.synchronize do @@asset_src.clear if @@asset_src.size >= ASSET_SRC_MAX @@asset_src[key] = [body, fresh_until] end end body end |
#file_input?(handle) ⇒ Boolean
577 578 579 |
# File 'lib/capybara/simulated/browser.rb', line 577 def file_input?(handle) tag(handle) == 'input' && attr(handle, 'type').to_s.downcase == 'file' end |
#file_picks_for(handle) ⇒ Object
890 891 892 |
# File 'lib/capybara/simulated/browser.rb', line 890 def file_picks_for(handle) (@file_picks && @file_picks[handle]) || [] end |
#find_css(css, context_handle = nil) ⇒ Object
432 433 434 435 436 437 438 439 440 441 442 443 |
# File 'lib/capybara/simulated/browser.rb', line 432 def find_css(css, context_handle = nil) s = css.to_s return find_xpath(s, context_handle) if xpath_shaped?(s) find_with_timer_fallback(:css, s, context_handle) do @runtime.call('__csimQuery', context_handle || @document_handle, s).to_a rescue StandardError => e # Invalid selector → empty result. Callers that genuinely # need the throw go through `evaluate_script`. raise unless syntax_or_invalid_selector_error?(e) [] end end |
#find_first_css(css, context_handle = nil) ⇒ Object
445 446 447 448 449 450 451 452 453 454 |
# File 'lib/capybara/simulated/browser.rb', line 445 def find_first_css(css, context_handle = nil) s = css.to_s find_with_timer_fallback(:css_first, s, context_handle) do h = @runtime.call('__csimQueryOne', context_handle || @document_handle, s).to_i h.zero? ? nil : h rescue StandardError => e raise unless syntax_or_invalid_selector_error?(e) nil end end |
#find_with_timer_fallback(kind, arg, ctx) ⇒ Object
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 |
# File 'lib/capybara/simulated/browser.rb', line 488 def find_with_timer_fallback(kind, arg, ctx) tick_real_time if timer_wait_elapsed? result = cached_find(kind, arg, ctx) { yield } # An empty result is the wait-for-it case: Capybara is retrying for # an element that hasn't appeared yet. Re-tick so the next poll # observes anything an active timer OR a background-IO channel # (Worker / EventSource / a held long-poll publish) is about to # deliver. Gating on `@timers_active` alone misses the held-poll # case — a MessageBus subscription waiting on a cross-session # publish has NO pending JS timer (the re-poll only schedules after # the current poll returns), so `@timers_active` is false while # `hijack_fetch_pending?` is true. Without `async_io_pending?` here # the delivered message never reaches the DOM during find-polling # (only `evaluate_script`, which ticks unconditionally, would see # it). Non-empty results keep the fast path — no extra tick. return result unless empty_find_result?(result) && (@timers_active || async_io_pending?) tick_real_time return result unless @find_cache_dirty cached_find(kind, arg, ctx) { yield } end |
#find_xpath(xpath, context_handle = nil) ⇒ Object
XPath is evaluated inside V8 against the live JS DOM via the xpathway engine (bundled, installed at snapshot build). One IPC per ‘find_xpath` — no serialise + reparse round-trip.
481 482 483 484 485 486 |
# File 'lib/capybara/simulated/browser.rb', line 481 def find_xpath(xpath, context_handle = nil) xpath_str = xpath.to_s find_with_timer_fallback(:xpath, xpath_str, context_handle) do @runtime.call('__csimEvaluateXPath', xpath_str, context_handle || 0).to_a end end |
#finish_trace_to(path, trace = (@trace || @pending_trace)) ⇒ Object
Persist ‘trace` (defaults to live or pending) to `path` and return the path. Doesn’t clear — ‘clear_trace!` is the explicit follow-up so a caller can inspect after writing if it wants.
1501 1502 1503 1504 |
# File 'lib/capybara/simulated/browser.rb', line 1501 def finish_trace_to(path, trace = (@trace || @pending_trace)) return nil unless trace trace.write_json(path) end |
#format_temporal_value(v, handle) ⇒ Object
877 878 879 880 881 882 883 884 885 886 887 888 |
# File 'lib/capybara/simulated/browser.rb', line 877 def format_temporal_value(v, handle) type = attr(handle, 'type').to_s.downcase case type when 'date' then v.respond_to?(:strftime) ? v.strftime('%Y-%m-%d') : v.to_s when 'time' then v.respond_to?(:strftime) ? v.strftime('%H:%M') : v.to_s when 'datetime-local' then v.respond_to?(:strftime) ? v.strftime('%Y-%m-%dT%H:%M') : v.to_s when 'month' then v.respond_to?(:strftime) ? v.strftime('%Y-%m') : v.to_s when 'week' then v.respond_to?(:strftime) ? v.strftime('%Y-W%V') : v.to_s else v.is_a?(Date) ? v.strftime('%Y-%m-%d') : v.to_s end end |
#geolocation_state_json ⇒ Object
Backs the ‘__csimGeolocationState` host fn. Returns the configured geolocation override as a JSON string (or ’null’ when none is set), which the JS geolocation object reads on every getCurrentPosition / watchPosition call.
1648 1649 1650 |
# File 'lib/capybara/simulated/browser.rb', line 1648 def geolocation_state_json JSON.generate(@geolocation) end |
#go_back ⇒ Object
Capybara-initiated ‘page.go_back` runs from Ruby, not inside a JS call, so it’s safe to rebuild the Context synchronously. The ‘force:` flag bypasses the deferral that `history_go` uses to avoid terminating the running JS context.
1377 |
# File 'lib/capybara/simulated/browser.rb', line 1377 def go_back ; history_go(-1, force: true) ; end |
#go_forward ⇒ Object
1378 |
# File 'lib/capybara/simulated/browser.rb', line 1378 def go_forward ; history_go(+1, force: true) ; end |
#handle_modal(type, message, default_value) ⇒ Object
JS-side ‘alert(…)` / `confirm(…)` / `prompt(…)` route here. If no handler is pushed (typical of apps under test), accept the dialog (Rails system-test default) so `data-turbo-confirm` / similar progress without an explicit `accept_confirm` in the test.
3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 |
# File 'lib/capybara/simulated/browser.rb', line 3155 def handle_modal(type, , default_value) handler = @modal_handlers.pop if handler handler.call(type, , default_value) else case type.to_s when 'alert' then nil when 'confirm' then true when 'prompt' then default_value.to_s end end end |
#hijack_fetch_pending? ⇒ Boolean
2409 |
# File 'lib/capybara/simulated/browser.rb', line 2409 def hijack_fetch_pending? = !@hijack_fetch_threads.empty? || !@hijack_fetch_queue.empty? |
#history_go(delta, force: false) ⇒ Object
Move through the history stack by ‘delta`. Per HTML spec, a same-document traversal (within a chain of pushState entries rooted at a single navigation) updates `location` and fires `popstate` with the entry’s state — no full reload. A cross- document traversal replays the entry (full navigate / re-POST).
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 |
# File 'lib/capybara/simulated/browser.rb', line 1385 def history_go(delta, force: false) delta = delta.to_i return if delta == 0 target = @history_idx + delta return if target < 0 || target >= @history.size if same_document_traversal?(@history_idx, target) # Pure pushState traversal — no VM rebuild, safe to run # inline; the popstate dispatch happens within the current # call's JS context. @history_idx = target entry = @history[target] @current_url = entry[:url] @runtime.call('__csimUpdateLocation', @current_url) @runtime.call('__csimDispatchPopState', entry[:state]) elsif force # Ruby-driven (`page.go_back`) — no live JS call to interrupt, # safe to rebuild the Context synchronously. perform_history_traverse(target) else # JS-driven (`history.back()` from a page handler): replaying # the history entry synchronously would call `rebuild_ctx` # on the still-executing Context and terminate the current # call with `ScriptTerminatedError` (terminating the # in-flight call on the isolate). Stash the intent # and drain after the call returns — mirrors # `location_assign` / `location_reload`. @pending_history_traverse = target end end |
#history_length ⇒ Object
Total history entries (after forward-tail truncation), surfaced to JS ‘history.length` via the `__historyLength` host fn.
3084 3085 3086 |
# File 'lib/capybara/simulated/browser.rb', line 3084 def history_length [@history.size, 1].max end |
#history_push(url, state = nil) ⇒ Object
‘history.pushState(state, _, url)` from SPA navigation (Turbo Visit, InstantClick, …) appends a new browser-history entry. Mirror that on the Ruby side so `Capybara#go_back` traverses within the pushState chain (fires `popstate`) and only crosses to a real reload when the back hits a `:visit` boundary.
3075 3076 3077 3078 3079 3080 |
# File 'lib/capybara/simulated/browser.rb', line 3075 def history_push(url, state = nil) resolved = resolve_against_current(url.to_s) record_url_transition(resolved) @current_url = resolved record_history({method: :get, url: resolved, state: state, kind: :push_state}) end |
#history_state(url, state = nil) ⇒ Object
‘history.pushState(state, ”, ’/path’)‘ ships the URL through `__setCurrentUrl` and lands here. Tab controllers / SPA frameworks pass a relative path; resolve it against the existing absolute `@current_url` so subsequent `resolve_against_current(href)` calls (e.g. click_link to a relative href) don’t hit ‘URI::BadURIError: both URI are relative`. `history.replaceState(state, _, url)` updates the current entry in place rather than appending. Both the state and (when given) the URL are mirrored on Ruby’s slot so a subsequent back to this entry restores the same state.
3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 |
# File 'lib/capybara/simulated/browser.rb', line 3057 def history_state(url, state = nil) if url resolved = resolve_against_current(url.to_s) record_url_transition(resolved) @current_url = resolved end return if @history_idx < 0 @history[@history_idx] = (@history[@history_idx] || {}).merge( url: @current_url, state: state, kind: @history[@history_idx] ? @history[@history_idx][:kind] : :push_state ) end |
#horizon_fast_forward_step ⇒ Object
This tick’s deterministic virtual-clock advance (ms). Default is the fixed ‘POLL_TICK_STEP_MS` — never wall-derived, so per-poll JS/Ruby/GC cost cannot shift WHEN a timer fires (the wall-sync↔perf coupling this replaces). When the page is observably idle (nothing runnable now, no background IO) but a near-future timer is parked within `FF_HORIZON_MS`, fast-forward straight to it — but only after the transient-guard window so pre-debounce states are still observed across several polls. `FF_HORIZON_MS=0` ⇒ pure fixed-step.
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 |
# File 'lib/capybara/simulated/browser.rb', line 1805 def horizon_fast_forward_step # Escape hatch to the legacy wall-sync clock (virtual advance = real # wall-elapsed per poll). The deterministic model decouples perf from # timing but can't match a real browser's wall-proportional cadence for # timing-fragile heavy-JS flows; `CSIM_CLOCK_WALL=1` restores wall-sync. if @clock_wall now = Process.clock_gettime(Process::CLOCK_MONOTONIC) step = ((now - (@wall_clock_last || now)) * 1000).to_i.clamp(0, 1000) @wall_clock_last = now return step end # (1) Background async (cheap Ruby-side checks, no V8 crossing) we must let # land before jumping the clock: advance one fixed step, reset the guard. if worker_pending? || event_source_pending? || hijack_fetch_pending? @ff_transient_polls = 0 return POLL_TICK_STEP_MS end # No fast-forward support on this runtime (e.g. a worker realm) → fixed step. return POLL_TICK_STEP_MS unless @runtime_supports_ff # ONE V8 crossing: `delay` = ms until the nearest timer; 0 = runnable now # (a rAF or a due-now timer — equivalent to `has_ready_timer?`), -1 = none. delay = @runtime.next_timer_delay_ms # (2) Runnable now → fixed step, reset guard (not a quiet pre-debounce window). if delay.zero? @ff_transient_polls = 0 return POLL_TICK_STEP_MS end # (3) Nothing parked → nothing to fast-forward to. return POLL_TICK_STEP_MS if delay.negative? # (4) Beyond the horizon (ahoy 1000 / session-timeout / analytics): leave # parked, advance only at the fixed rate. Not a transient window. if delay > FF_HORIZON_MS @ff_transient_polls = 0 return POLL_TICK_STEP_MS end # (5) Near-future timer, page idle: hold the pre-debounce window for the # guard so transient-catch tests observe the intermediate state. @ff_transient_polls = (@ff_transient_polls || 0) + 1 return POLL_TICK_STEP_MS if @ff_transient_polls < FF_TRANSIENT_GUARD_POLLS # (6) Fast-forward: jump exactly to the next timer's due. `runLoopStepLocal` # breaks on strict `nextDue > limit`, so `limit = virtualNow + delay` # (== that timer's due) fires it — and ONLY it, not a timer 1 ms later. delay end |
#hover(handle) ⇒ Object
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 |
# File 'lib/capybara/simulated/browser.rb', line 1027 def hover(handle) mark_action_baseline tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) # Set `document._hoverElement` so `:hover` pseudo-class matches # resolve against this element (Redmine's gantt tooltips + # context-menu submenus rely on CSS `:hover`). The host fn # call into `__csimSetHover` does the slot update on the JS # side AND fires `mouseover` / `mouseenter` — keeping the # state-set and dispatch on the same path avoids the # double-eval recursion the inlined `globalThis.document. # _hoverElement = ...` triggered (the eval string ran inside # a fresh microtask that re-entered the hover listeners). @runtime.call('__csimSetHover', handle) end |
#html ⇒ Object
1298 1299 1300 1301 |
# File 'lib/capybara/simulated/browser.rb', line 1298 def html tick_real_time @runtime.call('__csimDocumentHtml').to_s end |
#inner_html(handle) ⇒ Object
575 |
# File 'lib/capybara/simulated/browser.rb', line 575 def inner_html(handle) = @runtime.call('__csimInnerHTML', handle).to_s |
#invalidate_find_cache ⇒ Object
Any operation that may have mutated the DOM (click, set, send_keys, navigate, hover, …) must call this so the next find falls through to a fresh V8 query. Timer drains that fire any callbacks also dirty (see ‘tick_real_time`).
568 569 570 |
# File 'lib/capybara/simulated/browser.rb', line 568 def invalidate_find_cache @find_cache_dirty = true end |
#location_assign(url) ⇒ Object
Defer the navigation: doing it from inside the running V8 call would dispose the Context mid-call. tick_real_time drains after the call returns. Same pattern as ‘__csimPendingFormSubmit`.
3008 3009 3010 |
# File 'lib/capybara/simulated/browser.rb', line 3008 def location_assign(url) @pending_location = resolve_against_current(url.to_s) end |
#location_reload ⇒ Object
Mirror of ‘location_assign`’s deferral for ‘location.reload()`: the JS call lands here from `__locationReload`; running `browser.refresh` directly would `navigate` (rebuilding the Context) while we’re still inside the V8 call, which V8 terminates with a ‘ScriptTerminatedError`. Stash the intent and drain it from `tick_real_time` after the call returns.
3031 |
# File 'lib/capybara/simulated/browser.rb', line 3031 def location_reload ; @pending_reload = true ; end |
#log_console(severity, message) ⇒ Object
1556 1557 1558 1559 1560 1561 1562 |
# File 'lib/capybara/simulated/browser.rb', line 1556 def log_console(severity, ) # Diagnostic mirror: surface page console output on stderr regardless # of trace state (engine bring-up / CI triage). warn "[console:#{severity}] #{.to_s[0, 300]}" if CONSOLE_STDERR return unless @trace @trace.log_console(severity, (severity, )) end |
#log_network(method, url, status) ⇒ Object
1577 |
# File 'lib/capybara/simulated/browser.rb', line 1577 def log_network(method, url, status) = @trace&.log_network(method, url, status) |
#lookup_node(handle) ⇒ Object
611 612 613 |
# File 'lib/capybara/simulated/browser.rb', line 611 def lookup_node(handle) handle if @runtime.call('__csimAlive', handle) end |
#mark_action_baseline ⇒ Object
Pin the URL the page is at as a user action BEGINS — the FIRST line of every action entry (click / double_click / right_click / hover / set / send_keys / select / unselect). A Turbo Drive Visit the action triggers is async — its pushState may fire synchronously mid-action or in a LATER find-poll tick (the test’s ‘wait_for_loaded`) — so `record_url_transition` uses this baseline to recognise the pre-action URL as the action’s starting point, not a walkable intermediate, and skip queuing it. Set at action entry (NOT the tail drain, which runs after the pushState); must precede the action’s first ‘tick_real_time` so a deferred prior-page timer firing in that tick is still measured against the pre-action URL. Persists until the next action (so the async case is covered) and is reset by `navigate` so a stale baseline can’t leak across a document boundary.
1170 1171 1172 |
# File 'lib/capybara/simulated/browser.rb', line 1170 def mark_action_baseline @action_url_baseline = @current_url end |
#marshal_args(args) ⇒ Object
Capybara passes Node instances directly as script args (‘session.evaluate_script(’arguments.click()‘, some_node)`). the marshaller can’t pass a Ruby Node, so wrap as a sentinel the JS side recognises and rehydrates via the handle registry.
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 |
# File 'lib/capybara/simulated/browser.rb', line 1656 def marshal_args(args) args.map {|a| case a when Capybara::Simulated::Node then {'__elementHandle' => a.handle_id} when Array then marshal_args(a) when Hash then a.transform_values {|v| marshal_args([v]).first } else a end } end |
#mime_type_for_path(path) ⇒ Object
158 159 160 |
# File 'lib/capybara/simulated/browser.rb', line 158 def mime_type_for_path(path) Rack::Mime.mime_type(File.extname(path.to_s), '') end |
#modifier_flags(keys) ⇒ Object
999 1000 1001 1002 1003 1004 |
# File 'lib/capybara/simulated/browser.rb', line 999 def modifier_flags(keys) Array(keys).each_with_object({}) {|k, h| field = MODIFIER_KEYS[k.is_a?(Symbol) ? k : k.to_sym] h[field] = true if field } end |
#navigate_post(url, body, content_type, depth: 0, from_history: false) ⇒ Object
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 |
# File 'lib/capybara/simulated/browser.rb', line 1944 def navigate_post(url, body, content_type, depth: 0, from_history: false) raise 'too many redirects' if depth > 10 invalidate_find_cache record_history({method: :post, url: url, body: body, content_type: content_type}) unless from_history || depth > 0 env = Rack::MockRequest.env_for(url, method: 'POST', input: body) env['CONTENT_TYPE'] = content_type.empty? ? 'application/x-www-form-urlencoded' : content_type env['CONTENT_LENGTH'] = body.bytesize.to_s apply_default_request_env(env, referer: @current_url) status, headers, resp_body = dispatch_rack_or_http(url, env, method: 'POST', body: body) (headers) if (loc = redirect_location(status, headers)) next_url = resolve_against_current(loc) resp_body.close if resp_body.respond_to?(:close) # HTTP semantics: 301/302/303 → method becomes GET; 307/308 # require the method (and body) to be preserved. if [307, 308].include?(status) return navigate_post(next_url, body, content_type, depth: depth + 1) else return navigate(next_url, depth: depth + 1) end end if download_response?(headers) save_downloaded_response(url, headers, resp_body) return end @current_url = url record_response(status, headers) html = read_rack_body(resp_body) # Same rebuild-on-full-load contract as `navigate`. POST # responses (form submissions that don't redirect, AJAX-less # data-remote replies) replace the page; we follow real-browser # semantics and bring up a fresh VM rather than papering over # the previous one's state. boot_response_into_ctx(html) end |
#node_path(handle) ⇒ Object
609 |
# File 'lib/capybara/simulated/browser.rb', line 609 def node_path(handle) = @runtime.call('__csimNodePath', handle).to_s |
#option_selected?(h) ⇒ Boolean
HTML spec: ‘<option>.selected` IDL is true when the `selected` attribute is set OR when no sibling option has `selected` and this is the first non-disabled option of a single-select `<select>` (implicit default). Capybara’s ‘have_select(selected: “Choose an option”)` filter calls `selected?` on each option; without the implicit-default branch, a select with no explicit `<option selected>` reports no selected options and the matcher fails even though the first option is the currently chosen one in real browsers.
598 |
# File 'lib/capybara/simulated/browser.rb', line 598 def option_selected?(h) = !!@runtime.call('__csimOptionSelected', h) |
#outer_html(handle) ⇒ Object
576 |
# File 'lib/capybara/simulated/browser.rb', line 576 def outer_html(handle) = @runtime.call('__csimOuterHTML', handle).to_s |
#parse_trace_mode(raw) ⇒ Object
1488 1489 1490 1491 |
# File 'lib/capybara/simulated/browser.rb', line 1488 def parse_trace_mode(raw) return :on_failure if raw.nil? || raw.empty? TRACE_MODES[raw] || raise(ArgumentError, "CSIM_TRACE must be one of #{TRACE_MODES.keys.join(', ')}; got #{raw.inspect}") end |
#polling? ⇒ Boolean
Capybara polls find / has_? via ‘synchronize` while `Driver#wait?` is true. We stay true while there’s any scheduled timer (‘@timers_active` is flipped by the JS bridge’s ‘__setTimersActive` callback), plus a sticky grace window after the last timer fires so a `setTimeout` firing mid-loop doesn’t drop us off polling before Capybara’s own retry deadline.
Settle-gen idle gate: a recurring ‘setInterval` from a framework runloop (Ember / Glimmer) keeps `@timers_active` true forever even when nothing observable is changing. Without a second signal, Capybara waits the full `default_max_wait_time` on every `has_css?` / `has_no_css?` that’s destined to fail — which Discourse’s ‘CapybaraTimeoutExtension` reports as a “slow spec” failure. Track `@runtime.settle_gen` across polls: when it hasn’t bumped for ‘IDLE_SETTLE_POLLS` calls, drop polling even though timers are scheduled. `settle_gen` already bumps on every DOM mutation / URL change (see __settleGen wiring), so this only short-circuits genuinely idle loops.
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 |
# File 'lib/capybara/simulated/browser.rb', line 1711 def polling? # Background-thread work (workers, EventSource, MessageBus # long-poll) keeps the settle loop alive even when settle_gen # is otherwise idle. return true if worker_pending? || event_source_pending? || hijack_fetch_pending? if @timers_active gen = @runtime.settle_gen if @last_polled_gen.nil? || gen != @last_polled_gen @last_polled_gen = gen @idle_settle_polls = 0 @polling_grace = POLLING_GRACE_POLLS return true end @idle_settle_polls += 1 return true if @idle_settle_polls < IDLE_SETTLE_POLLS # Treat as idle for this poll; if a fresh timer fires later # the next poll's settle_gen check will resume polling. false elsif @polling_grace && @polling_grace > 0 @polling_grace -= 1 true else false end end |
#pure_fragment_navigation?(url) ⇒ Boolean
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 |
# File 'lib/capybara/simulated/browser.rb', line 773 def (url) return true if url.start_with?('#') return false if @current_url.nil? target = resolve_against_current(url) a = URI.parse(target) b = URI.parse(@current_url) # Same-document iff everything but the fragment matches AND the # fragment actually changes — `a.fragment != b.fragment` covers # both adding/changing a fragment and *clearing* one (target has # no fragment while the current URL does, e.g. `location.hash = # ''`). The old `!a.fragment.nil?` missed the clearing case, so a # hash-reset turned into a full document reload. a.scheme == b.scheme && a.host == b.host && a.port == b.port && a.path == b.path && a.query == b.query && a.fragment != b.fragment rescue URI::InvalidURIError false end |
#push_user_agent_to_js ⇒ Object
1341 1342 1343 1344 1345 |
# File 'lib/capybara/simulated/browser.rb', line 1341 def push_user_agent_to_js ua = @default_user_agent or return return unless @runtime @runtime.eval("try { Object.defineProperty(navigator, 'userAgent', { value: #{ua.to_json}, configurable: true }); } catch (_) {}") end |
#rack_fetch(method, url, body, headers, redirect_mode, env_extras: nil) ⇒ Object
URLs we won’t even try to route through Rack: anything that isn’t http(s) (data: / mailto: / about:) plus pseudo-tokens like V8’s ‘<snapshot>` that sourcemap libraries pull out of error stacks and feed straight to `fetch()` / `xhr.open()`.
2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 |
# File 'lib/capybara/simulated/browser.rb', line 2862 def rack_fetch(method, url, body, headers, redirect_mode, env_extras: nil) target = resolve_against_current(url.to_s) return nil unless target.is_a?(String) && target.match?(%r{\Ahttps?://}i) method = (method || 'GET').to_s.upcase redirected = false # JS-side base64-encodes Blob/File bodies (raw bytes survive # the engine's UTF-8 string boundary that way); decode before # handing to Rack so the upload PUT lands intact. if headers.is_a?(Hash) && headers['X-Csim-Body-B64'].to_s == '1' body = Base64.decode64(body.to_s) headers = headers.reject {|k, _| k == 'X-Csim-Body-B64' } end MAX_FETCH_REDIRECTS.times do # GET-only cache shortcut (RFC 9111). Fresh hit → skip @app.call # entirely; stale-but-revalidatable → fall through with conditional # headers added so the server can return 304. cache_entry = method == 'GET' ? @@asset_cache.lookup(target) : nil if cache_entry&.fresh? log_network(method, target, cache_entry.status) return response_hash(cache_entry.status, cache_entry.headers, cache_entry.body, target, redirected) end env = Rack::MockRequest.env_for(target, method: method, input: body || '') apply_request_headers(env, headers) if headers apply_request_headers(env, @@asset_cache.revalidation_headers(cache_entry)) if cache_entry apply_default_request_env(env, referer: @current_url, force: false) env.merge!(env_extras) if env_extras status, resp_headers, resp_body = dispatch_rack_or_http(target, env, method: method, body: body) (resp_headers) log_network(method, target, status) if status == 304 && cache_entry resp_body.close if resp_body.respond_to?(:close) @@asset_cache.refresh(cache_entry, resp_headers) return response_hash(cache_entry.status, cache_entry.headers, cache_entry.body, target, redirected) end if redirect_mode != 'manual' && (loc = redirect_location(status, resp_headers)) raise StandardError, '[capybara-simulated] fetch: redirect blocked by redirect=error mode' if redirect_mode == 'error' redirected = true preserve = [307, 308].include?(status) next_url = resolve_against(loc, target) target = carry_fragment(target, next_url) method = 'GET' unless preserve body = nil unless preserve resp_body.close if resp_body.respond_to?(:close) next end body_str = read_rack_body(resp_body) @@asset_cache.store(target, status, resp_headers, body_str) if method == 'GET' return response_hash(status, resp_headers, body_str, target, redirected) end raise StandardError, "[capybara-simulated] fetch exceeded #{MAX_FETCH_REDIRECTS} redirects" rescue StandardError => e warn "[capybara-simulated] rack_fetch failed: #{e.class}: #{e.[0, 200]}" nil end |
#rack_fetch_async(method, url, body, headers_json) ⇒ Object
── Hijack-aware async XHR ─────────────────────────────────────
Real browsers’ long-poll keeps the request socket open across the entire user-interactive session, so a server-side ‘MessageBus.publish` (or any other middleware writing through `rack.hijack`) lands on the open connection and the client gets the response when the server is ready. Our default `__rackFetch` is purely sync — the middleware’s hijack path never engaged, so MessageBus’s ‘subscribe(channel, -1)` + `__status` reset chain dropped any publish that landed between two scheduled polls.
‘rack_fetch_async` runs the Rack call with a `rack.hijack` lambda installed. The lambda is invoked iff the middleware actually hijacks; we detect that and spawn a background thread to read from the pipe until the middleware closes its end (a publish landed via `notify_clients`, or `cleanup_timer` fired the empty-`[]` close after `long_polling_interval`). Non-hijacking responses queue immediately on the same thread — no thread spawn, no backpressure beyond the existing sync `__rackFetch` cost.
The contract is generic: any middleware that follows the Rack hijack protocol works, not just ‘message_bus`. JS-side XHR’s async path routes every request here; sync XHRs (‘xhr.open(_, _, false)`, deprecated) stay on `__rackFetch` because the hijack contract can’t satisfy a synchronous XHR response anyway. Returns either a response hash (immediate — middleware didn’t hijack) or a ‘=> N‘ token (deferred — middleware hijacked the connection and a background thread is reading the pipe). The JS-side XHR checks the return shape to pick between inline processing and waiting for `_csim deliverHijackedFetches`.
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 |
# File 'lib/capybara/simulated/browser.rb', line 2351 def rack_fetch_async(method, url, body, headers_json) headers = begin JSON.parse(headers_json.to_s) rescue JSON::ParserError {} end # `rack_fetch` already handles redirects, cookie merge, the # asset cache shortcut, and download detection — keep async # XHRs on that single source of truth. The new behaviour is # the hijack hook for long-poll-shaped requests: install # `rack.hijack` so the middleware can hold the connection # open until something publishes through it. # # We can't unconditionally install the hijack env keys: some # downstream Discourse middleware paths take a different # streaming branch when `rack.hijack?` is truthy (even # without ever invoking the lambda) and the response then # re-renders the page in a slightly different order, racing # subsequent Capybara `find`s into StaleElement. Restrict # the hook to URLs that look like the long-poll endpoints # we actually need it for (`/message-bus/{id}/poll` today; # extend as new patterns surface). read_io = nil env_extras = if HIJACK_AWARE_URL_PATTERNS.any? {|re| re.match?(url.to_s) } { 'rack.hijack?' => true, 'rack.hijack' => lambda { read_io, write_io = IO.pipe write_io } } end resp = rack_fetch(method, url, body, headers, 'follow', env_extras: env_extras) return resp || {'status' => 0, 'headers' => {}, 'body' => ''} unless read_io id = (@hijack_fetch_seq += 1) @hijack_fetch_threads[id] = Thread.new do Thread.current.report_on_exception = false run_hijacked_pipe_read(id, read_io, @hijack_fetch_queue) end {'handle' => id} end |
#rack_fetch_async_abort(id) ⇒ Object
2403 2404 2405 2406 2407 |
# File 'lib/capybara/simulated/browser.rb', line 2403 def rack_fetch_async_abort(id) thread = @hijack_fetch_threads.delete(id.to_i) thread&.kill nil end |
#rack_fetch_body(url) ⇒ Object
── Host-fn callbacks invoked by bridge.js ──────────────────
2040 2041 2042 2043 2044 |
# File 'lib/capybara/simulated/browser.rb', line 2040 def rack_fetch_body(url) result = rack_fetch('GET', url, '', {}, 'follow') return nil unless result && result['status'].to_i < 400 result['body'].to_s end |
#read_file_pick(handle, index, start = nil, finish = nil) ⇒ Object
JS-side ‘__HostBackedFile.text()` / `arrayBuffer()` route through this to read attached file bytes on demand — ActiveStorage’s ‘DirectUpload` MD5-chunks the file via FileReader before POSTing to `/rails/active_storage/direct_uploads`. Returns the requested byte range as base64 so binary content survives the engine string boundary (same approach as `__csimReadBlobBase64`).
901 902 903 904 905 906 907 908 909 910 911 912 913 914 |
# File 'lib/capybara/simulated/browser.rb', line 901 def read_file_pick(handle, index, start = nil, finish = nil) paths = file_picks_for(handle.to_i) path = paths && paths[index.to_i] return nil unless path && File.exist?(path) size = File.size(path) s = [start.to_i, 0].max e = finish.nil? ? size : [finish.to_i, size].min return Base64.strict_encode64('') if e <= s bytes = File.open(path, 'rb') do |f| f.seek(s) f.read(e - s) end Base64.strict_encode64(bytes || '') end |
#read_rack_body(body) ⇒ Object
Rack response bodies must respond to ‘each` (or be an Array of strings). `to_s` on a streaming body returns the inspect form, not the bytes — which silently shipped 43-byte `#<Rack::Files…>` strings to the JS engine for big assets like jquery.js.
2998 2999 3000 3001 3002 3003 |
# File 'lib/capybara/simulated/browser.rb', line 2998 def read_rack_body(body) buf = +'' body.each {|chunk| buf << chunk.to_s } if body.respond_to?(:each) body.close if body.respond_to?(:close) buf end |
#record_action(kind, description) ⇒ Object
Wraps a driver action so the trace records description, urls, console / network activity, and (on action error / full mode) a post-action DOM snapshot. Re-entrant: nested recorded actions (label-click → click, session send_keys → send_keys) let the outer step own the boundary and the inner just yields.
‘description` is a String or Proc — Procs are lazy-evaluated only when a step is actually being recorded, so the off-path doesn’t pay ‘describe_node_handle`’s V8 round-trip.
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 |
# File 'lib/capybara/simulated/browser.rb', line 1521 def record_action(kind, description) # Off-mode: no autostart, only proceed if a trace was started # explicitly via `driver.start_tracing`. Hot path for users # who set CSIM_TRACE=off. return yield if @trace.nil? && @trace_mode == :off if @trace.nil? @trace = Trace.new(metadata: {auto_started_at: Time.now.utc.iso8601(3)}) @runtime.call('__csimSetTraceActive', true) end return yield if @recording_action @recording_action = true desc = description.is_a?(Proc) ? description.call : description @trace.begin_step(kind, description: desc, url_before: @current_url) error = nil begin yield rescue => e error = {class: e.class.name, message: e.} raise ensure # `full` mode serializes the document after every action; the # default `on_failure` mode only snapshots when an action # errored. The V8 round-trip + DOM serialize is the # expensive part of trace recording, so skipping it on the # happy path is the whole point of the default. dom = (error || @trace_mode == :full) ? html : nil @trace.finish_step(url_after: @current_url, dom_after: dom, error: error) @recording_action = false end end |
#record_history(entry) ⇒ Object
1435 1436 1437 1438 1439 1440 1441 |
# File 'lib/capybara/simulated/browser.rb', line 1435 def record_history(entry) # Discard any forward-history tail (a real browser drops the # redo stack the moment you navigate after a `go_back`). @history = @history[0..@history_idx] if @history_idx + 1 < @history.size @history << entry.merge(kind: entry[:kind] || :visit) @history_idx = @history.size - 1 end |
#record_response(status, headers) ⇒ Object
1310 1311 1312 1313 |
# File 'lib/capybara/simulated/browser.rb', line 1310 def record_response(status, headers) @last_response_status = status @last_response_headers = headers.to_h end |
#record_url_transition(new_url) ⇒ Object
Called whenever ‘@current_url` is about to be set to a new value during a page-load drain or a settle tick driven by a user action; queues the prior URL for surface-via- `current_url` so a polling matcher walks the intermediate chain. Out-of-band JS-driven pushStates (`execute_script(“history.pushState(…)”)`) bypass the queue —they have no chain of microtask-driven transitions to walk, and the caller expects to read the new URL one-shot. Bounded to size 8 to guard against runaway chains; `current_url`’s staleness check drops the rest on any read past the polling- cadence window. Without the queue the finish_installation wizard chain’s intermediate ‘/wizard` would be invisible: the JS-side `replaceWith` to `/wizard/steps/setup` lands during a tick, so by the time Capybara polls `@current_url` is already the final URL.
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 |
# File 'lib/capybara/simulated/browser.rb', line 416 def record_url_transition(new_url) return unless @ticking || @navigating old = @current_url return if old.nil? || old.to_s.empty? return if old.to_s == new_url.to_s # The URL the action started from is the starting point, not an # intermediate it walked through — don't surface it to a polling # (or one-shot) `current_url` as a step. Genuine mid-action # intermediates (a load to /wizard, *then* a replaceState to # /wizard/steps/setup) differ from the baseline and still queue. return if @action_url_baseline && old.to_s == @action_url_baseline.to_s @recent_urls << old.to_s @recent_urls.shift while @recent_urls.size > 8 @recent_urls_last_push_at = Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond) end |
#refresh ⇒ Object
is just a re-GET. Replay the current history entry.
3044 3045 3046 |
# File 'lib/capybara/simulated/browser.rb', line 3044 def refresh replay_history_entry(@history[@history_idx]) end |
#replay_history_entry(entry) ⇒ Object
1442 1443 1444 1445 1446 1447 1448 1449 |
# File 'lib/capybara/simulated/browser.rb', line 1442 def replay_history_entry(entry) return unless entry if entry[:method] == :post navigate_post(entry[:url], entry[:body], entry[:content_type], from_history: true) else navigate(entry[:url], from_history: true) end end |
#reset! ⇒ Object
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 |
# File 'lib/capybara/simulated/browser.rb', line 1980 def reset! @cookies.clear @local_storage.clear @session_storage.clear @sticky_headers.clear # The driver-side resize buffer has to clear too — without # this the previous test's `driver.resize(425, …)` leaks into # the next test's default viewport and any cascade rule that # gates on `(min-width: …)` reports the wrong answer for the # whole new test (Forem's comment-actions dropdown is # mobile-collapsed-by-default). The exception is the # `default_viewport` channel — drivers built for a mobile # session (Discourse's `playwright_mobile_chrome`) need to # stay mobile across resets, not snap back to desktop on the # next mobile-tagged test. if @default_viewport @viewport_width = @default_viewport[0] @viewport_height = @default_viewport[1] else @viewport_width = nil @viewport_height = nil end @current_url = nil @document_handle = 0 @history.clear @history_idx = -1 @file_picks = {} if @file_picks # Hand the live trace off to `@pending_trace` so an after-hook # running after `reset_session!` (Capybara's per-test teardown # order) still finds it. Anything stuck in `@pending_trace` # from a prior test is dropped — better than fusing two # tests' actions into one record. @pending_trace = @trace @trace = nil @recording_action = false # Kill any open SSE reader threads — the new VM has no JS-side # EventSource instances to dispatch into, and the old handles # would collide on the fresh handle counter the bridge starts # from after `reset_page`. Same shape for worker threads. reset_event_sources reset_hijacked_fetches reset_workers @blob_registry_lock.synchronize { @blob_registry.clear } # Drop volatile entries from the class-level HTTP asset cache # so test-local DB state (TranslationOverride, etc.) reaches # the app on subsequent visits. Fingerprinted assets # (`Cache-Control: immutable`) survive: their URLs are content- # addressable so a stale entry can't shadow a later test. @@asset_cache.clear_volatile if @@asset_cache.respond_to?(:clear_volatile) @runtime.reset_page # Per-visit ctx rebuild drops the JS-side trace-active flag, # so re-flip it if we're carrying a pending trace into the # next visit. @runtime.call('__csimSetTraceActive', false) reset_timer_state invalidate_find_cache end |
#reset_event_sources ⇒ Object
2311 2312 2313 2314 2315 |
# File 'lib/capybara/simulated/browser.rb', line 2311 def reset_event_sources @event_source_threads.each_value(&:kill) @event_source_threads.clear @event_source_queue.clear end |
#reset_hijacked_fetches ⇒ Object
2419 2420 2421 2422 2423 |
# File 'lib/capybara/simulated/browser.rb', line 2419 def reset_hijacked_fetches @hijack_fetch_threads.each_value(&:kill) @hijack_fetch_threads.clear @hijack_fetch_queue.clear end |
#reset_timer_state ⇒ Object
Re-sync the Ruby-side timer mirror with a freshly-rebuilt JS context. Clear ‘@timers_active` and the `@polling_grace` grace window so the previous page’s pending-timer state doesn’t leak into the next test, leaving ‘Driver#wait?` true and dragging every failing matcher through the full `default_max_wait_time` retry loop.
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 |
# File 'lib/capybara/simulated/browser.rb', line 1861 def reset_timer_state @last_tick_ts = Process.clock_gettime(Process::CLOCK_MONOTONIC) @wall_clock_last = @last_tick_ts # CSIM_CLOCK_WALL escape hatch: don't replay the prev page's gap @timers_active = false @polling_grace = nil @last_polled_gen = nil @idle_settle_polls = 0 @ff_transient_polls = 0 @context_gen += 1 end |
#reset_workers ⇒ Object
2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 |
# File 'lib/capybara/simulated/browser.rb', line 2608 def reset_workers @workers.each_value do |w| w[:inbox] << :terminate w[:thread].kill end @workers.clear @worker_outbox.clear @worker_in_flight = 0 @transfer_buffer_lock.synchronize { @transfer_buffers.clear @transfer_buffer_seq = 0 } end |
#resolve_against(url, base) ⇒ Object
2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 |
# File 'lib/capybara/simulated/browser.rb', line 2835 def resolve_against(url, base) return url if url =~ %r{\A[a-z]+://}i # quickjs.rb's module_loader passes the importer for nested # relative imports; if the importer was an inline-script # pseudo-name (no scheme), fall through to the page URL. base = nil unless base.is_a?(String) && base =~ %r{\A[a-z]+://}i eff = base || @current_url || @default_host # Memo of `URI.join(eff, url)` — a pure function of (effective base, url). # A heavy ESM app re-resolves the same ~80 module specifiers against the # same base on every visit (a fresh VM re-instantiates the whole module # graph); Ruby's URI parser was a measured ~11% of per-visit wall. The # Browser persists across a suite's visits, so this instance-level memo # (same scope/threading assumptions as @importmap / @current_url) turns # all but the first visit's resolves into hash hits. cache = (@resolve_against_cache ||= {}) cache[[eff, url]] ||= begin URI.join(eff, url).to_s rescue URI::InvalidURIError, URI::BadURIError url end end |
#resolve_module_specifier(specifier, base_url) ⇒ Object
2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 |
# File 'lib/capybara/simulated/browser.rb', line 2824 def resolve_module_specifier(specifier, base_url) @importmap ||= {'imports' => {}, 'scopes' => {}} if (mapped = @importmap['imports'][specifier]) return resolve_against(mapped, base_url) end if specifier.start_with?('/', './', '../') || specifier.match?(%r{\A[a-z]+://}i) return resolve_against(specifier, base_url) end specifier end |
#resolve_visit_url(url) ⇒ Object
352 353 354 355 356 357 358 359 360 361 362 363 364 |
# File 'lib/capybara/simulated/browser.rb', line 352 def resolve_visit_url(url) s = url.to_s unless s =~ %r{\A[a-z]+://}i host_root = (begin URI.parse(@current_url) rescue nil end)&.tap {|u| u.path = ''; u.query = nil; u.fragment = nil }&.to_s || @default_host host_root = host_root.sub(/\/+$/, '') s = "/#{s}" unless s.start_with?('/') s = "#{host_root}#{s}" end # Real browsers percent-encode characters that aren't legal in their # URL position before issuing the request. Skip the escape pass when # the input is already clean (the common case). s.match?(URL_UNSAFE_CHARS) ? URI::DEFAULT_PARSER.escape(s, URL_UNSAFE_CHARS) : s end |
#response_hash(status, headers, body, url, redirected) ⇒ Object
2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 |
# File 'lib/capybara/simulated/browser.rb', line 2945 def response_hash(status, headers, body, url, redirected) raw = body.to_s hdrs = stringify(headers) is_text = text_response?(hdrs) # `body` crosses as TEXT — `responseText` semantics: the bytes decoded # as UTF-8 with invalid sequences replaced (a leading BOM selects the # encoding per the HTML "decode" algorithm and is removed). The real # bytes for binary consumers ride `body_b64`; the Rack body arrives # BINARY-tagged (see `RuntimeShared.utf8_text`). text = RuntimeShared.utf8_text(is_text ? decode_response_bom(raw) : raw) out = { 'status' => status, 'headers' => hdrs, 'body' => text, 'url' => url, 'redirected' => redirected, 'type' => 'basic' } out['body_b64'] = Base64.strict_encode64(raw) unless is_text out end |
#response_headers ⇒ Object
Rack 3 lowercases header names; Capybara tests do ‘[’Content-Type’]‘.
1305 1306 1307 1308 1309 |
# File 'lib/capybara/simulated/browser.rb', line 1305 def response_headers (@last_response_headers || {}).each_with_object({}) {|(k, v), h| h[k.to_s.split('-').map(&:capitalize).join('-')] = v } end |
#right_click(handle, keys = [], **opts) ⇒ Object
916 917 918 919 920 921 922 923 924 925 926 |
# File 'lib/capybara/simulated/browser.rb', line 916 def right_click(handle, keys = [], **opts) mark_action_baseline tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) init = {'bubbles' => true, 'cancelable' => true, 'button' => 2, 'which' => 3}.merge(click_event_init(handle, keys, opts)) @runtime.call('__csimDispatchEvent', handle, 'mousedown', init) sleep opts[:delay].to_f if opts[:delay].to_f > 0 @runtime.call('__csimDispatchEvent', handle, 'mouseup', init) @runtime.call('__csimDispatchEvent', handle, 'contextmenu', init) end |
#same_document_traversal?(from, to) ⇒ Boolean
Same-document = every entry between ‘from` and `to` (inclusive) is a `:push_state` entry (or the boundary just changed state on the current URL). A `:visit` entry between them means we’d cross a real navigation, which needs a fresh document.
1430 1431 1432 1433 |
# File 'lib/capybara/simulated/browser.rb', line 1430 def same_document_traversal?(from, to) lo, hi = [from, to].sort ((lo + 1)..hi).all? {|i| @history[i] && @history[i][:kind] == :push_state } end |
#select_option(handle) ⇒ Object
1118 1119 1120 1121 1122 1123 1124 1125 |
# File 'lib/capybara/simulated/browser.rb', line 1118 def select_option(handle) mark_action_baseline tick_real_time invalidate_find_cache @runtime.call('__csimSelectOption', handle) tick_real_time drain_after_user_action end |
#send_keys(handle, keys) ⇒ Object
Capybara’s ‘send_keys` accepts Strings and Symbols (special keys: `:enter`, `:tab`, `:backspace`, …) and Array combos (modifier + key). We hand each item to JS as a tagged atom so the bridge can fire proper KeyboardEvents with `key` / `code` / `ctrlKey` / `metaKey` / `shiftKey` filled in — required by libraries that gate behaviour on the modifier flags (Redmine’s jstoolbar reads ‘event.ctrlKey || event.metaKey` for Ctrl+B / Cmd+B; quote-reply Stimulus controllers read `event.key`). An Array combo is the canonical “modifier + key” pattern: everything but the last entry is a modifier; the last entry is the key being pressed (String char or Symbol special).
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 |
# File 'lib/capybara/simulated/browser.rb', line 1062 def send_keys(handle, keys) mark_action_baseline tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) # Selenium's contract: a bare modifier symbol (`:shift`) at the # top level "holds" the modifier from that point on. `:null` # releases all modifiers. We rewrite the atom stream so each # following character / key carries the accumulated modifiers. held = [] atoms = keys.flat_map {|k| case k when Symbol if k == :null held = []; nil elsif MODIFIER_KEY_NAMES.include?(k) held = (held + [k.to_s]).uniq; nil else held.empty? ? {'kind' => 'key', 'name' => k.to_s} : {'kind' => 'combo', 'parts' => held + [k.to_s]} end when String held.empty? ? {'kind' => 'text', 'value' => k} : {'kind' => 'combo', 'parts' => held + [k]} when Array parts = k.map {|x| x.is_a?(Symbol) ? x.to_s : x.to_s } {'kind' => 'combo', 'parts' => parts} end }.compact # Contenteditable hosts (ProseMirror, Trix, Tiptap) reconcile # their view between chars; a batched `__csimSendKeys` queues # all `beforeinput` events on the same microtask round and PM # nukes the editor wrapper when its reconciler can't apply # them in order. Split multi-char text atoms into per-char # calls with a `settle` between so PM commits each transaction # before the next char arrives. Plain `<input>` / `<textarea>` # don't need this — keep the single batched call there. has_multichar_text = atoms.any? {|a| a['kind'] == 'text' && a['value'].to_s.length > 1 } if has_multichar_text && @runtime.call('__csimIsContentEditable', handle) per_char = atoms.flat_map {|a| next a unless a['kind'] == 'text' && a['value'].to_s.length > 1 a['value'].to_s.each_char.map {|c| {'kind' => 'text', 'value' => c} } } head, *tail = per_char @runtime.call('__csimSendKeys', handle, [head]) tail.each {|atom| tick_real_time @runtime.call('__csimSendKeys', handle, [atom]) settle } else @runtime.call('__csimSendKeys', handle, atoms) end drain_after_user_action end |
#send_session_key(key) ⇒ Object
1482 |
# File 'lib/capybara/simulated/browser.rb', line 1482 def send_session_key(key) = send_session_keys([key]) |
#send_session_keys(keys) ⇒ Object
Session-level keystroke. Tab / shift-tab cycle focus; everything else is routed to the currently focused element (if any) as a plain keydown/keyup pair.
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 |
# File 'lib/capybara/simulated/browser.rb', line 1458 def send_session_keys(keys) # Walk the key list with running modifier state so a Selenium- # style `(:shift, :enter)` invocation reaches `Browser#send_keys` # as one combo atom (shift held over enter), while independent # non-modifier keys stay separate calls — each one settles # between dispatches so a dropdown highlight (Avo Tags input's # arrow navigation) commits before the next key fires. Tab / # backtab are focus-advance, dispatched out of band. held = [] Array(keys).each do |k| sym = k.is_a?(Symbol) ? k : (k.respond_to?(:to_sym) ? k.to_sym : nil) if sym == :tab || sym == :backtab @runtime.call('__csimAdvanceFocus', sym == :backtab) elsif sym && MODIFIER_KEY_NAMES.include?(sym) held << sym else handle = active_element_handle handle = @document_handle if handle.nil? || handle.zero? atom = held.empty? ? k : (held + [k]) send_keys(handle, [atom]) end end end |
#set_geolocation(latitude: nil, longitude: nil, accuracy: 10, denied: false, **rest) ⇒ Object
CDP-ish shim: override navigator.geolocation (like CDP’s ‘Emulation.setGeolocationOverride`). State is Ruby-backed on `@geolocation`; the JS geolocation object reads it on every call via the `__csimGeolocationState` host fn, so it survives the per-call VM rebuilds (the same model web storage uses).
set_geolocation(latitude: 35.6, longitude: 139.7)
set_geolocation(latitude: 1, longitude: 2, accuracy: 5, altitude: 10)
set_geolocation(denied: true) # report PERMISSION_DENIED
set_geolocation # clear -> report POSITION_UNAVAILABLE
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 |
# File 'lib/capybara/simulated/browser.rb', line 1627 def set_geolocation(latitude: nil, longitude: nil, accuracy: 10, denied: false, **rest) @geolocation = if denied {'denied' => true} elsif latitude.nil? || longitude.nil? nil else {'coords' => {'latitude' => latitude, 'longitude' => longitude, 'accuracy' => accuracy}.merge(rest.transform_keys(&:to_s))} end # Re-deliver to any active watchPosition watchers, mirroring a real # browser firing the watch again when the location updates. The JS # side reads the fresh @geolocation via the host fn. execute_script('if (typeof globalThis.__csimGeoRefireWatches === "function") globalThis.__csimGeoRefireWatches();') nil end |
#set_header(name, value) ⇒ Object
1315 |
# File 'lib/capybara/simulated/browser.rb', line 1315 def set_header(name, value) ; @sticky_headers[name.to_s] = value.to_s ; end |
#set_importmap(json) ⇒ Object
JS-side ‘ingestImportmaps` calls this through the host fn so Ruby-side `resolve_module_specifier` agrees with the bare- specifier map shipped by `<script type=“importmap”>`.
2818 2819 2820 2821 2822 |
# File 'lib/capybara/simulated/browser.rb', line 2818 def set_importmap(json) @importmap = JSON.parse(json.to_s) rescue JSON::ParserError @importmap = {'imports' => {}, 'scopes' => {}} end |
#set_value_with_events(handle, value) ⇒ Object
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 |
# File 'lib/capybara/simulated/browser.rb', line 806 def set_value_with_events(handle, value) mark_action_baseline tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) # `attach_file` hands us a Pathname (or Array of Pathnames); # the marshaller rejects non-primitive types. Coerce to a path-list # form V8 can hold — the actual multipart upload happens later # in `build_multipart_body` during form submission. coerced = coerce_set_value(value) # For date/time-shaped inputs we need the type-specific # string. Probe the handle's `type` and re-format Date / Time # accordingly — `Date.today` → `2026-05-13` (date input) is # already right via to_s, but `Time` needs the input-type- # specific format. coerced = format_temporal_value(value, handle) if value.is_a?(Date) || value.is_a?(Time) @file_picks ||= {} # Capybara `attach_file` calls `Node#set` with a Pathname; some # callers pass a String path through directly. When the target # IS a file input, promote either form into the file-list path # so `.files` / `@file_picks` reflect the chosen file. coerced = [coerced.to_s] if value.is_a?(Pathname) if !coerced.is_a?(Array) && coerced.is_a?(String) && file_input?(handle) coerced = [coerced] end if coerced.is_a?(Array) paths = coerced.reject(&:empty?) @file_picks[handle] = paths # Expose File-list metadata to the JS side BEFORE setting the # value: __csimSetValue fires input + change synchronously, # and Redmine's onchange="addInputFiles(this)" reads # `inputEl.files` — if we set files after, the handler sees # an empty FileList and tears down the input. file_infos = paths.map {|p| stat = (File.stat(p) rescue nil) { 'name' => File.basename(p), 'size' => stat ? stat.size : 0, # Real browsers tag the File with the MIME type they # sniffed from the path / disk header. Uppy's image-type # filter rejects files whose `type` is empty, so without # this even a `logo.png` `attach_file` finishes uploading # 0 bytes through the validator and the composer's # `#file-uploading` flag stays set forever. Use the OS's # extension-based guess (matches what selenium / Chromium # do on these paths) and fall back to empty when the # extension is unknown. 'type' => mime_type_for_path(p), 'lastModified' => stat ? (stat.mtime.to_f * 1000).to_i : 0 } } @runtime.call('__csimSetFiles', handle, file_infos) # Mirror real browser: <input type=file>.value reflects only # the filename of the first chosen file (security-faked path). # __csimSetValue dispatches input + change synchronously. js_value = paths.first ? File.basename(paths.first) : '' @runtime.call('__csimSetValue', handle, js_value) else @runtime.call('__csimSetValue', handle, coerced) end drain_after_user_action end |
#set_viewport(w, h) ⇒ Object
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 |
# File 'lib/capybara/simulated/browser.rb', line 1347 def (w, h) @viewport_width = w.to_i @viewport_height = h.to_i invalidate_find_cache @runtime.eval("globalThis.innerWidth = #{@viewport_width}; globalThis.innerHeight = #{@viewport_height};") # Recompute the cascade `@media` rules against the new # viewport so visibility checks (Capybara `visible?`, # `getComputedStyle().display`) re-reflect mobile-breakpoint # `display: none` / `display: block` flips. Without this the # cascade keeps the pre-resize hide-rule set. @runtime.call('__csimRebuildCascade') if @document_handle.to_i > 0 # Fire `change` events on every live MediaQueryList whose # match state flipped, so libraries that hold `matchMedia(...)` # listeners (Discourse's `TrackedMediaQuery` powering the # viewport-based mobile/desktop class swap) reactively # re-render. The JS-side function iterates `_activeQueries` # and dispatches only on transitions — cheap no-op when no # query is open. @runtime.call('__csimViewportChanged') if @document_handle.to_i > 0 # Re-fire a `resize` event so libraries that re-layout on # resize (responsive nav, sidebar collapse) see the new size. @runtime.eval("try { (globalThis.dispatchEvent || function(){})(new Event('resize')); } catch (_) {}") nil end |
#settle ⇒ Object
Yield on the first observable change. Each iter (a) drains the chained-await/‘.then` microtask queue a few rounds, (b) checks the JS-side `__settleGen` counter — bumped on every DOM mutation / URL change — and bails if it ticked, otherwise © advances the virtual clock to fire rAF / setTimeout that the chain is parked on. Capybara’s outer polling loop drives the next iter on the next find / has_? — matching real browsers’ “one paint = one observable moment” semantics.
This makes a user-action settle as cheap as ~4 evals when the click immediately mutates DOM, and lets ‘wait_for_*` helpers catch transient states like “modal removed before the redirect_to Visit’s render rebuilds it” — exactly the window real browsers paint at.
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 |
# File 'lib/capybara/simulated/browser.rb', line 1204 def settle start_gen = @runtime.settle_gen prev_gen = start_gen SETTLE_MAX_ITER.times do deliver_event_source_events deliver_hijacked_fetches break if @runtime.settle_gen > start_gen break unless @timers_active || event_source_pending? || worker_pending? || hijack_fetch_pending? # ONE event-loop step replaces the old drain_microtasks(4)+drain_timers(32) # pair: it fires due timers, runs a per-task microtask checkpoint (so # chained .then / MutationObserver delivery interleave spec-correctly), # and runs the render phase — bailing INTERNALLY on the first settleGen # bump (yield_on_gen), which preserves the one-observable-boundary-per-poll # contract. maxMs 0 when no timer is active just flushes microtasks + # render for the work the deliveries above queued. @runtime.run_loop_step(@timers_active ? SETTLE_DRAIN_MS : 0, SETTLE_MAX_ITER_TASKS, yield_on_gen: true) deliver_event_source_events deliver_hijacked_fetches break if @runtime.settle_gen > start_gen # No progress this iter (no DOM/URL change observed) — the # remaining timers are queued for the future; bail and let # Capybara's wall-clock-driven poll loop drive the next tick # via `tick_real_time`. SSE / Worker channels keep us in # the loop as long as background threads have data queued. break if @runtime.settle_gen == prev_gen && !@runtime.has_ready_timer? && !event_source_pending? && !worker_pending? && !hijack_fetch_pending? prev_gen = @runtime.settle_gen end @find_cache_dirty = true end |
#shadow_root_handle(handle) ⇒ Object
599 600 601 602 |
# File 'lib/capybara/simulated/browser.rb', line 599 def shadow_root_handle(handle) h = @runtime.call('__csimShadowRoot', handle).to_i h.zero? ? nil : h end |
#stack_resolver ⇒ Object
1573 1574 1575 |
# File 'lib/capybara/simulated/browser.rb', line 1573 def stack_resolver @stack_resolver ||= StackResolver.new(self) end |
#start_trace(metadata = {}) ⇒ Object
1493 1494 1495 1496 |
# File 'lib/capybara/simulated/browser.rb', line 1493 def start_trace( = {}) @trace = Trace.new(metadata: ) @runtime.call('__csimSetTraceActive', true) end |
#status_code ⇒ Object
1303 1304 |
# File 'lib/capybara/simulated/browser.rb', line 1303 def status_code = (@last_response_status || 200) # Rack 3 lowercases header names; Capybara tests do `['Content-Type']`. |
#storage_clear(kind) ⇒ Object
3127 3128 3129 3130 |
# File 'lib/capybara/simulated/browser.rb', line 3127 def storage_clear(kind) store(kind).clear nil end |
#storage_get(kind, key) ⇒ Object
Web Storage host-fn shims. The Ruby-side hashes survive ‘rebuild_ctx` between visits, so apps that cache user data in `localStorage` on page A (Forem’s ‘browserStoreCache(’set’)‘ inside fetchBaseData) see it on page B — without this, every visit boots into a JS-side Map that starts empty and the first-call branches that hinge on cached user data (the onboarding task-card render, `initializeLocalStorageRender`, etc.) silently skip.
3116 3117 3118 |
# File 'lib/capybara/simulated/browser.rb', line 3116 def storage_get(kind, key) store(kind)[key.to_s] end |
#storage_key(kind, index) ⇒ Object
3131 3132 3133 |
# File 'lib/capybara/simulated/browser.rb', line 3131 def storage_key(kind, index) store(kind).keys[index.to_i] end |
#storage_length(kind) ⇒ Object
3134 3135 3136 |
# File 'lib/capybara/simulated/browser.rb', line 3134 def storage_length(kind) store(kind).size end |
#storage_remove(kind, key) ⇒ Object
3123 3124 3125 3126 |
# File 'lib/capybara/simulated/browser.rb', line 3123 def storage_remove(kind, key) store(kind).delete(key.to_s) nil end |
#storage_set(kind, key, value) ⇒ Object
3119 3120 3121 3122 |
# File 'lib/capybara/simulated/browser.rb', line 3119 def storage_set(kind, key, value) store(kind)[key.to_s] = value.to_s nil end |
#submit_form(handle) ⇒ Object
‘Node#submit(*)` (Capybara DSL) hits here. Find the enclosing form, serialise, post.
1285 1286 1287 1288 1289 1290 1291 |
# File 'lib/capybara/simulated/browser.rb', line 1285 def submit_form(handle) tick_real_time invalidate_find_cache form_handle = @runtime.call('__csimAncestorForm', handle).to_i return if form_handle.zero? submit_form_handle(form_handle, nil) end |
#submit_form_handle(form_handle, submitter_handle) ⇒ Object
Pulls the serialised form-state out of JS, encodes it, and drives the Rack app via ‘navigate` (for GET) or a POST.
1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 |
# File 'lib/capybara/simulated/browser.rb', line 1876 def submit_form_handle(form_handle, submitter_handle) invalidate_find_cache spec = @runtime.call('__csimFormSerialize', form_handle, submitter_handle || 0) return unless spec.is_a?(Hash) action = spec['action'].to_s method = spec['method'].to_s.upcase method = 'GET' if method.empty? fields = (spec['fields'] || []).map {|pair| [pair[0].to_s, pair[1].to_s] } file_inputs = spec['fileInputs'] || [] enctype = spec['enctype'].to_s multipart = enctype.start_with?('multipart/form-data') content_type = nil body = if multipart built = build_multipart_body(fields, file_inputs) content_type = built[:content_type] built[:body] else # Non-multipart: file inputs contribute the filename only. file_inputs.each do |fi| picks = @file_picks && @file_picks[fi['handle'].to_i] || [] fields << [fi['name'].to_s, picks.first ? File.basename(picks.first) : ''] end URI.encode_www_form(fields) end action_url = action.empty? ? (@current_url || @default_host) : resolve_against_current(action) if method == 'GET' uri = URI.parse(action_url) uri.query = body unless body.empty? navigate(uri.to_s) else navigate_post(action_url, body, content_type || enctype) end end |
#syntax_or_invalid_selector_error?(e) ⇒ Boolean
JS-side selector parser throws a ‘DOMException(’csim: …‘, ’SyntaxError’)‘. The JS engine surfaces it as a `…::SyntaxError` (QuickJS via dynamic-named class) or, under V8, a `RustyRacer::RuntimeError` whose message is `“SyntaxError: csim: …”`. Match the `csim: ` marker anywhere in the message (it’s no longer at the start once the DOMException name is prefixed) or the class suffix, so neither gem becomes a hard dependency.
463 464 465 466 |
# File 'lib/capybara/simulated/browser.rb', line 463 def syntax_or_invalid_selector_error?(e) e.class.name.to_s.end_with?('::SyntaxError') || e..to_s.include?('csim: ') end |
#tag(handle) ⇒ Object
573 |
# File 'lib/capybara/simulated/browser.rb', line 573 def tag(handle) = @runtime.call('__csimTag', handle).to_s |
#tag_name(handle) ⇒ Object
586 |
# File 'lib/capybara/simulated/browser.rb', line 586 def tag_name(handle) = tag(handle) |
#text(handle) ⇒ Object
572 |
# File 'lib/capybara/simulated/browser.rb', line 572 def text(handle) = @runtime.call('__csimText', handle).to_s |
#text_response?(headers) ⇒ Boolean
2988 2989 2990 2991 2992 |
# File 'lib/capybara/simulated/browser.rb', line 2988 def text_response?(headers) ct = (headers['content-type'] || headers['Content-Type']).to_s.downcase return false if ct.empty? TEXT_CONTENT_TYPE_PREFIXES.any? {|p| ct.start_with?(p) } end |
#tick_real_time(step_ms: nil) ⇒ Object
Advance the virtual JS clock and fire timers that came due. When ‘step_ms` is omitted, advance by `horizon_fast_forward_step` — a DETERMINISTIC step (never wall-derived, so per-poll JS/Ruby/GC cost can’t shift when a timer fires): a fixed ‘POLL_TICK_STEP_MS` per poll, fast- forwarding straight to a near-future timer when the page is otherwise idle. Explicit `step_ms` is used by `SleepHook#advance_virtual_clock_ms` (from `Kernel#sleep`) and by `Playwright::Page#wait_for_timeout` to step a precise virtual duration.
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 |
# File 'lib/capybara/simulated/browser.rb', line 1745 def tick_real_time(step_ms: nil) return unless @timers_active || worker_pending? || event_source_pending? || hijack_fetch_pending? # Re-entrancy guard. Capybara's `Result#each` triggers nested # finds (visible? per element); the outermost tick has already # advanced the clock, the inner calls would only re-drain # already-fired timers. return if @ticking @ticking = true begin now = Process.clock_gettime(Process::CLOCK_MONOTONIC) # Kept wall-anchored ONLY for `timer_wait_elapsed?` / FIND_PRE_TICK_MIN_S # (gates tick FREQUENCY for the smoke first-find-no-fire contract); the # step SIZE below is deterministic. @last_tick_ts = now effective_step = step_ms || horizon_fast_forward_step if @timers_active && effective_step > 0 r = @runtime.run_loop_step(effective_step) # `dirtied` (settleGen changed) catches a render-phase rAF / microtask- # delivered MutationObserver that mutated the DOM without firing a timer # (fired == 0) — a fired-count-only test would leave a stale find cache. @find_cache_dirty = true if r['dirtied'] || r['fired'].to_i > 0 end # Pull any pending Worker / EventSource messages into JS # state. Without this, `evaluate_script` after kicking off # a worker round-trip would see stale state — the inbox # outbox only drains during `settle`, which doesn't run # for direct `execute_script` / `evaluate_script` calls. @find_cache_dirty = true if > 0 @find_cache_dirty = true if deliver_event_source_events > 0 @find_cache_dirty = true if deliver_hijacked_fetches > 0 ensure @ticking = false end # Drain navigation intents queued by JS-side handlers that fired # during the drain (e.g. `setTimeout(() => location.pathname = X)`). # Outside the @ticking guard so the navigate's rebuild_ctx is # well-clear of the V8 call we just made. # Same shape for `form.submit()` queued by a timer callback — # Forem's comment-edit form has an `onsubmit` handler that # `preventDefault`s, polls for the CSRF meta tag inside # `setInterval(…, 1)`, then calls `form.submit()` once the # meta is present. The click that originally fired the submit # event has already returned by the time the interval triggers, # so without this drain the intent sits on the slot forever # and the form never posts. consume_pending_form_submit # And for `<a download>` clicks (Avo's action-download chain # goes via file-saver's `saveAs` → synthetic dispatchEvent # on a freshly-created anchor with `download` + blob URL). consume_pending_download end |
#timer_wait_elapsed? ⇒ Boolean
523 524 525 526 |
# File 'lib/capybara/simulated/browser.rb', line 523 def timer_wait_elapsed? @timers_active && (Process.clock_gettime(Process::CLOCK_MONOTONIC) - @last_tick_ts) >= FIND_PRE_TICK_MIN_S end |
#title ⇒ Object
1293 1294 1295 1296 |
# File 'lib/capybara/simulated/browser.rb', line 1293 def title tick_real_time @runtime.call('__csimDocumentTitle').to_s end |
#transfer_buffer_fetch(id) ⇒ Object
2653 2654 2655 |
# File 'lib/capybara/simulated/browser.rb', line 2653 def transfer_buffer_fetch(id) @transfer_buffer_lock.synchronize { @transfer_buffers.delete(id.to_i) } end |
#transfer_buffer_fetch_for_js(id) ⇒ Object
Wraps the raw bytes in whatever binary shape the ACTIVE runtime can marshal to a JS Uint8Array (V8: the BINARY-tagged string itself —tag-driven marshalling crosses it as a Uint8Array; QuickJS: base64 that the JS shim’s ‘fetchedToBytes` atob’s — it has no binary marshaller). Asked of the runtime so each engine picks its shape.
2662 2663 2664 2665 2666 |
# File 'lib/capybara/simulated/browser.rb', line 2662 def transfer_buffer_fetch_for_js(id) bytes = transfer_buffer_fetch(id) return nil unless bytes @runtime.wrap_binary(bytes) end |
#transfer_buffer_stash(bytes) ⇒ Object
── postMessage transferable-buffer registry ───────────────────
Large Uint8Array / ArrayBuffer payloads cross isolates by ID; rusty_racer marshals typed arrays as ASCII-8BIT Strings so no JS-side latin-1 / base64 intermediate is built. Without this the 317 MB raw frames in Discourse’s media-optimization-worker peak >4 GB of JS strings before the worker even sees them.
2643 2644 2645 2646 2647 2648 2649 2650 2651 |
# File 'lib/capybara/simulated/browser.rb', line 2643 def transfer_buffer_stash(bytes) s = bytes.to_s s = s.dup.force_encoding(Encoding::ASCII_8BIT) unless s.encoding == Encoding::ASCII_8BIT @transfer_buffer_lock.synchronize { id = (@transfer_buffer_seq += 1) @transfer_buffers[id] = s id } end |
#unselect_option(handle) ⇒ Object
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 |
# File 'lib/capybara/simulated/browser.rb', line 1127 def unselect_option(handle) mark_action_baseline tick_real_time invalidate_find_cache # Single-select <select>s can't have a selection cleared per # HTML — Capybara surfaces this as `UnselectNotAllowed`. Ask # the JS side whether the option's parent select is `multiple` # before issuing the unselect; the answer doubles as the # "found the right ancestor" check. info = @runtime.call('__csimOptionContext', handle) if info.is_a?(Hash) && info['hasSelect'] && !info['multiple'] raise Capybara::UnselectNotAllowed, 'Cannot unselect option from single select box.' end @runtime.call('__csimUnselectOption', handle) tick_real_time drain_after_user_action end |
#update_current_hash(url) ⇒ Object
791 792 793 794 795 796 797 798 799 800 801 802 803 804 |
# File 'lib/capybara/simulated/browser.rb', line 791 def update_current_hash(url) return if @current_url.nil? new_url = resolve_against_current(url) @current_url = new_url # JS-driven same-document fragment navigations (anchor clicks AND # `location.hash`/`href`/`assign` sets) are now handled entirely in # the VM by `tryFragmentNavigate` — they update the JS location and # fire `hashchange` there and never round-trip through here. This # path remains only as a defensive fallback for a fragment URL that # reaches the Ruby navigate/pending drain by some other route; keep # the VM's location object in sync so its `location.href` getter # doesn't read stale. @runtime.call('__csimUpdateLocation', new_url) if @runtime.respond_to?(:call) end |
#value(handle) ⇒ Object
587 |
# File 'lib/capybara/simulated/browser.rb', line 587 def value(handle) = @runtime.call('__csimValue', handle) |
#viewport_height ⇒ Object
1372 |
# File 'lib/capybara/simulated/browser.rb', line 1372 def ; @viewport_height || 768 ; end |
#viewport_width ⇒ Object
1371 |
# File 'lib/capybara/simulated/browser.rb', line 1371 def ; @viewport_width || 1024 ; end |
#visible?(handle) ⇒ Boolean
580 |
# File 'lib/capybara/simulated/browser.rb', line 580 def visible?(handle) = @runtime.call('__csimVisible', handle) ? true : false |
#visible_text(handle) ⇒ Object
585 |
# File 'lib/capybara/simulated/browser.rb', line 585 def visible_text(handle) = @runtime.call('__csimVisibleText', handle).to_s |
#visit(url) ⇒ Object
Address-bar navigation: no Referer, and relative paths resolve against the host root (not the current page’s directory).
345 346 347 |
# File 'lib/capybara/simulated/browser.rb', line 345 def visit(url) navigate(resolve_visit_url(url), referer: nil) end |
#webauthn ⇒ Object
2749 |
# File 'lib/capybara/simulated/browser.rb', line 2749 def webauthn = (@webauthn ||= WebauthnState.new) |
#with_modal(handler) ⇒ Object
Push a one-shot handler onto the modal-dialog stack — the next modal that fires consumes the topmost handler. Block exit pops in case the dialog never fired.
3143 3144 3145 3146 3147 3148 |
# File 'lib/capybara/simulated/browser.rb', line 3143 def with_modal(handler) @modal_handlers.push(handler) yield if block_given? ensure @modal_handlers.delete(handler) end |
#worker_pending? ⇒ Boolean
2560 |
# File 'lib/capybara/simulated/browser.rb', line 2560 def worker_pending? = !@worker_outbox.empty? || @worker_in_flight > 0 |
#worker_post_to_worker(handle, data) ⇒ Object
2528 2529 2530 2531 2532 2533 |
# File 'lib/capybara/simulated/browser.rb', line 2528 def worker_post_to_worker(handle, data) w = @workers[handle.to_i] return unless w @worker_in_flight += 1 w[:inbox] << data.to_s end |
#worker_spawn(url) ⇒ Object
── Web Workers ────────────────────────────────────────────────
‘new Worker(url)` in JS lands in `worker_spawn`. The Ruby thread it spawns owns a fresh V8 Context / QuickJS VM (true isolate, separate microtask queue and timer table), evals the worker script there, and runs an event loop draining timers, microtasks, and the inbox queue from the main thread. Each worker’s ‘__csim_workerPostMessage` host fn closes over its handle and routes outgoing messages onto a shared outbox the main settle drains.
2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 |
# File 'lib/capybara/simulated/browser.rb', line 2508 def worker_spawn(url) handle = (@worker_seq += 1) inbox = Thread::Queue.new outbox = @worker_outbox engine_class = @runtime.class target = resolve_against_current(url.to_s) # Resolve the worker script body on the main thread before # handing off to the worker. `blob:` URLs need the main VM's # blob registry; calling into the main runtime from a # non-owning thread SEGVs (V8 isolates are thread- # bound; quickjs.rb's VM is similarly per-thread). body = fetch_worker_script(target) thread = Thread.new do Thread.current.report_on_exception = false run_worker(handle, target, body, inbox, outbox, engine_class) end @workers[handle] = {thread: thread, inbox: inbox} handle end |
#worker_terminate(handle) ⇒ Object
2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 |
# File 'lib/capybara/simulated/browser.rb', line 2535 def worker_terminate(handle) w = @workers.delete(handle.to_i) return unless w w[:inbox] << :terminate # Most clean shutdowns are <10 ms; the kill is the fallback # for blocked workers. w[:thread].join(WORKER_TERMINATE_GRACE) w[:thread].kill if w[:thread].alive? # A blocked worker that never returned messages leaves # `@worker_in_flight` permanently > 0; reset when no workers # remain so `polling?` can short-circuit again. @worker_in_flight = 0 if @workers.empty? end |
#write_document_cookie(s) ⇒ Object
3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 |
# File 'lib/capybara/simulated/browser.rb', line 3095 def (s) return if s.nil? || s.empty? name, rest = s.split('=', 2) return if name.nil? || name.empty? parts = (rest || '').split(';').map(&:strip) value = parts.shift.to_s if (parts) @cookies.delete(name.strip) else @cookies[name.strip] = value end end |
#xpath_shaped?(s) ⇒ Boolean
468 469 470 471 472 473 474 475 476 |
# File 'lib/capybara/simulated/browser.rb', line 468 def xpath_shaped?(s) # Cheap probe: anything starting with `/` (absolute or relative # XPath), `(` (grouped XPath like `(//a)[1]`), or `./` / # `..` (XPath current-node + step) is XPath. We can't treat a # bare leading `.` as XPath because CSS class selectors look # exactly like that (`.contextual`); only the `./` form is # unambiguous. !!(s =~ %r{\A\s*(?:/|\(\s*/|\./|\.\.)}) end |