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.
-
#current_realm_id ⇒ Object
readonly
Returns the value of attribute current_realm_id.
-
#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.
-
#window_handle ⇒ Object
The Driver’s handle for the window this Browser backs (set right after construction).
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.
- #close_child_window(handle) ⇒ Object
- #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_browsing_context_url ⇒ Object
The active browsing context’s own URL: the frame document’s URL inside a ‘within_frame` block, else the main page URL.
-
#current_document_handle ⇒ Object
Root for a context-less find: the active frame’s document (handle 0 ⇒ the realm’s own ‘globalThis.document`) when in a frame, else the main document handle.
- #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_window_messages ⇒ Object
Fire queued cross-window messages as ‘message` events on window.
- #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`).
-
#dom_call(name, *args) ⇒ Object
DOM / node / query host-fn dispatch.
- #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
-
#enqueue_window_message(data, origin, source_handle) ⇒ Object
Queue a cross-window message for delivery into THIS window’s VM (called by the Driver on the target Browser).
-
#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
-
#frame_self_target?(target) ⇒ Boolean
Does a link/form ‘target` load into the CURRENT frame? Empty or `_self` do; `_top` / `_blank` / `_parent` / a named context do not.
-
#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
‘page.html` inside a `within_frame` block returns the frame document’s source (Selenium parity), so route through the active realm.
-
#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
-
#open_child_window(url, name) ⇒ Object
‘window.open(url, name)` from JS — returns the new (or reused, by name) window’s handle, or nil.
- #opener_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.
-
#post_message_to_window(target_handle, data, origin) ⇒ Object
‘targetWindow.postMessage(data, origin)` — route to the target window’s inbox, tagged with this window as the source.
- #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_frame_scope ⇒ Object
Return DOM-op routing to the main document and drop any frame stack.
- #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_document_url(url) ⇒ Object
Public entry for the Driver to resolve a ‘window.open` / cross-window `location` URL against THIS window’s document (the internal resolver is private).
- #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
- #set_window_location(handle, url) ⇒ 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.
-
#switch_to_frame(target) ⇒ Object
Capybara ‘switch_to_frame`.
-
#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
- #window_closed?(handle) ⇒ Boolean
- #window_location_of(handle) ⇒ Object
- #window_message_pending? ⇒ Boolean
-
#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.
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 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 |
# File 'lib/capybara/simulated/browser.rb', line 167 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 # `within_frame` state. `@current_realm_id` is the V8 context id of the # active frame realm (nil = the main document); `@frame_stack` records # the enclosing realms so `switch_to_frame(:parent)` can pop one level. # DOM / node / query ops route through `dom_call`, which dispatches to # this realm. nil is the steady state, so the routing is one nil-check. @current_realm_id = nil @frame_stack = [] @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 # Cross-window `postMessage` inbox. Another window's `target.postMessage` # routes through the Driver and lands here; this window drains it into a # `message` event the next time it's active and settles/ticks. Plain # array (same thread — windows aren't background-threaded like workers). @window_inbox = [] end |
Instance Attribute Details
#context_gen ⇒ Object (readonly)
Returns the value of attribute context_gen.
2047 2048 2049 |
# File 'lib/capybara/simulated/browser.rb', line 2047 def context_gen @context_gen end |
#current_realm_id ⇒ Object (readonly)
Returns the value of attribute current_realm_id.
469 470 471 |
# File 'lib/capybara/simulated/browser.rb', line 469 def current_realm_id @current_realm_id 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.
1498 1499 1500 |
# File 'lib/capybara/simulated/browser.rb', line 1498 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.
1498 1499 1500 |
# File 'lib/capybara/simulated/browser.rb', line 1498 def @default_viewport end |
#pending_trace ⇒ Object (readonly)
Returns the value of attribute pending_trace.
1652 1653 1654 |
# File 'lib/capybara/simulated/browser.rb', line 1652 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.
1652 1653 1654 |
# File 'lib/capybara/simulated/browser.rb', line 1652 def trace @trace end |
#trace_mode ⇒ Object (readonly)
Returns the value of attribute trace_mode.
1652 1653 1654 |
# File 'lib/capybara/simulated/browser.rb', line 1652 def trace_mode @trace_mode end |
#window_handle ⇒ Object
The Driver’s handle for the window this Browser backs (set right after construction). Lets host fns name the source window of a cross-window ‘postMessage` / `window.open` so the Driver can route to the target.
59 60 61 |
# File 'lib/capybara/simulated/browser.rb', line 59 def window_handle @window_handle 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
158 159 160 161 |
# File 'lib/capybara/simulated/browser.rb', line 158 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
1619 1620 1621 1622 1623 |
# File 'lib/capybara/simulated/browser.rb', line 1619 def active_element_handle tick_real_time h = dom_call('__csimActiveElement').to_i h.zero? ? nil : h end |
#advance_virtual_clock_ms(ms) ⇒ Object
2025 2026 2027 2028 |
# File 'lib/capybara/simulated/browser.rb', line 2025 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.
738 |
# File 'lib/capybara/simulated/browser.rb', line 738 def all_text(handle) = text(handle) |
#annotate_console_message(severity, message) ⇒ Object
1736 1737 1738 1739 1740 |
# File 'lib/capybara/simulated/browser.rb', line 1736 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
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 |
# File 'lib/capybara/simulated/browser.rb', line 2113 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.
3154 3155 3156 3157 3158 3159 3160 3161 3162 |
# File 'lib/capybara/simulated/browser.rb', line 3154 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.
691 692 693 |
# File 'lib/capybara/simulated/browser.rb', line 691 def async_io_pending? worker_pending? || event_source_pending? || hijack_fetch_pending? || end |
#attr(handle, name) ⇒ Object
728 |
# File 'lib/capybara/simulated/browser.rb', line 728 def attr(handle, name) = dom_call('__csimAttr', handle, name.to_s) |
#blob_register(url, body_b64) ⇒ Object
2851 2852 2853 2854 |
# File 'lib/capybara/simulated/browser.rb', line 2851 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
2856 2857 2858 |
# File 'lib/capybara/simulated/browser.rb', line 2856 def blob_resolve(url) @blob_registry_lock.synchronize { @blob_registry[url.to_s] } end |
#blob_unregister(url) ⇒ Object
2860 2861 2862 2863 |
# File 'lib/capybara/simulated/browser.rb', line 2860 def blob_unregister(url) @blob_registry_lock.synchronize { @blob_registry.delete(url.to_s) } nil end |
#build_multipart_body(fields, file_inputs) ⇒ Object
2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 |
# File 'lib/capybara/simulated/browser.rb', line 2091 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
330 331 332 333 334 335 336 337 338 339 340 341 342 |
# File 'lib/capybara/simulated/browser.rb', line 330 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.
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 |
# File 'lib/capybara/simulated/browser.rb', line 702 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
769 770 771 772 773 774 775 776 |
# File 'lib/capybara/simulated/browser.rb', line 769 def check_stale(handle, initial, gen = nil) return if initial && (gen.nil? || gen == @context_gen) && dom_call('__csimAlive', handle) tick_real_time return if initial && (gen.nil? || gen == @context_gen) && dom_call('__csimAlive', handle) raise Capybara::Simulated::StaleElement, "Element with handle #{handle} is no longer attached to the document" end |
#clear_trace! ⇒ Object
1675 1676 1677 1678 1679 |
# File 'lib/capybara/simulated/browser.rb', line 1675 def clear_trace! @trace = nil @pending_trace = nil @runtime.call('__csimSetTraceActive', false) end |
#click(handle, keys = [], **opts) ⇒ Object
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 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 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 |
# File 'lib/capybara/simulated/browser.rb', line 791 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 = dom_call('__csimClickResolve', handle, init) sleep delay dom_call('__csimClickFinish', handle, partial.is_a?(Hash) ? partial['base'] : init) else dom_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 # Inside a frame, a self-targeted link navigates the FRAME, not the # top page: fetch + rebuild this frame's realm. A pure-fragment link # is already handled in-realm by the frame's own location JS. if @current_realm_id && frame_self_target?(target) unless (url) tick_real_time navigate_frame(resolve_against_current(url, use_base: true)) end # `target="_blank"` (or any non-_self/_top/_parent name) opens # in a new browsing context (its own Browser/VM); the primary # stays put (per HTML spec — original window is unaffected). No # `opener_handle` is passed: modern browsers default `target=_blank` # to `noopener` (so `window.opener` is null), unlike JS `window.open` # which keeps the opener — see `open_window_from_js`. elsif !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.
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 |
# File 'lib/capybara/simulated/browser.rb', line 1178 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 = dom_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 |
#close_child_window(handle) ⇒ Object
2771 |
# File 'lib/capybara/simulated/browser.rb', line 2771 def close_child_window(handle) = (@driver.close_window(handle.to_s) if @driver.respond_to?(:close_window)) |
#coerce_set_value(v) ⇒ Object
1034 1035 1036 1037 1038 1039 1040 |
# File 'lib/capybara/simulated/browser.rb', line 1034 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
757 758 759 760 761 762 |
# File 'lib/capybara/simulated/browser.rb', line 757 def computed_style(handle, names) tick_real_time result = dom_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.
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 |
# File 'lib/capybara/simulated/browser.rb', line 1432 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.
1316 1317 1318 1319 1320 |
# File 'lib/capybara/simulated/browser.rb', line 1316 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
1584 1585 1586 1587 1588 |
# File 'lib/capybara/simulated/browser.rb', line 1584 def consume_pending_history_traverse return unless (target = @pending_history_traverse) @pending_history_traverse = nil perform_history_traverse(target) end |
#consume_pending_location ⇒ Object
3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 |
# File 'lib/capybara/simulated/browser.rb', line 3240 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.
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 |
# File 'lib/capybara/simulated/browser.rb', line 1411 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
3261 3262 3263 3264 3265 |
# File 'lib/capybara/simulated/browser.rb', line 3261 def consume_pending_reload return unless @pending_reload @pending_reload = false refresh end |
#current_browsing_context_url ⇒ Object
The active browsing context’s own URL: the frame document’s URL inside a ‘within_frame` block, else the main page URL. Used to resolve a frame-relative navigation and to set its request referrer, so `resolve_against_current` / `pure_fragment_navigation?` work the same whether the navigation originates in the main page or a frame.
562 563 564 565 566 |
# File 'lib/capybara/simulated/browser.rb', line 562 def current_browsing_context_url return @current_url unless @current_realm_id href = dom_call('__csimLocationHref').to_s href.empty? ? @current_url : href end |
#current_document_handle ⇒ Object
Root for a context-less find: the active frame’s document (handle 0 ⇒the realm’s own ‘globalThis.document`) when in a frame, else the main document handle.
495 496 497 |
# File 'lib/capybara/simulated/browser.rb', line 495 def current_document_handle @current_realm_id ? 0 : @document_handle end |
#current_path ⇒ Object
1859 1860 1861 1862 1863 1864 1865 |
# File 'lib/capybara/simulated/browser.rb', line 1859 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
3323 |
# File 'lib/capybara/simulated/browser.rb', line 3323 def current_referer ; @current_referer.to_s ; end |
#current_url ⇒ Object
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 |
# File 'lib/capybara/simulated/browser.rb', line 413 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.
2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 |
# File 'lib/capybara/simulated/browser.rb', line 2805 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).
3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 |
# File 'lib/capybara/simulated/browser.rb', line 3201 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.
2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 |
# File 'lib/capybara/simulated/browser.rb', line 2903 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.
2349 2350 2351 2352 2353 2354 2355 |
# File 'lib/capybara/simulated/browser.rb', line 2349 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
2596 2597 2598 2599 2600 2601 2602 |
# File 'lib/capybara/simulated/browser.rb', line 2596 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_window_messages ⇒ Object
Fire queued cross-window messages as ‘message` events on window.
2784 2785 2786 2787 2788 2789 |
# File 'lib/capybara/simulated/browser.rb', line 2784 def return 0 if @window_inbox.empty? events = @window_inbox.slice!(0, @window_inbox.length) @runtime.call('__csim_deliverWindowMessages', events) events.size end |
#deliver_worker_messages ⇒ Object
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 |
# File 'lib/capybara/simulated/browser.rb', line 2734 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).
1752 1753 1754 1755 1756 1757 1758 1759 1760 |
# File 'lib/capybara/simulated/browser.rb', line 1752 def describe_node_handle(handle) return "handle=#{handle}" if handle.nil? || handle.zero? info = dom_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
742 743 744 745 746 747 748 749 750 751 |
# File 'lib/capybara/simulated/browser.rb', line 742 def disabled?(handle) = dom_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
1209 1210 1211 1212 1213 1214 |
# File 'lib/capybara/simulated/browser.rb', line 1209 def dispatch_event(handle, type, init = {}) tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) dom_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.
3320 3321 3322 |
# File 'lib/capybara/simulated/browser.rb', line 3320 def RuntimeShared.utf8_text(@cookies.map {|k, v| "#{k}=#{v}" }.join('; ')) end |
#dom_call(name, *args) ⇒ Object
DOM / node / query host-fn dispatch. Inside a ‘within_frame` block it routes to the active frame realm’s context; otherwise straight to the main context. Handle integers are per-realm (each realm is a full bridge with its own registry), so an op on a frame node must run in the realm the handle came from — which, per Capybara’s within_frame contract, is the current realm for the block’s duration. Hot path: ‘@current_realm_id` is nil outside frames, so this is one nil-check over a direct `@runtime.call`.
479 480 481 482 483 484 485 486 487 488 489 490 |
# File 'lib/capybara/simulated/browser.rb', line 479 def dom_call(name, *args) return @runtime.call(name, *args) if @current_realm_id.nil? # The active frame's realm was torn down mid-block (the iframe was # removed or re-navigated). Surface a stale element so Capybara # retries / reports, rather than letting realm_call fall back to the # main context where this frame handle would mis-resolve. unless @runtime.frame_realm_alive?(@current_realm_id) raise Capybara::Simulated::StaleElement, "frame browsing context #{@current_realm_id} was torn down (frame removed or re-navigated)" end @runtime.realm_call(@current_realm_id, name, *args) end |
#double_click(handle, keys = [], **opts) ⇒ Object
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 |
# File 'lib/capybara/simulated/browser.rb', line 1135 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 { dom_call('__csimClickResolve', handle, opts) } init = {'bubbles' => true, 'cancelable' => true}.merge(click_event_init(handle, keys, opts)) dom_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. dom_call('__csimSelectWordAt', handle) settle end |
#download_link(url, filename_hint = '') ⇒ Object
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 |
# File 'lib/capybara/simulated/browser.rb', line 917 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.
1112 1113 1114 1115 1116 1117 1118 1119 1120 |
# File 'lib/capybara/simulated/browser.rb', line 1112 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) dom_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.
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 |
# File 'lib/capybara/simulated/browser.rb', line 1344 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
3266 3267 3268 3269 3270 |
# File 'lib/capybara/simulated/browser.rb', line 3266 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.
1097 1098 1099 1100 1101 1102 1103 |
# File 'lib/capybara/simulated/browser.rb', line 1097 def drop(handle, args) tick_real_time invalidate_find_cache ensure_alive_after_tick(handle) items = args.flat_map {|arg| drop_items(arg) } dom_call('__csimDropOnto', handle, items) end |
#drop_items(arg) ⇒ Object
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 |
# File 'lib/capybara/simulated/browser.rb', line 1121 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.
2242 2243 2244 2245 2246 2247 2248 |
# File 'lib/capybara/simulated/browser.rb', line 2242 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
665 666 667 |
# File 'lib/capybara/simulated/browser.rb', line 665 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
2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 |
# File 'lib/capybara/simulated/browser.rb', line 2964 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 |
#enqueue_window_message(data, origin, source_handle) ⇒ Object
Queue a cross-window message for delivery into THIS window’s VM (called by the Driver on the target Browser). Delivered as a ‘message` event the next time this window settles / ticks.
2777 2778 2779 |
# File 'lib/capybara/simulated/browser.rb', line 2777 def (data, origin, source_handle) @window_inbox << {'data' => data, 'origin' => origin.to_s, 'sourceHandle' => source_handle.to_s} 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).
786 787 788 789 |
# File 'lib/capybara/simulated/browser.rb', line 786 def ensure_alive_after_tick(handle) return if dom_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`.
2298 2299 2300 |
# File 'lib/capybara/simulated/browser.rb', line 2298 def eval_esm_module(url, src = nil) @runtime.eval_esm_module(url, src) end |
#evaluate_async_script(code, args = []) ⇒ Object
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 |
# File 'lib/capybara/simulated/browser.rb', line 1837 def evaluate_async_script(code, args = []) tick_real_time invalidate_find_cache # Runs in the active frame realm inside `within_frame` (Selenium # parity), same as evaluate_script; the result slot is realm-local so # the poll below must read from the same realm. dom_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 = dom_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
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 |
# File 'lib/capybara/simulated/browser.rb', line 1761 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 # Routes to the active frame realm inside `within_frame` (Selenium # parity: `evaluate_script` runs in the current browsing context). result = dom_call('__csimEvalScript', code.to_s, marshal_args(args || [])) result end |
#event_source_close(id) ⇒ Object
2333 2334 2335 2336 2337 |
# File 'lib/capybara/simulated/browser.rb', line 2333 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.
2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 |
# File 'lib/capybara/simulated/browser.rb', line 2322 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
2343 |
# File 'lib/capybara/simulated/browser.rb', line 2343 def event_source_pending? = !@event_source_queue.empty? |
#event_source_poll ⇒ Object
2339 2340 2341 |
# File 'lib/capybara/simulated/browser.rb', line 2339 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.
1780 1781 1782 1783 1784 1785 1786 |
# File 'lib/capybara/simulated/browser.rb', line 1780 def execute_script(code, args = []) tick_real_time invalidate_find_cache dom_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.
2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 |
# File 'lib/capybara/simulated/browser.rb', line 2268 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
731 732 733 |
# File 'lib/capybara/simulated/browser.rb', line 731 def file_input?(handle) tag(handle) == 'input' && attr(handle, 'type').to_s.downcase == 'file' end |
#file_picks_for(handle) ⇒ Object
1055 1056 1057 |
# File 'lib/capybara/simulated/browser.rb', line 1055 def file_picks_for(handle) (@file_picks && @file_picks[handle]) || [] end |
#find_css(css, context_handle = nil) ⇒ Object
586 587 588 589 590 591 592 593 594 595 596 597 |
# File 'lib/capybara/simulated/browser.rb', line 586 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 dom_call('__csimQuery', context_handle || current_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
599 600 601 602 603 604 605 606 607 608 |
# File 'lib/capybara/simulated/browser.rb', line 599 def find_first_css(css, context_handle = nil) s = css.to_s find_with_timer_fallback(:css_first, s, context_handle) do h = dom_call('__csimQueryOne', context_handle || current_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
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 |
# File 'lib/capybara/simulated/browser.rb', line 642 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.
635 636 637 638 639 640 |
# File 'lib/capybara/simulated/browser.rb', line 635 def find_xpath(xpath, context_handle = nil) xpath_str = xpath.to_s find_with_timer_fallback(:xpath, xpath_str, context_handle) do dom_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.
1670 1671 1672 1673 |
# File 'lib/capybara/simulated/browser.rb', line 1670 def finish_trace_to(path, trace = (@trace || @pending_trace)) return nil unless trace trace.write_json(path) end |
#format_temporal_value(v, handle) ⇒ Object
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 |
# File 'lib/capybara/simulated/browser.rb', line 1042 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 |
#frame_self_target?(target) ⇒ Boolean
Does a link/form ‘target` load into the CURRENT frame? Empty or `_self` do; `_top` / `_blank` / `_parent` / a named context do not. `_top` correctly navigates the main page (it falls through to `navigate`). `_parent` from a frame nested ≥2 levels would ideally navigate the intermediate parent frame, not the top page — that ancestor-targeted case isn’t modelled yet (rare); it currently navigates the main page.
581 582 583 584 |
# File 'lib/capybara/simulated/browser.rb', line 581 def frame_self_target?(target) t = target.to_s.downcase t.empty? || t == '_self' 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.
1819 1820 1821 |
# File 'lib/capybara/simulated/browser.rb', line 1819 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.
1546 |
# File 'lib/capybara/simulated/browser.rb', line 1546 def go_back ; history_go(-1, force: true) ; end |
#go_forward ⇒ Object
1547 |
# File 'lib/capybara/simulated/browser.rb', line 1547 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.
3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 |
# File 'lib/capybara/simulated/browser.rb', line 3384 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
2594 |
# File 'lib/capybara/simulated/browser.rb', line 2594 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).
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 |
# File 'lib/capybara/simulated/browser.rb', line 1554 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.
3313 3314 3315 |
# File 'lib/capybara/simulated/browser.rb', line 3313 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.
3304 3305 3306 3307 3308 3309 |
# File 'lib/capybara/simulated/browser.rb', line 3304 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.
3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 |
# File 'lib/capybara/simulated/browser.rb', line 3286 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.
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 |
# File 'lib/capybara/simulated/browser.rb', line 1980 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
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 |
# File 'lib/capybara/simulated/browser.rb', line 1192 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). dom_call('__csimSetHover', handle) end |
#html ⇒ Object
‘page.html` inside a `within_frame` block returns the frame document’s source (Selenium parity), so route through the active realm.
1467 1468 1469 1470 |
# File 'lib/capybara/simulated/browser.rb', line 1467 def html tick_real_time dom_call('__csimDocumentHtml').to_s end |
#inner_html(handle) ⇒ Object
729 |
# File 'lib/capybara/simulated/browser.rb', line 729 def inner_html(handle) = dom_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`).
722 723 724 |
# File 'lib/capybara/simulated/browser.rb', line 722 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`.
3237 3238 3239 |
# File 'lib/capybara/simulated/browser.rb', line 3237 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.
3260 |
# File 'lib/capybara/simulated/browser.rb', line 3260 def location_reload ; @pending_reload = true ; end |
#log_console(severity, message) ⇒ Object
1725 1726 1727 1728 1729 1730 1731 |
# File 'lib/capybara/simulated/browser.rb', line 1725 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
1746 |
# File 'lib/capybara/simulated/browser.rb', line 1746 def log_network(method, url, status) = @trace&.log_network(method, url, status) |
#lookup_node(handle) ⇒ Object
765 766 767 |
# File 'lib/capybara/simulated/browser.rb', line 765 def lookup_node(handle) handle if dom_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.
1335 1336 1337 |
# File 'lib/capybara/simulated/browser.rb', line 1335 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.
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 |
# File 'lib/capybara/simulated/browser.rb', line 1827 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
163 164 165 |
# File 'lib/capybara/simulated/browser.rb', line 163 def mime_type_for_path(path) Rack::Mime.mime_type(File.extname(path.to_s), '') end |
#modifier_flags(keys) ⇒ Object
1164 1165 1166 1167 1168 1169 |
# File 'lib/capybara/simulated/browser.rb', line 1164 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
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 |
# File 'lib/capybara/simulated/browser.rb', line 2124 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
763 |
# File 'lib/capybara/simulated/browser.rb', line 763 def node_path(handle) = dom_call('__csimNodePath', handle).to_s |
#open_child_window(url, name) ⇒ Object
‘window.open(url, name)` from JS — returns the new (or reused, by name) window’s handle, or nil. The URL is resolved against THIS document so a relative ‘window.open(’/x’)‘ targets the right origin/path.
2756 2757 2758 2759 |
# File 'lib/capybara/simulated/browser.rb', line 2756 def open_child_window(url, name) return nil unless @driver.respond_to?(:open_window_from_js) @driver.open_window_from_js(self, url.to_s, name.to_s) end |
#opener_handle ⇒ Object
2772 |
# File 'lib/capybara/simulated/browser.rb', line 2772 def opener_handle = @driver.respond_to?(:opener_handle_of) ? @driver.opener_handle_of(self) : nil |
#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.
752 |
# File 'lib/capybara/simulated/browser.rb', line 752 def option_selected?(h) = !!dom_call('__csimOptionSelected', h) |
#outer_html(handle) ⇒ Object
730 |
# File 'lib/capybara/simulated/browser.rb', line 730 def outer_html(handle) = dom_call('__csimOuterHTML', handle).to_s |
#parse_trace_mode(raw) ⇒ Object
1657 1658 1659 1660 |
# File 'lib/capybara/simulated/browser.rb', line 1657 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.
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 1885 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 |
#post_message_to_window(target_handle, data, origin) ⇒ Object
‘targetWindow.postMessage(data, origin)` — route to the target window’s inbox, tagged with this window as the source.
2763 2764 2765 2766 |
# File 'lib/capybara/simulated/browser.rb', line 2763 def (target_handle, data, origin) return unless @driver.respond_to?(:window_post_message) @driver.(self, target_handle.to_s, data, origin.to_s) end |
#pure_fragment_navigation?(url) ⇒ Boolean
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 |
# File 'lib/capybara/simulated/browser.rb', line 937 def (url) return true if url.start_with?('#') doc_url = current_browsing_context_url return false if doc_url.nil? target = resolve_against_current(url) a = URI.parse(target) b = URI.parse(doc_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
1510 1511 1512 1513 1514 |
# File 'lib/capybara/simulated/browser.rb', line 1510 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()`.
3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 |
# File 'lib/capybara/simulated/browser.rb', line 3091 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`.
2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 |
# File 'lib/capybara/simulated/browser.rb', line 2536 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
2588 2589 2590 2591 2592 |
# File 'lib/capybara/simulated/browser.rb', line 2588 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 ──────────────────
2225 2226 2227 2228 2229 |
# File 'lib/capybara/simulated/browser.rb', line 2225 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`).
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 |
# File 'lib/capybara/simulated/browser.rb', line 1066 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.
3227 3228 3229 3230 3231 3232 |
# File 'lib/capybara/simulated/browser.rb', line 3227 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.
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 |
# File 'lib/capybara/simulated/browser.rb', line 1690 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
1604 1605 1606 1607 1608 1609 1610 |
# File 'lib/capybara/simulated/browser.rb', line 1604 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
1479 1480 1481 1482 |
# File 'lib/capybara/simulated/browser.rb', line 1479 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.
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 |
# File 'lib/capybara/simulated/browser.rb', line 453 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.
3273 3274 3275 |
# File 'lib/capybara/simulated/browser.rb', line 3273 def refresh replay_history_entry(@history[@history_idx]) end |
#replay_history_entry(entry) ⇒ Object
1611 1612 1613 1614 1615 1616 1617 1618 |
# File 'lib/capybara/simulated/browser.rb', line 1611 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
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 |
# File 'lib/capybara/simulated/browser.rb', line 2160 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 # A test may leave a frame switched-to without switching back # (Capybara's reset_session spec covers exactly this); start the # next test back on the main document. reset_frame_scope @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 @window_inbox.clear @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
2496 2497 2498 2499 2500 |
# File 'lib/capybara/simulated/browser.rb', line 2496 def reset_event_sources @event_source_threads.each_value(&:kill) @event_source_threads.clear @event_source_queue.clear end |
#reset_frame_scope ⇒ Object
Return DOM-op routing to the main document and drop any frame stack. Called by ‘switch_to_frame(:top)`, per-test `reset!`, and every full page (re)build (which disposes all frame realms) — anything that invalidates the active `within_frame` scope.
552 553 554 555 |
# File 'lib/capybara/simulated/browser.rb', line 552 def reset_frame_scope @current_realm_id = nil @frame_stack.clear end |
#reset_hijacked_fetches ⇒ Object
2604 2605 2606 2607 2608 |
# File 'lib/capybara/simulated/browser.rb', line 2604 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.
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 |
# File 'lib/capybara/simulated/browser.rb', line 2036 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
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 |
# File 'lib/capybara/simulated/browser.rb', line 2837 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
3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 |
# File 'lib/capybara/simulated/browser.rb', line 3064 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_document_url(url) ⇒ Object
Public entry for the Driver to resolve a ‘window.open` / cross-window `location` URL against THIS window’s document (the internal resolver is private). Honours ‘<base href>` like the page’s own links do.
571 572 573 |
# File 'lib/capybara/simulated/browser.rb', line 571 def resolve_document_url(url) resolve_against_current(url, use_base: true) end |
#resolve_module_specifier(specifier, base_url) ⇒ Object
3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 |
# File 'lib/capybara/simulated/browser.rb', line 3053 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
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 |
# File 'lib/capybara/simulated/browser.rb', line 369 def resolve_visit_url(url) s = url.to_s # `about:blank` (and other authority-less schemes) have no `//`, so the # `scheme://` test below would treat them as relative paths and prepend # the host root. `navigate` handles `about:blank` specially — pass it # through untouched (open_new_window opens an about:blank tab). return s if s.match?(/\Aabout:/i) unless s =~ %r{\A[a-z]+://}i # Strip path/query/fragment off the current URL to get the origin # root. An opaque or host-less current URL (e.g. `about:blank` in a # freshly-opened window) can't yield an origin — fall back to the # default host so a subsequent relative `visit` still resolves. host_root = begin u = URI.parse(@current_url.to_s) if u.opaque || u.host.nil? @default_host else u.path = ''; u.query = nil; u.fragment = nil u.to_s end rescue URI::InvalidURIError @default_host end 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
3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 |
# File 'lib/capybara/simulated/browser.rb', line 3174 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’]‘.
1474 1475 1476 1477 1478 |
# File 'lib/capybara/simulated/browser.rb', line 1474 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
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 |
# File 'lib/capybara/simulated/browser.rb', line 1081 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)) dom_call('__csimDispatchEvent', handle, 'mousedown', init) sleep opts[:delay].to_f if opts[:delay].to_f > 0 dom_call('__csimDispatchEvent', handle, 'mouseup', init) dom_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.
1599 1600 1601 1602 |
# File 'lib/capybara/simulated/browser.rb', line 1599 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
1283 1284 1285 1286 1287 1288 1289 1290 |
# File 'lib/capybara/simulated/browser.rb', line 1283 def select_option(handle) mark_action_baseline tick_real_time invalidate_find_cache dom_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).
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 |
# File 'lib/capybara/simulated/browser.rb', line 1227 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 && dom_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 dom_call('__csimSendKeys', handle, [head]) tail.each {|atom| tick_real_time dom_call('__csimSendKeys', handle, [atom]) settle } else dom_call('__csimSendKeys', handle, atoms) end drain_after_user_action end |
#send_session_key(key) ⇒ Object
1651 |
# File 'lib/capybara/simulated/browser.rb', line 1651 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.
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 |
# File 'lib/capybara/simulated/browser.rb', line 1627 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 dom_call('__csimAdvanceFocus', sym == :backtab) elsif sym && MODIFIER_KEY_NAMES.include?(sym) held << sym else handle = active_element_handle handle = current_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
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 |
# File 'lib/capybara/simulated/browser.rb', line 1798 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
1484 |
# File 'lib/capybara/simulated/browser.rb', line 1484 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”>`.
3047 3048 3049 3050 3051 |
# File 'lib/capybara/simulated/browser.rb', line 3047 def set_importmap(json) @importmap = JSON.parse(json.to_s) rescue JSON::ParserError @importmap = {'imports' => {}, 'scopes' => {}} end |
#set_value_with_events(handle, value) ⇒ Object
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 |
# File 'lib/capybara/simulated/browser.rb', line 971 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 } } dom_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) : '' dom_call('__csimSetValue', handle, js_value) else dom_call('__csimSetValue', handle, coerced) end drain_after_user_action end |
#set_viewport(w, h) ⇒ Object
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 |
# File 'lib/capybara/simulated/browser.rb', line 1516 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 |
#set_window_location(handle, url) ⇒ Object
2769 |
# File 'lib/capybara/simulated/browser.rb', line 2769 def set_window_location(handle, url) = (@driver.window_set_location(handle.to_s, url.to_s) if @driver.respond_to?(:window_set_location)) |
#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.
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 |
# File 'lib/capybara/simulated/browser.rb', line 1369 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
753 754 755 756 |
# File 'lib/capybara/simulated/browser.rb', line 753 def shadow_root_handle(handle) h = dom_call('__csimShadowRoot', handle).to_i h.zero? ? nil : h end |
#stack_resolver ⇒ Object
1742 1743 1744 |
# File 'lib/capybara/simulated/browser.rb', line 1742 def stack_resolver @stack_resolver ||= StackResolver.new(self) end |
#start_trace(metadata = {}) ⇒ Object
1662 1663 1664 1665 |
# File 'lib/capybara/simulated/browser.rb', line 1662 def start_trace( = {}) @trace = Trace.new(metadata: ) @runtime.call('__csimSetTraceActive', true) end |
#status_code ⇒ Object
1472 1473 |
# File 'lib/capybara/simulated/browser.rb', line 1472 def status_code = (@last_response_status || 200) # Rack 3 lowercases header names; Capybara tests do `['Content-Type']`. |
#storage_clear(kind) ⇒ Object
3356 3357 3358 3359 |
# File 'lib/capybara/simulated/browser.rb', line 3356 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.
3345 3346 3347 |
# File 'lib/capybara/simulated/browser.rb', line 3345 def storage_get(kind, key) store(kind)[key.to_s] end |
#storage_key(kind, index) ⇒ Object
3360 3361 3362 |
# File 'lib/capybara/simulated/browser.rb', line 3360 def storage_key(kind, index) store(kind).keys[index.to_i] end |
#storage_length(kind) ⇒ Object
3363 3364 3365 |
# File 'lib/capybara/simulated/browser.rb', line 3363 def storage_length(kind) store(kind).size end |
#storage_remove(kind, key) ⇒ Object
3352 3353 3354 3355 |
# File 'lib/capybara/simulated/browser.rb', line 3352 def storage_remove(kind, key) store(kind).delete(key.to_s) nil end |
#storage_set(kind, key, value) ⇒ Object
3348 3349 3350 3351 |
# File 'lib/capybara/simulated/browser.rb', line 3348 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.
1452 1453 1454 1455 1456 1457 1458 |
# File 'lib/capybara/simulated/browser.rb', line 1452 def submit_form(handle) tick_real_time invalidate_find_cache form_handle = dom_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.
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 |
# File 'lib/capybara/simulated/browser.rb', line 2051 def submit_form_handle(form_handle, submitter_handle) invalidate_find_cache spec = dom_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_browsing_context_url || @default_host) : resolve_against_current(action) # A form submitted inside a frame whose target is the frame itself # navigates the FRAME, not the top page. in_frame = !!@current_realm_id && frame_self_target?(spec['target']) if method == 'GET' uri = URI.parse(action_url) uri.query = body unless body.empty? in_frame ? navigate_frame(uri.to_s) : navigate(uri.to_s) elsif in_frame navigate_frame_post(action_url, body, content_type || enctype) else navigate_post(action_url, body, content_type || enctype) end end |
#switch_to_frame(target) ⇒ Object
Capybara ‘switch_to_frame`. `target` is an `<iframe>` handle in the CURRENT realm, or `:parent` / `:top`. Entering builds (or reuses) the frame’s V8 realm and routes subsequent DOM ops there; ‘:parent` pops one level, `:top` returns to the main document. Frame switches invalidate the find cache (its keys aren’t realm-qualified, and a switch is rare).
Scope: finds, reads, interactions (click/fill_in/…), evaluate_script, and a self-targeted navigation (a link / form submit whose default action loads a new document) all route into the frame — the frame’s realm is rebuilt from the fetched document, leaving the top page untouched (see ‘navigate_frame`). Out of scope: `_top` navigates the main page (correct), but a `_parent` target from a frame nested ≥2 levels navigates the main page rather than the intermediate frame, and cross-origin frame locality is resolved against the main page’s origin.
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 |
# File 'lib/capybara/simulated/browser.rb', line 513 def switch_to_frame(target) invalidate_find_cache case target when :parent @frame_stack.pop @current_realm_id = @frame_stack.last && @frame_stack.last[:realm_id] when :top reset_frame_scope else # Per-frame realms are a V8-engine feature; QuickJS has no nested # browsing context to route into. Distinguish that (unsupported # engine) from a frame that simply failed to build (below), so the # error doesn't misattribute a load failure to the engine. unless @runtime.respond_to?(:realm_call) raise Capybara::Simulated::FrameNotSupported, 'within_frame needs a per-frame browsing context, which only the ' \ 'V8 (rusty_racer) engine provides; QuickJS keeps a same-realm fallback.' end parent_realm = @current_realm_id tick_real_time rid = dom_call('__csimEnsureFrameRealm', target.to_i).to_i if rid.zero? raise Capybara::Simulated::StaleElement, "could not enter frame ##{target} (not a frame element, or its document failed to load)" end # Record the iframe handle + the realm it lives in so a frame-scoped # navigation can rebuild this exact frame (`reload_current_frame_realm`). @frame_stack.push({realm_id: rid, iframe_handle: target.to_i, parent_realm_id: parent_realm}) @current_realm_id = rid # Let the freshly built realm's inline scripts / load handlers settle # so a find immediately inside the block sees the loaded document. settle 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.
617 618 619 620 |
# File 'lib/capybara/simulated/browser.rb', line 617 def syntax_or_invalid_selector_error?(e) e.class.name.to_s.end_with?('::SyntaxError') || e..to_s.include?('csim: ') end |
#tag(handle) ⇒ Object
727 |
# File 'lib/capybara/simulated/browser.rb', line 727 def tag(handle) = dom_call('__csimTag', handle).to_s |
#tag_name(handle) ⇒ Object
740 |
# File 'lib/capybara/simulated/browser.rb', line 740 def tag_name(handle) = tag(handle) |
#text(handle) ⇒ Object
726 |
# File 'lib/capybara/simulated/browser.rb', line 726 def text(handle) = dom_call('__csimText', handle).to_s |
#text_response?(headers) ⇒ Boolean
3217 3218 3219 3220 3221 |
# File 'lib/capybara/simulated/browser.rb', line 3217 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.
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 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 |
# File 'lib/capybara/simulated/browser.rb', line 1919 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 @find_cache_dirty = true if > 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
677 678 679 680 |
# File 'lib/capybara/simulated/browser.rb', line 677 def timer_wait_elapsed? @timers_active && (Process.clock_gettime(Process::CLOCK_MONOTONIC) - @last_tick_ts) >= FIND_PRE_TICK_MIN_S end |
#title ⇒ Object
1460 1461 1462 1463 |
# File 'lib/capybara/simulated/browser.rb', line 1460 def title tick_real_time @runtime.call('__csimDocumentTitle').to_s end |
#transfer_buffer_fetch(id) ⇒ Object
2882 2883 2884 |
# File 'lib/capybara/simulated/browser.rb', line 2882 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.
2891 2892 2893 2894 2895 |
# File 'lib/capybara/simulated/browser.rb', line 2891 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.
2872 2873 2874 2875 2876 2877 2878 2879 2880 |
# File 'lib/capybara/simulated/browser.rb', line 2872 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
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 |
# File 'lib/capybara/simulated/browser.rb', line 1292 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 = dom_call('__csimOptionContext', handle) if info.is_a?(Hash) && info['hasSelect'] && !info['multiple'] raise Capybara::UnselectNotAllowed, 'Cannot unselect option from single select box.' end dom_call('__csimUnselectOption', handle) tick_real_time drain_after_user_action end |
#update_current_hash(url) ⇒ Object
956 957 958 959 960 961 962 963 964 965 966 967 968 969 |
# File 'lib/capybara/simulated/browser.rb', line 956 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
741 |
# File 'lib/capybara/simulated/browser.rb', line 741 def value(handle) = dom_call('__csimValue', handle) |
#viewport_height ⇒ Object
1541 |
# File 'lib/capybara/simulated/browser.rb', line 1541 def ; @viewport_height || 768 ; end |
#viewport_width ⇒ Object
1540 |
# File 'lib/capybara/simulated/browser.rb', line 1540 def ; @viewport_width || 1024 ; end |
#visible?(handle) ⇒ Boolean
734 |
# File 'lib/capybara/simulated/browser.rb', line 734 def visible?(handle) = dom_call('__csimVisible', handle) ? true : false |
#visible_text(handle) ⇒ Object
739 |
# File 'lib/capybara/simulated/browser.rb', line 739 def visible_text(handle) = dom_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).
362 363 364 |
# File 'lib/capybara/simulated/browser.rb', line 362 def visit(url) navigate(resolve_visit_url(url), referer: nil) end |
#webauthn ⇒ Object
2978 |
# File 'lib/capybara/simulated/browser.rb', line 2978 def webauthn = (@webauthn ||= WebauthnState.new) |
#window_closed?(handle) ⇒ Boolean
2770 |
# File 'lib/capybara/simulated/browser.rb', line 2770 def window_closed?(handle) = @driver.respond_to?(:window_closed?) ? @driver.window_closed?(handle.to_s) : true |
#window_location_of(handle) ⇒ Object
2768 |
# File 'lib/capybara/simulated/browser.rb', line 2768 def window_location_of(handle) = @driver.respond_to?(:window_location) ? @driver.window_location(handle.to_s).to_s : '' |
#window_message_pending? ⇒ Boolean
2781 |
# File 'lib/capybara/simulated/browser.rb', line 2781 def = !@window_inbox.empty? |
#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.
3372 3373 3374 3375 3376 3377 |
# File 'lib/capybara/simulated/browser.rb', line 3372 def with_modal(handler) @modal_handlers.push(handler) yield if block_given? ensure @modal_handlers.delete(handler) end |
#worker_pending? ⇒ Boolean
2745 |
# File 'lib/capybara/simulated/browser.rb', line 2745 def worker_pending? = !@worker_outbox.empty? || @worker_in_flight > 0 |
#worker_post_to_worker(handle, data) ⇒ Object
2713 2714 2715 2716 2717 2718 |
# File 'lib/capybara/simulated/browser.rb', line 2713 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.
2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 |
# File 'lib/capybara/simulated/browser.rb', line 2693 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
2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 |
# File 'lib/capybara/simulated/browser.rb', line 2720 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
3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 |
# File 'lib/capybara/simulated/browser.rb', line 3324 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
622 623 624 625 626 627 628 629 630 |
# File 'lib/capybara/simulated/browser.rb', line 622 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 |