bidi2pdf 0.1.22 → 0.1.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: '008d5b0569ba4b7f8bbcd4092da72ce14e5d0e42589a97813f7c64c8bc6a0d9f'
4
- data.tar.gz: 8266f91bfa7606d843bed392cee203060cc3b13d98435cc9a0c4a679b5041285
3
+ metadata.gz: 924c1d8c78d46fdb5e08e333861afbac5384a17b3d4a78c365f9cd09d88b5068
4
+ data.tar.gz: 973fcae887672a67d00acb6ee131866ef904f2b6f67661f180b7e51f16b90c3f
5
5
  SHA512:
6
- metadata.gz: 27ce2475fa8d30bc9c5447353767c6d2c06db59f57daa7fab7e7a337e26703cc1a0df04439d2b8b68455e5a872138775321a7f31988beb02dba47df0dd06d48d
7
- data.tar.gz: acb216b0c656916ee8e8ea797b1fccd026c67fa6260ac5f230f1c44190ffb00455fd83efb5238826c97af0f0051cf68a7335d09e51e0aaa25b85c2efdc802290
6
+ metadata.gz: f73a0fddac84bfc084e57a2a5353587d00d72ad9dd9f37d6ec35ce86050794b033fed60a7ed8d7425ee5624b9a1757941e8f646b1155057f171f704c2799811e
7
+ data.tar.gz: 96dcbd832b570bc9723581cffc4eeae40bb547eb7eb9ca81578911ea0985953c3353b7ac4c8896cfd490240862b48d88aade7d38e4cb788a2c23058ee20350d0
data/CHANGELOG.md CHANGED
@@ -8,10 +8,53 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
- [unreleased]: https://github.com/dieter-medium/bidi2pdf/compare/v0.1.22..HEAD
11
+ [unreleased]: https://github.com/dieter-medium/bidi2pdf/compare/v0.1.24..HEAD
12
12
 
13
13
  <!-- generated by git-cliff end -->
14
14
 
15
+ ## [0.1.24] - 2026-10-27
16
+
17
+ ### 🐛 Fixed
18
+ - Release every live slot after a fork
19
+ - Release a forked child's in-flight slots too
20
+ - Close a forked child's copies of inherited sockets
21
+ - Give a forked child its own session warmer
22
+
23
+ ### 🔄 Changed
24
+ - Merge pull request #174 from dieter-medium/fix/warmer-after-fork
25
+ - Merge pull request #173 from dieter-medium/dependabot/bundler/main/rubocop-1.92.1
26
+
27
+ ### 🔧 Build
28
+ - Bump rubocop from 1.92.0 to 1.92.1
29
+
30
+ ## [0.1.23] - 2026-10-18
31
+
32
+ ### 🐛 Fixed
33
+ - Spell the plugin version as semver
34
+ - Keep screenshot names apart and stop browsers
35
+ - Stop every browser even when one stop fails
36
+ - Keep stdout to the JSON document or the PDF
37
+ - Lay a mobile print out at the intended width
38
+
39
+ ### 📝 Docs
40
+ - Explain how to install, pin and update the Claude Code skills
41
+ - Fix the script path and weigh the Chrome sandbox
42
+
43
+ ### 🔄 Changed
44
+ - Merge pull request #170 from dieter-medium/feat/claude-skills
45
+ - Merge pull request #169 from dieter-medium/fix/clean-stdout
46
+ - Merge pull request #160 from dieter-medium/dependabot/bundler/main/simplecov-1.3.2
47
+ - Merge pull request #167 from dieter-medium/dependabot/bundler/main/rubocop-1.92.0
48
+ - Merge pull request #168 from dieter-medium/feat/emulate-media
49
+
50
+ ### 🔧 Build
51
+ - Bump simplecov from 1.3.1 to 1.3.2
52
+ - Bump rubocop from 1.91.0 to 1.92.0
53
+
54
+ ### 🚀 Added
55
+ - Ship Claude Code skills for bidi2pdf
56
+ - Let a tab emulate a CSS media type
57
+
15
58
  ## [0.1.22] - 2026-10-11
16
59
 
17
60
  ### 🐛 Fixed
@@ -568,7 +611,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
568
611
 
569
612
  ### 🔄 Released
570
613
 
571
- - [unreleased](https://github.com/dieter-medium/bidi2pdf/compare/v0.1.22..HEAD)
614
+ - [unreleased](https://github.com/dieter-medium/bidi2pdf/compare/v0.1.24..HEAD)
615
+ - [0.1.24](https://github.com/dieter-medium/bidi2pdf/compare/v0.1.23..v0.1.24)
616
+ - [0.1.23](https://github.com/dieter-medium/bidi2pdf/compare/v0.1.22..v0.1.23)
572
617
  - [0.1.22](https://github.com/dieter-medium/bidi2pdf/compare/v0.1.21..v0.1.22)
573
618
  - [0.1.21](https://github.com/dieter-medium/bidi2pdf/compare/v0.1.20..v0.1.21)
574
619
  - [0.1.20](https://github.com/dieter-medium/bidi2pdf/compare/v0.1.19..v0.1.20)
data/README.md CHANGED
@@ -110,6 +110,26 @@ bidi2pdf render \
110
110
  --log-level debug
111
111
  ```
112
112
 
113
+ #### The page as it looks on screen, dark mode, or its mobile version
114
+
115
+ By default Chrome prints with the page's print stylesheet. `--media screen` prints its screen styles
116
+ instead, `--color_scheme dark` its dark mode, `--reduced_motion reduce` with animations off.
117
+
118
+ A narrow page adds the page's mobile layout. A printed page is laid out at the width between its side
119
+ margins, not at the paper's width: page width minus `--margin_left` and `--margin_right`, at about
120
+ 37.8 CSS px per cm (96 / 2.54). Without margins of your own Chrome uses 1 cm a side, so a 9.5 cm page
121
+ lays out at about 283 px. For a 360 px phone layout, set the side margins explicitly:
122
+
123
+ ```bash
124
+ bidi2pdf render --url https://example.com --output mobile.pdf \
125
+ --media screen --color_scheme dark \
126
+ --page_width 9.525 --page_height 20 --margin_left 0 --margin_right 0
127
+ ```
128
+
129
+ 8.467 cm without side margins gives 320 px. All page sizes and margins are in centimetres.
130
+
131
+ `bidi2pdf diagnose` takes the same three options, so its screenshot shows the same emulation.
132
+
113
133
  ---
114
134
 
115
135
  ## 🤖 Agent and Automation Usage
@@ -243,7 +263,7 @@ bidi2pdf run invoice.yml --json # actions, then the PDF, then assertions a
243
263
  ```
244
264
 
245
265
  Actions (`wait_for`, `click`, `evaluate`, `inject_script`, `inject_style`, `set_viewport`,
246
- `wait_network_idle`) and page assertions (`selector_exists`, `text_present`, `no_console_errors`,
266
+ `wait_network_idle`, `emulate_media`) and page assertions (`selector_exists`, `text_present`, `no_console_errors`,
247
267
  `no_network_failures`, `fonts_loaded`) are a thin layer over the same `BrowserTab` methods the
248
268
  [Programmatic API](#-programmatic-api) below uses directly. PDF assertions (`page_count`,
249
269
  `pdf_text_present`, `pdf_not_blank`) need the `pdf-reader` gem - a recipe using one fails
@@ -256,6 +276,91 @@ rejected by both `bidi2pdf schema recipe` and `--validate` rather than being sil
256
276
  `wait_for` needs exactly one of `selector`, `paged_js`, `script` - zero or more than one is
257
277
  rejected the same way, before any browser launches.
258
278
 
279
+ ### Claude Code skills
280
+
281
+ The repository ships a [Claude Code](https://claude.com/claude-code) plugin with six skills, so an
282
+ agent uses bidi2pdf the way it is meant to be used instead of guessing options:
283
+
284
+ | Skill | For |
285
+ |---|---|
286
+ | `render-pdf` | a URL or HTML file to PDF with the CLI: order of commands, waits, screen/dark/mobile view, reading the JSON result and exit codes |
287
+ | `pdf-recipe` | a recipe for pages that need steps before printing, validated without a browser |
288
+ | `diagnose-pdf` | a blank, unstyled or wrongly paged PDF: a checklist around `bidi2pdf diagnose` |
289
+ | `remote-chrome` | a shared chromedriver container: settings, sizing, session cleanup, untrusted HTML |
290
+ | `page-screenshots` | review screenshots per page at phone and desktop width, light and dark (with a script) |
291
+ | `pdf-specs` | RSpec specs with the gem's PDF matchers and Chrome container helpers |
292
+
293
+ #### Installing the skills
294
+
295
+ The plugin is not in a central store: this repository is its own Claude Code marketplace
296
+ (`.claude-plugin/marketplace.json`, marketplace name `bidi2pdf`). You add the repository as a
297
+ marketplace once, then install the plugin from it. In a Claude Code session:
298
+
299
+ ```text
300
+ /plugin marketplace add dieter-medium/bidi2pdf
301
+ /plugin install bidi2pdf@bidi2pdf
302
+ ```
303
+
304
+ `/plugin install` does not install right away: it opens the plugin's details, where you choose the scope
305
+ (just you, the project, or only this checkout) and confirm the installation.
306
+
307
+ Or from a shell, where the install happens at once:
308
+
309
+ ```bash
310
+ claude plugin marketplace add dieter-medium/bidi2pdf
311
+ claude plugin install bidi2pdf@bidi2pdf # --scope user (default), project or local
312
+ ```
313
+
314
+ The skills then load on their own when a task fits them; nothing else needs configuring.
315
+
316
+ **Which version you get.** The plugin's version is the gem's (`claude-plugin/.claude-plugin/plugin.json`),
317
+ and Claude Code installs an update only when that version changes - not with every commit. Adding the
318
+ marketplace as above follows the default branch, so after a release the skills there can already
319
+ describe the next, unreleased gem (the version then reads e.g. `0.1.24-pre`). To stay on the skills of
320
+ the gem you actually use, add the marketplace at its release tag:
321
+
322
+ ```bash
323
+ claude plugin marketplace add dieter-medium/bidi2pdf#v0.1.23
324
+ ```
325
+
326
+ **Updating and removing.** Auto-update is off for this marketplace unless you turn it on (`/plugin` >
327
+ Marketplaces). By hand:
328
+
329
+ ```bash
330
+ claude plugin marketplace update bidi2pdf # fetch the marketplace again
331
+ claude plugin update bidi2pdf@bidi2pdf # take the new version
332
+ claude plugin uninstall bidi2pdf@bidi2pdf # remove the plugin only
333
+ claude plugin marketplace remove bidi2pdf # remove the marketplace and every plugin installed from it
334
+ ```
335
+
336
+ **For a whole team.** To give everyone working in a project the skills, commit this to the project's
337
+ `.claude/settings.json` - each member gets them after accepting Claude Code's trust prompt for the
338
+ folder:
339
+
340
+ ```json
341
+ {
342
+ "extraKnownMarketplaces": {
343
+ "bidi2pdf": { "source": { "source": "github", "repo": "dieter-medium/bidi2pdf" } }
344
+ },
345
+ "enabledPlugins": { "bidi2pdf@bidi2pdf": true }
346
+ }
347
+ ```
348
+
349
+ `claude plugin marketplace add dieter-medium/bidi2pdf --scope project` and
350
+ `claude plugin install bidi2pdf@bidi2pdf --scope project` write the same entries for you.
351
+
352
+ **From a checkout, without installing** (to try a change to a skill):
353
+
354
+ ```bash
355
+ claude --plugin-dir ./claude-plugin # for this one session
356
+ claude plugin validate ./claude-plugin --strict # check the plugin's structure
357
+ ```
358
+
359
+ The skills point at `bidi2pdf help <command>` and `bidi2pdf schema <kind>` for exact options and
360
+ shapes; a spec (`spec/unit/claude_plugin_spec.rb`) checks every command, option, error code, recipe and
361
+ method they name against the gem, so they cannot drift from it. The plugin is not part of the gem
362
+ itself.
363
+
259
364
  ---
260
365
 
261
366
  ## 🧠 Programmatic API
@@ -350,6 +455,10 @@ tab.navigate_to "https://example.com/invoice/14432423"
350
455
  # Printing HTML you do not trust? Switch its scripts off before navigating:
351
456
  # tab.disable_script_execution
352
457
 
458
+ # Print the screen styles in dark mode instead of the print stylesheet (holds for later
459
+ # navigations in this tab; tab.emulate_media without arguments ends it):
460
+ # tab.emulate_media(media: "screen", color_scheme: "dark")
461
+
353
462
  tab.wait_until_network_idle
354
463
  tab.print("my.pdf")
355
464
 
@@ -716,6 +825,61 @@ session becomes a leftover like any other. Only processes that share the registr
716
825
  each other's leases: give job workers in another container the same `registry_dir` on a shared
717
826
  volume. Sessions other tools opened have no lease; under `scope: :all` only `min_age` protects them.
718
827
 
828
+ **Forked processes (Puma workers).** The warmer belongs to the process that configured it. A child
829
+ forked after that - Rails boots the app, and with it the warmer, in Puma's master before it forks its
830
+ workers - does not use the copy it inherits: its threads did not survive the fork, and its slots,
831
+ WebSocket connections included, are the parent's (a render on one used to time out while the parent
832
+ took the answers). The child drops that copy - it closes only its own copies of the spare slots'
833
+ sockets, locally, with no WebSocket close frame and no session end, so nothing of its parent's is
834
+ touched - and builds its own warmer. The parent keeps its warmer.
835
+
836
+ Without further setup the child builds it on its first render, and that render then waits for the
837
+ whole warm-up: `size` new Chrome sessions, one after the other. To warm each worker before it takes
838
+ requests:
839
+
840
+ ```ruby
841
+ # config/puma.rb
842
+ on_worker_boot do
843
+ Bidi2pdf::SessionWarmer.after_fork
844
+ end
845
+ ```
846
+
847
+ Every worker then holds `size` spares of its own, besides the master's: with `W` workers, `size * (W + 1)`
848
+ idle sessions after boot - 2 workers at `size = 1` keep 3 Chromes waiting - and during renders one more
849
+ per render in flight plus the replacements warming. Count them in when sizing the chromedriver
850
+ (`max_sessions`, its memory and its process limit).
851
+
852
+ Puma's master renders nothing. To keep it from holding warm sessions nobody uses, end its warmer before
853
+ it forks - at that point no worker exists yet, so no child holds a copy of those sessions:
854
+
855
+ ```ruby
856
+ # config/puma.rb
857
+ before_fork do
858
+ Bidi2pdf::SessionWarmer.shutdown
859
+ end
860
+ ```
861
+
862
+ With `fork_worker`, worker 0 serves requests and forks the other workers itself; `before_fork` runs only
863
+ in the master and does not cover those forks. Puma runs `before_refork` in worker 0 before it forks and
864
+ `after_refork` once the cycle is done, so end worker 0's warmer before and give it a new one after:
865
+
866
+ ```ruby
867
+ # config/puma.rb, with fork_worker
868
+ before_refork do
869
+ Bidi2pdf::SessionWarmer.shutdown
870
+ end
871
+
872
+ after_refork do
873
+ Bidi2pdf::SessionWarmer.after_fork # builds worker 0 a warmer of its own again
874
+ end
875
+ ```
876
+
877
+ The workers worker 0 forks run `on_worker_boot` like any other. A render still in flight in worker 0 when
878
+ it forks is fine: a child releases every slot it inherited - warm, out for a render, or being checked out
879
+ or retired - and a release that fails is logged while the others go on. Not covered is a session still
880
+ being built in the forking process at that instant: its socket copy in the child is left to garbage
881
+ collection (a file descriptor, nothing the child or the parent uses).
882
+
719
883
  **Last resort: pressure.** `sweep!(pressure: true)` closes every session nobody holds that is past
720
884
  `min_age`, without waiting for `orphan_age`, the unresponsive checks or the limit. `with_retry` does
721
885
  that when its block fails with a resource error - chromedriver refusing a session
@@ -41,6 +41,13 @@ module Bidi2pdf
41
41
  class BrowserTab
42
42
  include JsLoggerHelper
43
43
 
44
+ # The values #emulate_media accepts, by argument - what Chrome's Emulation.setEmulatedMedia knows.
45
+ EMULATED_MEDIA = {
46
+ media: %w[screen print],
47
+ color_scheme: %w[light dark],
48
+ reduced_motion: %w[reduce no-preference]
49
+ }.freeze
50
+
44
51
  # @return [Object] The WebSocket client.
45
52
  attr_reader :client
46
53
 
@@ -439,7 +446,9 @@ module Bidi2pdf
439
446
 
440
447
  block.call(pdf_base64) if block_given?
441
448
 
442
- return pdf_base64 unless outputfile || block_given?
449
+ # The block's value, not a `return`: returning out of the instrumented block would
450
+ # skip the print event, and with it every subscriber (ResultCollector, --output -).
451
+ outputfile || block_given? ? nil : pdf_base64
443
452
  else
444
453
  Bidi2pdf.logger.error "Error printing: #{response}"
445
454
  end
@@ -480,7 +489,8 @@ module Bidi2pdf
480
489
 
481
490
  block.call(png_base64) if block_given?
482
491
 
483
- return png_base64 unless outputfile || block_given?
492
+ # The block's value, not a `return` - see #print.
493
+ outputfile || block_given? ? nil : png_base64
484
494
  else
485
495
  Bidi2pdf.logger.error "Error capturing screenshot: #{response}"
486
496
  end
@@ -513,8 +523,43 @@ module Bidi2pdf
513
523
  client.send_cmd_and_wait(cmd) { |response| response }
514
524
  end
515
525
 
526
+ # Emulates a CSS media type and media features for this tab, through Chrome's own
527
+ # Emulation.setEmulatedMedia (CDP, via goog:cdp.sendCommand). It holds for every later
528
+ # navigation in the tab and for printing: +media: "screen"+ prints a page with its screen styles
529
+ # instead of its print stylesheet, +color_scheme: "dark"+ in its dark mode. On a narrow page the
530
+ # screen media type prints a page's mobile layout: the layout width is the page width minus the
531
+ # side margins (Chrome's default is 1 cm each), at 96 / 2.54 CSS px per cm - e.g.
532
+ # +page: { width: 9.525 }, margin: { left: 0, right: 0 }+ lays out at 360 px. Each call replaces
533
+ # the previous emulation, so a media type or feature it omits is reset; a call without arguments
534
+ # ends it.
535
+ #
536
+ # @param [String, Symbol, nil] media "screen" or "print"; nil leaves it to the browser.
537
+ # @param [String, Symbol, nil] color_scheme "light" or "dark" (prefers-color-scheme).
538
+ # @param [String, Symbol, nil] reduced_motion "reduce" or "no-preference" (prefers-reduced-motion).
539
+ # @raise [ArgumentError] for a value Chrome does not know, before anything is sent.
540
+ def emulate_media(media: nil, color_scheme: nil, reduced_motion: nil)
541
+ params = emulated_media_params(media: media, color_scheme: color_scheme, reduced_motion: reduced_motion)
542
+ cmd = Commands::CdpSendCommand.new(method: "Emulation.setEmulatedMedia", params: params, session: cdp_session)
543
+ client.send_cmd_and_wait(cmd) { |response| response }
544
+ end
545
+
516
546
  private
517
547
 
548
+ def emulated_media_params(**values)
549
+ values.each { |name, value| check_emulated_media(name, value) }
550
+
551
+ features = { "prefers-color-scheme" => values[:color_scheme], "prefers-reduced-motion" => values[:reduced_motion] }
552
+ .filter_map { |name, value| { name: name, value: value.to_s } unless value.nil? }
553
+ { media: values[:media].to_s, features: features }
554
+ end
555
+
556
+ def check_emulated_media(name, value)
557
+ allowed = EMULATED_MEDIA.fetch(name)
558
+ return if value.nil? || allowed.include?(value.to_s)
559
+
560
+ raise ArgumentError, "#{name} must be one of #{allowed.join(", ")}, got #{value.inspect}"
561
+ end
562
+
518
563
  def build_command_and_extractor(print_options)
519
564
  cmd_type = (print_options.delete(:cmd_type) || :bidi).to_sym
520
565
 
@@ -82,6 +82,23 @@ module Bidi2pdf
82
82
  end
83
83
  end
84
84
 
85
+ # In a forked child: drops this process's copy of a connection the parent opened, without a word
86
+ # to the peer - no close frame, no TLS close_notify (the underlying TCP socket is closed, not the
87
+ # SSL one), no :close event - so the parent goes on using it. Closing a descriptor the parent also
88
+ # holds ends nothing for the peer; the reader thread did not survive the fork.
89
+ def release_after_fork
90
+ @close_monitor.synchronize do
91
+ return if @closed
92
+
93
+ @closed = true
94
+ io = @socket.respond_to?(:to_io) ? @socket.to_io : @socket
95
+ io&.close unless io.nil? || io.closed?
96
+ @socket = nil
97
+ end
98
+ rescue IOError, SystemCallError
99
+ nil
100
+ end
101
+
85
102
  def open? = @handshaked && !@closed
86
103
 
87
104
  def closed? = @closed
@@ -154,6 +154,12 @@ module Bidi2pdf
154
154
  end
155
155
 
156
156
  # Closes the WebSocket connection.
157
+ # In a forked child: lets go of the parent's connection locally (BufferedWebSocketClient#release_after_fork).
158
+ def release_after_fork
159
+ @socket&.release_after_fork
160
+ @socket = nil
161
+ end
162
+
157
163
  def close
158
164
  return unless @socket
159
165
 
@@ -167,6 +167,14 @@ module Bidi2pdf
167
167
  end
168
168
  end
169
169
 
170
+ # In a forked child: drops this process's copies of the parent's connections - the command client
171
+ # and the event socket - without ending the session, which is the parent's (see #close for that).
172
+ def release_after_fork
173
+ @client&.release_after_fork
174
+ @event_socket&.release_after_fork
175
+ @client = @event_socket = nil
176
+ end
177
+
170
178
  private
171
179
 
172
180
  # Sends a command to the WebSocket client.
data/lib/bidi2pdf/cli.rb CHANGED
@@ -78,10 +78,10 @@ module Bidi2pdf
78
78
  option :manifest, type: :string, desc: "Write a render manifest (see `bidi2pdf schema manifest`) to this file"
79
79
 
80
80
  option :background, type: :boolean, default: true, desc: "Print background graphics"
81
- option :margin_top, type: :numeric, default: 1.0, desc: "Top margin in inches"
82
- option :margin_bottom, type: :numeric, default: 1.0, desc: "Bottom margin in inches"
83
- option :margin_left, type: :numeric, default: 1.0, desc: "Left margin in inches"
84
- option :margin_right, type: :numeric, default: 1.0, desc: "Right margin in inches"
81
+ option :margin_top, type: :numeric, default: 1.0, desc: "Top margin in cm"
82
+ option :margin_bottom, type: :numeric, default: 1.0, desc: "Bottom margin in cm"
83
+ option :margin_left, type: :numeric, default: 1.0, desc: "Left margin in cm"
84
+ option :margin_right, type: :numeric, default: 1.0, desc: "Right margin in cm"
85
85
  option :orientation, type: :string, default: "portrait", enum: %w[portrait landscape], desc: "Page orientation"
86
86
  option :page_width, type: :numeric, default: 21.59, desc: "Page width in cm (min 0.0352)"
87
87
  option :page_height, type: :numeric, default: 27.94, desc: "Page height in cm (min 0.0352)"
@@ -90,6 +90,9 @@ module Bidi2pdf
90
90
  option :shrink_to_fit, type: :boolean, default: true, desc: "Shrink content to fit page"
91
91
  option :generate_tagged_pdf, type: :boolean, default: false, desc: "Generate tagged PDF"
92
92
  option :generate_document_outline, type: :boolean, default: false, desc: "Generate document outline"
93
+ option :media, type: :string, enum: %w[screen print], desc: "Emulate a CSS media type; screen prints the page with its screen styles. For its mobile layout, narrow the page: the layout width is --page_width minus the side margins, 9.525 cm with --margin_left 0 --margin_right 0 = 360 CSS px"
94
+ option :color_scheme, type: :string, enum: %w[light dark], desc: "Emulate prefers-color-scheme"
95
+ option :reduced_motion, type: :string, enum: %w[reduce no-preference], desc: "Emulate prefers-reduced-motion"
93
96
 
94
97
  class << self
95
98
  def exit_on_failure?
@@ -152,6 +155,9 @@ module Bidi2pdf
152
155
  option :json, type: :boolean, default: false, desc: "Emit a single structured JSON document (see `bidi2pdf schema diagnose`) instead of a human-readable summary"
153
156
  option :json_stream, type: :boolean, default: false, desc: "Emit one JSON progress event per line to stderr as diagnostics run, with or without --json (see `bidi2pdf schema event`)"
154
157
  option :screenshot, type: :string, desc: "Also capture a screenshot to this PNG file"
158
+ option :media, type: :string, enum: %w[screen print], desc: "Emulate a CSS media type; screen prints the page with its screen styles. For its mobile layout, narrow the page: the layout width is --page_width minus the side margins, 9.525 cm with --margin_left 0 --margin_right 0 = 360 CSS px"
159
+ option :color_scheme, type: :string, enum: %w[light dark], desc: "Emulate prefers-color-scheme"
160
+ option :reduced_motion, type: :string, enum: %w[reduce no-preference], desc: "Emulate prefers-reduced-motion"
155
161
  option :pdf, type: :string, desc: "Also render a PDF to this file and report its page count / blank-check"
156
162
 
157
163
  def diagnose
@@ -307,9 +313,11 @@ module Bidi2pdf
307
313
  emit_structured_render_output(result, collector)
308
314
 
309
315
  exit_for_result(result)
316
+ ensure
317
+ stop_browsers
310
318
  end
311
319
  ensure
312
- launcher.stop if defined?(@launcher) && @launcher
320
+ stop_browsers
313
321
  stream&.unsubscribe
314
322
  cleanup_stdin_tempfile
315
323
  end
@@ -369,9 +377,11 @@ module Bidi2pdf
369
377
  $stdout.puts(diagnose_payload(result, diagnostics).to_json)
370
378
 
371
379
  exit_for_result(result)
380
+ ensure
381
+ stop_browsers
372
382
  end
373
383
  ensure
374
- launcher.stop if defined?(@launcher) && @launcher
384
+ stop_browsers
375
385
  stream&.unsubscribe
376
386
  cleanup_stdin_tempfile
377
387
  end
@@ -413,7 +423,6 @@ module Bidi2pdf
413
423
  # --- run - Loader/Validator run before any browser work, both in --validate and in a real
414
424
  # run, so an invalid recipe never launches one.
415
425
 
416
- # rubocop:disable-next Metrics/CyclomaticComplexity
417
426
  def perform_human_run(recipe_path)
418
427
  recipe = load_and_validate_recipe(recipe_path)
419
428
  return puts "Recipe '#{recipe_path}' is valid." if merged_options[:validate]
@@ -448,12 +457,12 @@ module Bidi2pdf
448
457
  rescue Bidi2pdf::Error => e
449
458
  raise Thor::Error, e.message
450
459
  ensure
451
- @run_launcher&.stop
460
+ stop_browsers
452
461
  stream&.unsubscribe
453
462
  cleanup_stdin_tempfile
454
463
  end
455
464
 
456
- # rubocop:disable-next Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
465
+ # rubocop:disable-next Metrics/CyclomaticComplexity
457
466
  def perform_structured_run(recipe_path)
458
467
  recipe = load_and_validate_recipe(recipe_path)
459
468
 
@@ -490,12 +499,14 @@ module Bidi2pdf
490
499
  $stdout.puts(payload.to_json)
491
500
 
492
501
  exit_for_result(result)
502
+ ensure
503
+ stop_browsers
493
504
  end
494
505
  rescue Bidi2pdf::InvalidRecipeError, Bidi2pdf::PdfInspectionUnavailableError, Bidi2pdf::InvalidPrintOptionError => e
495
506
  $stdout.puts Bidi2pdf::Result.failure(command: "run", error: ErrorCodes.describe(e)).to_json
496
507
  exit(Bidi2pdf::ExitCodes.for(ErrorCodes.for(e)))
497
508
  ensure
498
- @run_launcher&.stop
509
+ stop_browsers
499
510
  stream&.unsubscribe
500
511
  cleanup_stdin_tempfile
501
512
  end
@@ -510,6 +521,22 @@ module Bidi2pdf
510
521
  recipe.source["url"] || recipe.source["file"] || "(stdin)"
511
522
  end
512
523
 
524
+ # Stops whatever browser this command started, once. The structured paths call it inside
525
+ # reserve_stdout_for_machine_output, while the loggers still write to stderr: stopping logs
526
+ # ("WebSocket closed"), and after the block those lines would land on stdout behind the JSON
527
+ # document or the PDF bytes. Each browser is stopped on its own, and a failing stop is logged,
528
+ # not raised: this runs in an ensure, where raising would replace the command's own result and
529
+ # exit status.
530
+ def stop_browsers
531
+ launchers = [(@launcher if defined?(@launcher)), (@run_launcher if defined?(@run_launcher))].compact
532
+ @launcher = @run_launcher = nil
533
+ launchers.each do |launcher|
534
+ launcher.stop
535
+ rescue StandardError => e
536
+ Bidi2pdf.logger.error "Stopping the browser failed: #{e.class}: #{e.message}"
537
+ end
538
+ end
539
+
513
540
  def with_recipe_tab(recipe)
514
541
  @run_launcher = launcher_for_recipe(recipe)
515
542
  tab = @run_launcher.diagnose
@@ -818,11 +845,18 @@ module Bidi2pdf
818
845
  wait_network_idle: merged_options[:wait_network_idle],
819
846
  print_options: print_options,
820
847
  network_log_format: merged_options[:network_log_format],
821
- chrome_args: chrome_args
848
+ chrome_args: chrome_args,
849
+ emulate_media: emulate_media_options
822
850
  )
823
851
  end
824
852
  end
825
853
 
854
+ # The --media/--color_scheme/--reduced_motion choices for BrowserTab#emulate_media; empty when none
855
+ # is given, so the browser keeps its own.
856
+ def emulate_media_options
857
+ { media: merged_options[:media], color_scheme: merged_options[:color_scheme], reduced_motion: merged_options[:reduced_motion] }.compact
858
+ end
859
+
826
860
  def configure
827
861
  Bidi2pdf.configure do |config|
828
862
  config.logger.level = log_level
@@ -35,45 +35,31 @@ module Bidi2pdf
35
35
  # @param [Hash] print_options Options for printing the page. Defaults to an empty hash.
36
36
  # @param [String, nil] remote_browser_url The URL of a remote browser to connect to. Defaults to nil.
37
37
  # @param [Symbol] network_log_format The format for network logs. Defaults to :console.
38
+ # @param [Hash] emulate_media Media type and features for BrowserTab#emulate_media (media:,
39
+ # color_scheme:, reduced_motion:). Defaults to none.
38
40
  class Launcher
39
41
  # rubocop:disable Metrics/ParameterLists
40
42
  def initialize(url:, inputfile:, output:, cookies:, headers:, auth:, headless: true, port: 0, wait_window_loaded: false,
41
43
  wait_network_idle: false, print_options: {}, remote_browser_url: nil, network_log_format: :console,
42
- chrome_args: Bidi::Session::DEFAULT_CHROME_ARGS)
43
- @url = url
44
- @inputfile = inputfile
44
+ chrome_args: Bidi::Session::DEFAULT_CHROME_ARGS, emulate_media: {})
45
+ # What both runners get, unchanged - SessionRunner's own keyword arguments.
46
+ @runner_options = {
47
+ url: url, inputfile: inputfile, output: output, cookies: cookies, headers: headers, auth: auth,
48
+ wait_window_loaded: wait_window_loaded, wait_network_idle: wait_network_idle, print_options: print_options || {},
49
+ network_log_format: network_log_format, emulate_media: emulate_media || {}
50
+ }
45
51
  @port = port
46
52
  @headless = headless
47
- @output = output
48
- @cookies = cookies
49
- @headers = headers
50
- @auth = auth
51
53
  @manager = nil
52
- @wait_window_loaded = wait_window_loaded
53
- @wait_network_idle = wait_network_idle
54
- @print_options = print_options || {}
55
54
  @remote_browser_url = remote_browser_url
56
55
  @custom_session = nil
57
- @network_log_format = network_log_format
58
56
  @chrome_args = chrome_args
59
57
  end
60
58
 
61
59
  # rubocop:enable Metrics/ParameterLists
62
60
 
63
61
  def launch
64
- runner = SessionRunner.new(
65
- session: session,
66
- url: @url,
67
- inputfile: @inputfile,
68
- output: @output,
69
- cookies: @cookies,
70
- headers: @headers,
71
- auth: @auth,
72
- wait_window_loaded: @wait_window_loaded,
73
- wait_network_idle: @wait_network_idle,
74
- print_options: @print_options,
75
- network_log_format: @network_log_format
76
- )
62
+ runner = SessionRunner.new(session: session, **@runner_options)
77
63
  runner.run
78
64
  end
79
65
 
@@ -83,19 +69,7 @@ module Bidi2pdf
83
69
  #
84
70
  # @return [Bidi2pdf::Bidi::BrowserTab] the navigated tab.
85
71
  def diagnose
86
- @diagnose_runner = SessionRunner.new(
87
- session: session,
88
- url: @url,
89
- inputfile: @inputfile,
90
- output: @output,
91
- cookies: @cookies,
92
- headers: @headers,
93
- auth: @auth,
94
- wait_window_loaded: @wait_window_loaded,
95
- wait_network_idle: @wait_network_idle,
96
- print_options: @print_options,
97
- network_log_format: @network_log_format
98
- )
72
+ @diagnose_runner = SessionRunner.new(session: session, **@runner_options)
99
73
  @diagnose_runner.run_diagnose
100
74
  end
101
75
 
@@ -90,6 +90,7 @@ module Bidi2pdf
90
90
  when "inject_style" then @tab.inject_style(url: opts["url"], content: opts["content"], id: opts["id"])
91
91
  when "set_viewport" then @tab.set_viewport(width: opts["width"], height: opts["height"], device_pixel_ratio: opts["device_pixel_ratio"])
92
92
  when "wait_network_idle" then @tab.wait_until_network_idle(timeout: opts.fetch("timeout", 10))
93
+ when "emulate_media" then @tab.emulate_media(media: opts["media"], color_scheme: opts["color_scheme"], reduced_motion: opts["reduced_motion"])
93
94
  end
94
95
  end
95
96
 
@@ -12,7 +12,7 @@ module Bidi2pdf
12
12
  # launches) -> Validator -> Runner.
13
13
  class Recipe
14
14
  KNOWN_TOP_LEVEL_KEYS = %w[version source browser headers cookies auth actions assert print output].freeze
15
- KNOWN_ACTIONS = %w[wait_for click evaluate inject_script inject_style set_viewport wait_network_idle].freeze
15
+ KNOWN_ACTIONS = %w[wait_for click evaluate inject_script inject_style set_viewport wait_network_idle emulate_media].freeze
16
16
  PAGE_ASSERTIONS = %w[selector_exists text_present no_console_errors no_network_failures fonts_loaded].freeze
17
17
  PDF_ASSERTIONS = %w[page_count pdf_text_present pdf_not_blank].freeze
18
18
  KNOWN_ASSERTIONS = (PAGE_ASSERTIONS + PDF_ASSERTIONS).freeze
@@ -219,7 +219,7 @@ module Bidi2pdf
219
219
  }.freeze
220
220
 
221
221
  RECIPE_ACTIONS = {
222
- "description" => "one of the 7 known actions - a thin dispatch over BrowserTab's own methods, see README's " \
222
+ "description" => "one of the 8 known actions - a thin dispatch over BrowserTab's own methods, see README's " \
223
223
  "Agent and Automation Usage section",
224
224
  "oneOf" => [
225
225
  {
@@ -271,6 +271,18 @@ module Bidi2pdf
271
271
  "type" => "object", "required" => %w[wait_network_idle], "additionalProperties" => false,
272
272
  "properties" => { "wait_network_idle" => { "type" => "object", "additionalProperties" => false,
273
273
  "properties" => { "timeout" => { "type" => "number" } } } }
274
+ },
275
+ {
276
+ "type" => "object", "required" => %w[emulate_media], "additionalProperties" => false,
277
+ "properties" => {
278
+ "emulate_media" => {
279
+ "type" => "object", "additionalProperties" => false,
280
+ "description" => "the CSS media type and media features the page is shown and printed with, from here on; " \
281
+ "media: screen prints the screen styles; on a narrow print page (layout width = page width minus the side margins, " \
282
+ "9.525 cm without side margins = 360 CSS px) the mobile layout",
283
+ "properties" => Bidi2pdf::Bidi::BrowserTab::EMULATED_MEDIA.to_h { |name, values| [name.to_s, { "type" => "string", "enum" => values }] }
284
+ }
285
+ }
274
286
  }
275
287
  ]
276
288
  }.freeze
@@ -33,10 +33,12 @@ module Bidi2pdf
33
33
  # @param [Boolean] wait_network_idle Whether to wait for the network to become idle. Defaults to false.
34
34
  # @param [Hash] print_options Options for printing the page. Defaults to an empty hash.
35
35
  # @param [Symbol] network_log_format The format for network logs. Defaults to :console.
36
+ # @param [Hash] emulate_media Media type and features for BrowserTab#emulate_media (media:,
37
+ # color_scheme:, reduced_motion:), applied before navigating. Defaults to none.
36
38
  class SessionRunner
37
39
  # rubocop: disable Metrics/ParameterLists
38
40
  def initialize(session:, url:, inputfile:, output:, cookies: {}, headers: {}, auth: {}, wait_window_loaded: false,
39
- wait_network_idle: false, print_options: {}, network_log_format: :console)
41
+ wait_network_idle: false, print_options: {}, network_log_format: :console, emulate_media: {})
40
42
  @session = session
41
43
  @url = url
42
44
  @inputfile = inputfile
@@ -48,6 +50,7 @@ module Bidi2pdf
48
50
  @wait_network_idle = wait_network_idle
49
51
  @print_options = print_options || {}
50
52
  @network_log_format = network_log_format
53
+ @emulate_media = emulate_media || {}
51
54
  end
52
55
 
53
56
  # rubocop: enable Metrics/ParameterLists
@@ -100,6 +103,7 @@ module Bidi2pdf
100
103
 
101
104
  add_headers
102
105
  add_basic_auth
106
+ @tab.emulate_media(**@emulate_media) if @emulate_media.any?
103
107
  end
104
108
 
105
109
  def add_cookies(tab)
@@ -157,11 +157,13 @@ module Bidi2pdf
157
157
  def configure
158
158
  @config = Configuration.new
159
159
  yield @config if block_given?
160
+ abandon_inherited_instance
160
161
  @instance&.shutdown
161
162
  # Cleared first: if the constructor below raises, a stale, already-shut-down instance must
162
163
  # not stay registered (it would keep serving cold slots but never warm again).
163
164
  @instance = nil
164
165
  @instance = new(@config, slot_factory: @config.slot_factory)
166
+ @instance_pid = Process.pid
165
167
  end
166
168
 
167
169
  # Returns the warmer's configuration, initializing defaults if needed.
@@ -197,9 +199,18 @@ module Bidi2pdf
197
199
  Bidi2pdf.logger.warn "session_warmer: error closing #{label}: #{e.message}"
198
200
  end
199
201
 
200
- # Returns the shared singleton warmer instance, creating it (and pre-warming it) on first call.
202
+ # Returns the shared singleton warmer instance, creating it (and pre-warming it) on first call -
203
+ # and in a forked child, its own one instead of the copy it inherited (see
204
+ # #abandon_inherited_instance).
201
205
  def instance
202
- @instance ||= new(config, slot_factory: config.slot_factory)
206
+ abandon_inherited_instance
207
+ @instance ||= new(config, slot_factory: config.slot_factory).tap { @instance_pid = Process.pid }
208
+ end
209
+
210
+ # Warms this process's own slots now - for a forked child (a Puma worker's on_worker_boot), so
211
+ # its first render does not pay for them. Without it the child warms on its first render.
212
+ def after_fork
213
+ instance
203
214
  end
204
215
 
205
216
  # Checks out a slot, yields a fresh tab for one render, then retires the slot.
@@ -210,17 +221,37 @@ module Bidi2pdf
210
221
  # Sweeps the remote chromedriver with the configured sweeper; nil when there is none (or no
211
222
  # warmer yet - this never creates one).
212
223
  def sweep!(reason: :manual)
224
+ abandon_inherited_instance
213
225
  @instance&.sweep!(reason: reason)
214
226
  end
215
227
 
216
- # Retires every currently-warm spare and resets the singleton.
228
+ # Retires every currently-warm spare and resets the singleton. In a forked child it only drops
229
+ # the inherited copy: those spares are the parent's.
217
230
  def shutdown
231
+ abandon_inherited_instance
218
232
  @instance&.shutdown
219
233
  @instance = nil
220
234
  end
221
235
 
222
236
  private
223
237
 
238
+ # The instance belongs to the process that created it. A forked child (a Puma worker - Rails
239
+ # boots the app, and with it this warmer, in the master before the fork) inherits a copy whose
240
+ # threads did not survive the fork and whose slots are its parent's, WebSocket connections
241
+ # included: a render on one sent its commands down the parent's socket, the parent's reader
242
+ # thread took the answers ("Unknown response"), and the child timed out. So the child lets go
243
+ # of its copy - closing only its own copies of the spare slots' sockets, never their sessions,
244
+ # which are its parent's (#release_after_fork) - and builds its own from the same
245
+ # configuration.
246
+ def abandon_inherited_instance
247
+ return if @instance.nil? || @instance_pid == Process.pid
248
+
249
+ inherited = @instance
250
+ @instance = nil
251
+ @instance_pid = nil
252
+ inherited.release_after_fork
253
+ end
254
+
224
255
  # Records each part in +parts+ the moment it exists, so #default_slot_factory's rescue can
225
256
  # retire exactly what was created so far. Mirrors Launcher#session's local/remote branch.
226
257
  def build_slot(config, parts)
@@ -250,6 +281,9 @@ module Bidi2pdf
250
281
  @slot_factory = slot_factory || self.class.default_slot_factory(config)
251
282
  @mutex = Mutex.new
252
283
  @available = []
284
+ # Every slot from its creation to its retirement - warm, out for a render, or in between - so a
285
+ # forked child can let go of all of them (#release_after_fork).
286
+ @live = []
253
287
  @replenish_threads = []
254
288
  @warming = 0
255
289
  @shutdown = false
@@ -262,6 +296,29 @@ module Bidi2pdf
262
296
  start_background_work
263
297
  end
264
298
 
299
+ # In a forked child, for the copy it inherited: closes the child's copies of the sockets of every
300
+ # slot the parent had - warm, out for a render, or between the two (being checked out, being
301
+ # retired) - locally (Session#release_after_fork: no close frame, no session end), and forgets the
302
+ # slots. The parent's sessions, its renders in flight, its leases and its threads are untouched.
303
+ # One slot that fails to release does not stop the others. The warmer itself is unusable
304
+ # afterwards - .instance builds the child its own.
305
+ #
306
+ # Not covered: a session still being built when the parent forked - between chromedriver's
307
+ # answer and #create_slot listing it, a fraction of a second. Its socket copy in the child is left
308
+ # to garbage collection. That needs a fork from a process that is building a slot on another
309
+ # thread at that moment; Puma's master never renders, so its forks do not meet it.
310
+ def release_after_fork
311
+ inherited = @live.dup
312
+ @available = []
313
+ @live = []
314
+ inherited.each do |slot|
315
+ session = slot[:session]
316
+ session.release_after_fork if session.respond_to?(:release_after_fork)
317
+ rescue StandardError => e
318
+ Bidi2pdf.logger.warn "session_warmer: releasing an inherited slot failed: #{e.message}"
319
+ end
320
+ end
321
+
265
322
  # Sweeps the remote chromedriver now - for an application that suspects leaked sessions.
266
323
  #
267
324
  # @return [ChromeSweeper::Result, nil] nil when no sweeper is configured.
@@ -381,7 +438,10 @@ module Bidi2pdf
381
438
  slot = new_slot
382
439
  id = session_id_of(slot)
383
440
  @registry&.hold(id)
384
- @mutex.synchronize { @own_sessions << id } if id
441
+ @mutex.synchronize do
442
+ @own_sessions << id if id
443
+ @live << slot
444
+ end
385
445
  slot
386
446
  end
387
447
 
@@ -563,7 +623,10 @@ module Bidi2pdf
563
623
  self.class.retire_slot(session: slot[:session], manager: slot[:manager])
564
624
  id = session_id_of(slot)
565
625
  @registry&.forget(id)
566
- @mutex.synchronize { @own_sessions.delete(id) }
626
+ @mutex.synchronize do
627
+ @own_sessions.delete(id)
628
+ @live.delete_if { |live| live.equal?(slot) }
629
+ end
567
630
  end
568
631
 
569
632
  def safe_close(label, &)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Bidi2pdf
4
- VERSION = "0.1.22"
4
+ VERSION = "0.1.24"
5
5
  end
@@ -56,6 +56,9 @@ module Bidi2pdf
56
56
 
57
57
  include JsLoggerHelper
58
58
 
59
+ # The values #emulate_media accepts, by argument - what Chrome's Emulation.setEmulatedMedia knows.
60
+ EMULATED_MEDIA: { media: ::Array["screen" | "print"], color_scheme: ::Array["light" | "dark"], reduced_motion: ::Array["reduce" | "no-preference"] }
61
+
59
62
  # @return [Object] The WebSocket client.
60
63
  attr_reader client: untyped
61
64
 
@@ -238,8 +241,28 @@ module Bidi2pdf
238
241
  # @param [Boolean] disabled Defaults to true.
239
242
  def disable_script_execution: (?disabled: bool) -> untyped
240
243
 
244
+ # Emulates a CSS media type and media features for this tab, through Chrome's own
245
+ # Emulation.setEmulatedMedia (CDP, via goog:cdp.sendCommand). It holds for every later
246
+ # navigation in the tab and for printing: +media: "screen"+ prints a page with its screen styles
247
+ # instead of its print stylesheet, +color_scheme: "dark"+ in its dark mode. On a narrow page the
248
+ # screen media type prints a page's mobile layout: the layout width is the page width minus the
249
+ # side margins (Chrome's default is 1 cm each), at 96 / 2.54 CSS px per cm - e.g.
250
+ # +page: { width: 9.525 }, margin: { left: 0, right: 0 }+ lays out at 360 px. Each call replaces
251
+ # the previous emulation, so a media type or feature it omits is reset; a call without arguments
252
+ # ends it.
253
+ #
254
+ # @param [String, Symbol, nil] media "screen" or "print"; nil leaves it to the browser.
255
+ # @param [String, Symbol, nil] color_scheme "light" or "dark" (prefers-color-scheme).
256
+ # @param [String, Symbol, nil] reduced_motion "reduce" or "no-preference" (prefers-reduced-motion).
257
+ # @raise [ArgumentError] for a value Chrome does not know, before anything is sent.
258
+ def emulate_media: (?media: untyped?, ?color_scheme: untyped?, ?reduced_motion: untyped?) -> untyped
259
+
241
260
  private
242
261
 
262
+ def emulated_media_params: (**untyped values) -> { media: untyped, features: untyped }
263
+
264
+ def check_emulated_media: (untyped name, untyped value) -> (nil | untyped)
265
+
243
266
  def build_command_and_extractor: (untyped print_options) -> ::Array[untyped]
244
267
 
245
268
  def cdp_session: () -> untyped
@@ -51,6 +51,12 @@ module Bidi2pdf
51
51
  # nor be killed before :close has been emitted.
52
52
  def close: (?untyped? error) -> untyped
53
53
 
54
+ # In a forked child: drops this process's copy of a connection the parent opened, without a word
55
+ # to the peer - no close frame, no TLS close_notify (the underlying TCP socket is closed, not the
56
+ # SSL one), no :close event - so the parent goes on using it. Closing a descriptor the parent also
57
+ # holds ends nothing for the peer; the reader thread did not survive the fork.
58
+ def release_after_fork: () -> untyped
59
+
54
60
  def open?: () -> untyped
55
61
 
56
62
  def closed?: () -> untyped
@@ -114,6 +114,9 @@ module Bidi2pdf
114
114
  def remove_event_listener: (*untyped names, untyped listener) -> untyped
115
115
 
116
116
  # Closes the WebSocket connection.
117
+ # In a forked child: lets go of the parent's connection locally (BufferedWebSocketClient#release_after_fork).
118
+ def release_after_fork: () -> untyped
119
+
117
120
  def close: () -> (nil | untyped)
118
121
 
119
122
  private
@@ -101,6 +101,10 @@ module Bidi2pdf
101
101
  # @return [String] The WebSocket URL.
102
102
  def websocket_url: () -> untyped
103
103
 
104
+ # In a forked child: drops this process's copies of the parent's connections - the command client
105
+ # and the event socket - without ending the session, which is the parent's (see #close for that).
106
+ def release_after_fork: () -> untyped
107
+
104
108
  private
105
109
 
106
110
  # Sends a command to the WebSocket client.
data/sig/bidi2pdf/cli.rbs CHANGED
@@ -1,6 +1,8 @@
1
1
  module Bidi2pdf
2
2
  # rubocop:disable Metrics/AbcSize
3
3
  class CLI < Thor
4
+ @launcher: untyped
5
+
4
6
  @run_launcher: untyped
5
7
 
6
8
  @render_input_path: untyped
@@ -9,8 +11,6 @@ module Bidi2pdf
9
11
 
10
12
  @stdin_tempfile: untyped
11
13
 
12
- @launcher: untyped
13
-
14
14
  include JsonOutput
15
15
 
16
16
  include SessionCommands
@@ -55,16 +55,23 @@ module Bidi2pdf
55
55
 
56
56
  def capture_diagnose_pdf: (untyped tab) -> (nil | { path: untyped, pages: untyped, not_blank: untyped })
57
57
 
58
- # rubocop:disable-next Metrics/CyclomaticComplexity
59
58
  def perform_human_run: (untyped recipe_path) -> untyped
60
59
 
61
- # rubocop:disable-next Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
60
+ # rubocop:disable-next Metrics/CyclomaticComplexity
62
61
  def perform_structured_run: (untyped recipe_path) -> untyped
63
62
 
64
63
  def load_and_validate_recipe: (untyped recipe_path) -> untyped
65
64
 
66
65
  def recipe_requested_url: (untyped recipe) -> untyped
67
66
 
67
+ # Stops whatever browser this command started, once. The structured paths call it inside
68
+ # reserve_stdout_for_machine_output, while the loggers still write to stderr: stopping logs
69
+ # ("WebSocket closed"), and after the block those lines would land on stdout behind the JSON
70
+ # document or the PDF bytes. Each browser is stopped on its own, and a failing stop is logged,
71
+ # not raised: this runs in an ensure, where raising would replace the command's own result and
72
+ # exit status.
73
+ def stop_browsers: () -> untyped
74
+
68
75
  def with_recipe_tab: (untyped recipe) { (untyped) -> untyped } -> untyped
69
76
 
70
77
  # A failing action/assertion raises Recipe::Runner::StepFailure (its own entries plus the real
@@ -144,6 +151,10 @@ module Bidi2pdf
144
151
 
145
152
  def launcher: () -> untyped
146
153
 
154
+ # The --media/--color_scheme/--reduced_motion choices for BrowserTab#emulate_media; empty when none
155
+ # is given, so the browser keeps its own.
156
+ def emulate_media_options: () -> untyped
157
+
147
158
  def configure: () -> untyped
148
159
 
149
160
  def log_level: () -> untyped
@@ -29,43 +29,28 @@ module Bidi2pdf
29
29
  # @param [Hash] print_options Options for printing the page. Defaults to an empty hash.
30
30
  # @param [String, nil] remote_browser_url The URL of a remote browser to connect to. Defaults to nil.
31
31
  # @param [Symbol] network_log_format The format for network logs. Defaults to :console.
32
+ # @param [Hash] emulate_media Media type and features for BrowserTab#emulate_media (media:,
33
+ # color_scheme:, reduced_motion:). Defaults to none.
32
34
  class Launcher
33
- @url: untyped
34
-
35
- @inputfile: untyped
35
+ # What both runners get, unchanged - SessionRunner's own keyword arguments.
36
+ @runner_options: untyped
36
37
 
37
38
  @port: untyped
38
39
 
39
40
  @headless: untyped
40
41
 
41
- @output: untyped
42
-
43
- @cookies: untyped
44
-
45
- @headers: untyped
46
-
47
- @auth: untyped
48
-
49
42
  @manager: untyped
50
43
 
51
- @wait_window_loaded: untyped
52
-
53
- @wait_network_idle: untyped
54
-
55
- @print_options: untyped
56
-
57
44
  @remote_browser_url: untyped
58
45
 
59
46
  @custom_session: untyped
60
47
 
61
- @network_log_format: untyped
62
-
63
48
  @chrome_args: untyped
64
49
 
65
50
  @diagnose_runner: untyped
66
51
 
67
52
  # rubocop:disable Metrics/ParameterLists
68
- def initialize: (url: untyped, inputfile: untyped, output: untyped, cookies: untyped, headers: untyped, auth: untyped, ?headless: bool, ?port: ::Integer, ?wait_window_loaded: bool, ?wait_network_idle: bool, ?print_options: ::Hash[untyped, untyped], ?remote_browser_url: untyped?, ?network_log_format: ::Symbol, ?chrome_args: untyped) -> void
53
+ def initialize: (url: untyped, inputfile: untyped, output: untyped, cookies: untyped, headers: untyped, auth: untyped, ?headless: bool, ?port: ::Integer, ?wait_window_loaded: bool, ?wait_network_idle: bool, ?print_options: ::Hash[untyped, untyped], ?remote_browser_url: untyped?, ?network_log_format: ::Symbol, ?chrome_args: untyped, ?emulate_media: ::Hash[untyped, untyped]) -> void
69
54
 
70
55
  def launch: () -> untyped
71
56
 
@@ -10,7 +10,7 @@ module Bidi2pdf
10
10
 
11
11
  KNOWN_TOP_LEVEL_KEYS: ::Array["version" | "source" | "browser" | "headers" | "cookies" | "auth" | "actions" | "assert" | "print" | "output"]
12
12
 
13
- KNOWN_ACTIONS: ::Array["wait_for" | "click" | "evaluate" | "inject_script" | "inject_style" | "set_viewport" | "wait_network_idle"]
13
+ KNOWN_ACTIONS: ::Array["wait_for" | "click" | "evaluate" | "inject_script" | "inject_style" | "set_viewport" | "wait_network_idle" | "emulate_media"]
14
14
 
15
15
  PAGE_ASSERTIONS: ::Array["selector_exists" | "text_present" | "no_console_errors" | "no_network_failures" | "fonts_loaded"]
16
16
 
@@ -30,7 +30,7 @@ module Bidi2pdf
30
30
 
31
31
  RECIPE_SOURCE: { "description" => "exactly one of url, file, stdin", "oneOf" => ::Array[{ "type" => "object", "required" => ::Array["url"], "properties" => { "url" => { "type" => "string" } }, "additionalProperties" => false } | { "type" => "object", "required" => ::Array["file"], "properties" => { "file" => { "type" => "string" } }, "additionalProperties" => false } | { "type" => "object", "required" => ::Array["stdin"], "properties" => { "stdin" => { "const" => true } }, "additionalProperties" => false }] }
32
32
 
33
- RECIPE_ACTIONS: { "description" => "one of the 7 known actions - a thin dispatch over BrowserTab's own methods, see README's Agent and Automation Usage section", "oneOf" => ::Array[{ "type" => "object", "required" => ::Array["wait_for"], "additionalProperties" => false, "properties" => { "wait_for" => { "type" => "object", "description" => "exactly one of selector, paged_js, script; timeout is always optional", "oneOf" => ::Array[{ "type" => "object", "required" => ::Array["selector"], "additionalProperties" => false, "properties" => { "selector" => { "type" => "string" }, "timeout" => { "type" => "number" } } } | { "type" => "object", "required" => ::Array["paged_js"], "additionalProperties" => false, "properties" => { "paged_js" => { "type" => "boolean" }, "timeout" => { "type" => "number" } } } | { "type" => "object", "required" => ::Array["script"], "additionalProperties" => false, "properties" => { "script" => { "type" => "string" }, "timeout" => { "type" => "number" } } }] } } } | { "type" => "object", "required" => ::Array["click"], "additionalProperties" => false, "properties" => { "click" => { "type" => "object", "required" => ::Array["selector"], "additionalProperties" => false, "properties" => { "selector" => { "type" => "string" } } } } } | { "type" => "object", "required" => ::Array["evaluate"], "additionalProperties" => false, "properties" => { "evaluate" => { "type" => "object", "required" => ::Array["script"], "additionalProperties" => false, "properties" => { "script" => { "type" => "string" }, "assign" => { "type" => "string" } } } } } | { "type" => "object", "required" => ::Array["inject_script"], "additionalProperties" => false, "properties" => { "inject_script" => { "type" => "object", "additionalProperties" => false, "properties" => { "url" => { "type" => "string" }, "content" => { "type" => "string" }, "id" => { "type" => "string" } } } } } | { "type" => "object", "required" => ::Array["inject_style"], "additionalProperties" => false, "properties" => { "inject_style" => { "type" => "object", "additionalProperties" => false, "properties" => { "url" => { "type" => "string" }, "content" => { "type" => "string" }, "id" => { "type" => "string" } } } } } | { "type" => "object", "required" => ::Array["set_viewport"], "additionalProperties" => false, "properties" => { "set_viewport" => { "type" => "object", "required" => ::Array["width" | "height"], "additionalProperties" => false, "properties" => { "width" => { "type" => "number" }, "height" => { "type" => "number" }, "device_pixel_ratio" => { "type" => "number" } } } } } | { "type" => "object", "required" => ::Array["wait_network_idle"], "additionalProperties" => false, "properties" => { "wait_network_idle" => { "type" => "object", "additionalProperties" => false, "properties" => { "timeout" => { "type" => "number" } } } } }] }
33
+ RECIPE_ACTIONS: { "description" => "one of the 8 known actions - a thin dispatch over BrowserTab's own methods, see README's Agent and Automation Usage section", "oneOf" => ::Array[{ "type" => "object", "required" => ::Array["wait_for"], "additionalProperties" => false, "properties" => { "wait_for" => { "type" => "object", "description" => "exactly one of selector, paged_js, script; timeout is always optional", "oneOf" => ::Array[{ "type" => "object", "required" => ::Array["selector"], "additionalProperties" => false, "properties" => { "selector" => { "type" => "string" }, "timeout" => { "type" => "number" } } } | { "type" => "object", "required" => ::Array["paged_js"], "additionalProperties" => false, "properties" => { "paged_js" => { "type" => "boolean" }, "timeout" => { "type" => "number" } } } | { "type" => "object", "required" => ::Array["script"], "additionalProperties" => false, "properties" => { "script" => { "type" => "string" }, "timeout" => { "type" => "number" } } }] } } } | { "type" => "object", "required" => ::Array["click"], "additionalProperties" => false, "properties" => { "click" => { "type" => "object", "required" => ::Array["selector"], "additionalProperties" => false, "properties" => { "selector" => { "type" => "string" } } } } } | { "type" => "object", "required" => ::Array["evaluate"], "additionalProperties" => false, "properties" => { "evaluate" => { "type" => "object", "required" => ::Array["script"], "additionalProperties" => false, "properties" => { "script" => { "type" => "string" }, "assign" => { "type" => "string" } } } } } | { "type" => "object", "required" => ::Array["inject_script"], "additionalProperties" => false, "properties" => { "inject_script" => { "type" => "object", "additionalProperties" => false, "properties" => { "url" => { "type" => "string" }, "content" => { "type" => "string" }, "id" => { "type" => "string" } } } } } | { "type" => "object", "required" => ::Array["inject_style"], "additionalProperties" => false, "properties" => { "inject_style" => { "type" => "object", "additionalProperties" => false, "properties" => { "url" => { "type" => "string" }, "content" => { "type" => "string" }, "id" => { "type" => "string" } } } } } | { "type" => "object", "required" => ::Array["set_viewport"], "additionalProperties" => false, "properties" => { "set_viewport" => { "type" => "object", "required" => ::Array["width" | "height"], "additionalProperties" => false, "properties" => { "width" => { "type" => "number" }, "height" => { "type" => "number" }, "device_pixel_ratio" => { "type" => "number" } } } } } | { "type" => "object", "required" => ::Array["wait_network_idle"], "additionalProperties" => false, "properties" => { "wait_network_idle" => { "type" => "object", "additionalProperties" => false, "properties" => { "timeout" => { "type" => "number" } } } } } | { "type" => "object", "required" => ::Array["emulate_media"], "additionalProperties" => false, "properties" => { "emulate_media" => { "type" => "object", "additionalProperties" => false, "description" => "the CSS media type and media features the page is shown and printed with, from here on; media: screen prints the screen styles; on a narrow print page (layout width = page width minus the side margins, 9.525 cm without side margins = 360 CSS px) the mobile layout", "properties" => untyped } } }] }
34
34
 
35
35
  RECIPE_ASSERT: { "description" => "one of the 8 known assertions. The presence-only ones (no_console_errors, no_network_failures, fonts_loaded, pdf_not_blank) never have their value read at run time - Recipe::Runner only checks the key is there - so they must be written as `true`; `false` or any other value is rejected as misleading rather than silently ignored. The last 3 assertions also require the pdf-reader gem at --validate time - a runtime fact this schema cannot express, see the top-level description", "oneOf" => ::Array[{ "type" => "object", "required" => ::Array["selector_exists"], "additionalProperties" => false, "properties" => { "selector_exists" => { "type" => "object", "required" => ::Array["selector"], "additionalProperties" => false, "properties" => { "selector" => { "type" => "string" } } } } } | { "type" => "object", "required" => ::Array["text_present"], "additionalProperties" => false, "properties" => { "text_present" => { "type" => "object", "required" => ::Array["text"], "additionalProperties" => false, "properties" => { "text" => { "type" => "string" } } } } } | { "type" => "object", "required" => ::Array["no_console_errors"], "additionalProperties" => false, "properties" => { "no_console_errors" => { "const" => true } } } | { "type" => "object", "required" => ::Array["no_network_failures"], "additionalProperties" => false, "properties" => { "no_network_failures" => { "const" => true } } } | { "type" => "object", "required" => ::Array["fonts_loaded"], "additionalProperties" => false, "properties" => { "fonts_loaded" => { "const" => true } } } | { "type" => "object", "required" => ::Array["page_count"], "additionalProperties" => false, "properties" => { "page_count" => { "oneOf" => ::Array[{ "type" => "integer" } | { "type" => "object", "properties" => { "min" => { "type" => "integer" }, "max" => { "type" => "integer" } }, "additionalProperties" => false }] } } } | { "type" => "object", "required" => ::Array["pdf_text_present"], "additionalProperties" => false, "properties" => { "pdf_text_present" => { "type" => "object", "required" => ::Array["text"], "additionalProperties" => false, "properties" => { "text" => { "type" => "string" } } } } } | { "type" => "object", "required" => ::Array["pdf_not_blank"], "additionalProperties" => false, "properties" => { "pdf_not_blank" => { "const" => true } } }] }
36
36
 
@@ -31,6 +31,8 @@ module Bidi2pdf
31
31
  # @param [Boolean] wait_network_idle Whether to wait for the network to become idle. Defaults to false.
32
32
  # @param [Hash] print_options Options for printing the page. Defaults to an empty hash.
33
33
  # @param [Symbol] network_log_format The format for network logs. Defaults to :console.
34
+ # @param [Hash] emulate_media Media type and features for BrowserTab#emulate_media (media:,
35
+ # color_scheme:, reduced_motion:), applied before navigating. Defaults to none.
34
36
  class SessionRunner
35
37
  @session: untyped
36
38
 
@@ -54,6 +56,8 @@ module Bidi2pdf
54
56
 
55
57
  @network_log_format: untyped
56
58
 
59
+ @emulate_media: untyped
60
+
57
61
  @window: untyped
58
62
 
59
63
  @tab: untyped
@@ -63,7 +67,7 @@ module Bidi2pdf
63
67
  @uri: untyped
64
68
 
65
69
  # rubocop: disable Metrics/ParameterLists
66
- def initialize: (session: untyped, url: untyped, inputfile: untyped, output: untyped, ?cookies: ::Hash[untyped, untyped], ?headers: ::Hash[untyped, untyped], ?auth: ::Hash[untyped, untyped], ?wait_window_loaded: bool, ?wait_network_idle: bool, ?print_options: ::Hash[untyped, untyped], ?network_log_format: ::Symbol) -> void
70
+ def initialize: (session: untyped, url: untyped, inputfile: untyped, output: untyped, ?cookies: ::Hash[untyped, untyped], ?headers: ::Hash[untyped, untyped], ?auth: ::Hash[untyped, untyped], ?wait_window_loaded: bool, ?wait_network_idle: bool, ?print_options: ::Hash[untyped, untyped], ?network_log_format: ::Symbol, ?emulate_media: ::Hash[untyped, untyped]) -> void
67
71
 
68
72
  def run: () -> untyped
69
73
 
@@ -26,6 +26,8 @@ module Bidi2pdf
26
26
  # not stay registered (it would keep serving cold slots but never warm again).
27
27
  self.@instance: untyped
28
28
 
29
+ self.@instance_pid: untyped
30
+
29
31
  @config: untyped
30
32
 
31
33
  @slot_factory: untyped
@@ -34,6 +36,10 @@ module Bidi2pdf
34
36
 
35
37
  @available: untyped
36
38
 
39
+ # Every slot from its creation to its retirement - warm, out for a render, or in between - so a
40
+ # forked child can let go of all of them (#release_after_fork).
41
+ @live: untyped
42
+
37
43
  @replenish_threads: untyped
38
44
 
39
45
  @warming: untyped
@@ -180,9 +186,15 @@ module Bidi2pdf
180
186
 
181
187
  def self.safe_close: (untyped label) { () -> untyped } -> untyped
182
188
 
183
- # Returns the shared singleton warmer instance, creating it (and pre-warming it) on first call.
189
+ # Returns the shared singleton warmer instance, creating it (and pre-warming it) on first call -
190
+ # and in a forked child, its own one instead of the copy it inherited (see
191
+ # #abandon_inherited_instance).
184
192
  def self.instance: () -> untyped
185
193
 
194
+ # Warms this process's own slots now - for a forked child (a Puma worker's on_worker_boot), so
195
+ # its first render does not pay for them. Without it the child warms on its first render.
196
+ def self.after_fork: () -> untyped
197
+
186
198
  # Checks out a slot, yields a fresh tab for one render, then retires the slot.
187
199
  def self.with_tab: () { (?) -> untyped } -> untyped
188
200
 
@@ -190,11 +202,22 @@ module Bidi2pdf
190
202
  # warmer yet - this never creates one).
191
203
  def self.sweep!: (?reason: ::Symbol) -> untyped
192
204
 
193
- # Retires every currently-warm spare and resets the singleton.
205
+ # Retires every currently-warm spare and resets the singleton. In a forked child it only drops
206
+ # the inherited copy: those spares are the parent's.
194
207
  def self.shutdown: () -> untyped
195
208
 
196
209
  private
197
210
 
211
+ # The instance belongs to the process that created it. A forked child (a Puma worker - Rails
212
+ # boots the app, and with it this warmer, in the master before the fork) inherits a copy whose
213
+ # threads did not survive the fork and whose slots are its parent's, WebSocket connections
214
+ # included: a render on one sent its commands down the parent's socket, the parent's reader
215
+ # thread took the answers ("Unknown response"), and the child timed out. So the child lets go
216
+ # of its copy - closing only its own copies of the spare slots' sockets, never their sessions,
217
+ # which are its parent's (#release_after_fork) - and builds its own from the same
218
+ # configuration.
219
+ def self.abandon_inherited_instance: () -> (nil | untyped)
220
+
198
221
  # Records each part in +parts+ the moment it exists, so #default_slot_factory's rescue can
199
222
  # retire exactly what was created so far. Mirrors Launcher#session's local/remote branch.
200
223
  def self.build_slot: (untyped config, untyped parts) -> { session: untyped, browser: untyped, manager: untyped }
@@ -207,6 +230,19 @@ module Bidi2pdf
207
230
 
208
231
  def initialize: (untyped config, ?slot_factory: untyped?) -> void
209
232
 
233
+ # In a forked child, for the copy it inherited: closes the child's copies of the sockets of every
234
+ # slot the parent had - warm, out for a render, or between the two (being checked out, being
235
+ # retired) - locally (Session#release_after_fork: no close frame, no session end), and forgets the
236
+ # slots. The parent's sessions, its renders in flight, its leases and its threads are untouched.
237
+ # One slot that fails to release does not stop the others. The warmer itself is unusable
238
+ # afterwards - .instance builds the child its own.
239
+ #
240
+ # Not covered: a session still being built when the parent forked - between chromedriver's
241
+ # answer and #create_slot listing it, a fraction of a second. Its socket copy in the child is left
242
+ # to garbage collection. That needs a fork from a process that is building a slot on another
243
+ # thread at that moment; Puma's master never renders, so its forks do not meet it.
244
+ def release_after_fork: () -> untyped
245
+
210
246
  # Sweeps the remote chromedriver now - for an application that suspects leaked sessions.
211
247
  #
212
248
  # @return [ChromeSweeper::Result, nil] nil when no sweeper is configured.
@@ -1,3 +1,3 @@
1
1
  module Bidi2pdf
2
- VERSION: "0.1.22"
2
+ VERSION: "0.1.24"
3
3
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: bidi2pdf
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.22
4
+ version: 0.1.24
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dieter S.