vectory 0.13.2 → 0.13.4

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: f57a3fbf7c5b0f3c7660e32dbd1f6361d149ee27a9eef68418ced42ab0d4416b
4
- data.tar.gz: 0e6dcda6b904e457b75ee3091ee27f91c6790da056f289003f289f585a66148b
3
+ metadata.gz: 809155cb1687db89170886bfaf647690e3aaadd430137a8c117d9e18190514a5
4
+ data.tar.gz: c24754f16c265fe36c352a2e3908331280652ba4a0301d916cf1d15de072d4fc
5
5
  SHA512:
6
- metadata.gz: bdd45abe6b12a83b16d04a63fca16fa3052552909ac1a16de73623706d0b2ee8dd84a958baec8e60e14c6d4b4037c6832ec55abddda3acb94b971cd5bbbbe206
7
- data.tar.gz: 9761d2d5b4169f87fbbc46555ac74ab8d3d43ad80260aadd07bc6a77aa7d0c6ea564854bef42f70b02a383a1647610a1770af8d200a43881a91001386bec2f3d
6
+ metadata.gz: 7a6d4223ea9c84a0c9cec02be8c017d2f28a0fdbfad54b673901f73981e7e6d9cba66156e54a5e6798a8a7212469a81eefe100b215e84e0de75af550232729a8
7
+ data.tar.gz: 000b1c27e0e55f8bae132b2dbc5fb73ffa320f316d04a658645c0bcf473d893b0e7405d2b0ab57eace0ac38e138f36dd751738280f5a84817b5e145f78fcfe9b
@@ -9,7 +9,7 @@ on:
9
9
  pull_request:
10
10
 
11
11
  permissions:
12
- contents: write
12
+ contents: read
13
13
  packages: read
14
14
 
15
15
  jobs:
@@ -20,5 +20,29 @@ jobs:
20
20
  submodules: true
21
21
  choco-cache: true
22
22
  private-fonts: false
23
+ cascade: false
23
24
  secrets:
24
25
  pat_token: ${{ secrets.CLARICLE_CI_PAT_TOKEN }}
26
+
27
+ tests-passed:
28
+ needs: rake
29
+ runs-on: ubuntu-latest
30
+ permissions:
31
+ contents: write
32
+ steps:
33
+ - name: Tests passed
34
+ uses: peter-evans/repository-dispatch@v3
35
+ with:
36
+ token: ${{ secrets.CLARICLE_CI_PAT_TOKEN || github.token }}
37
+ repository: ${{ github.repository }}
38
+ event-type: tests-passed
39
+ client-payload: '{"ref": "${{ github.ref }}", "sha": "${{ github.sha }}", "type": "tests-passed"}'
40
+
41
+ - if: startsWith(github.ref, 'refs/tags/v')
42
+ name: Repository ready for release
43
+ uses: peter-evans/repository-dispatch@v3
44
+ with:
45
+ token: ${{ secrets.CLARICLE_CI_PAT_TOKEN || github.token }}
46
+ repository: ${{ github.repository }}
47
+ event-type: do-release
48
+ client-payload: '{"ref": "${{ github.ref }}", "sha": "${{ github.sha }}", "type": "do-release"}'
@@ -20,6 +20,7 @@ on:
20
20
  permissions:
21
21
  contents: write
22
22
  id-token: write
23
+ pull-requests: write
23
24
 
24
25
  concurrency:
25
26
  group: release
data/Gemfile CHANGED
@@ -7,11 +7,13 @@ gemspec
7
7
 
8
8
  gem "canon", "~> 0.1.7"
9
9
  gem "connection_pool", "~> 2.0"
10
+ gem "nokogiri" # dev-only: exercises SvgMapping's duck-typed document-object input (metanorma passes Nokogiri docs)
10
11
  gem "openssl", "~> 3.0"
11
12
  gem "rake"
12
- gem "nokogiri" # dev-only: exercises SvgMapping's duck-typed document-object input (metanorma passes Nokogiri docs)
13
13
  gem "rspec"
14
14
  gem "rubocop"
15
15
  gem "rubocop-performance"
16
16
  gem "rubocop-rake"
17
17
  gem "rubocop-rspec"
18
+
19
+ gem "png_conform", "~> 0.1.5", group: :test
data/README.adoc CHANGED
@@ -9,7 +9,7 @@ image:https://img.shields.io/github/commits-since/metanorma/vectory/latest.svg["
9
9
  == Purpose
10
10
 
11
11
  Vectory is a Ruby gem that performs pairwise vector image conversions for common
12
- vector image formats (EPS, PS, EMF, SVG).
12
+ vector image formats (EPS, PS, EMF, SVG), with PNG output from each format.
13
13
 
14
14
  [quote]
15
15
  ____
@@ -21,12 +21,27 @@ ____
21
21
 
22
22
  === Prerequisites
23
23
 
24
- Vectory ships as a pure-Ruby gem. Format support is provided by these Ruby gems (installed automatically):
24
+ Vectory is written in Ruby. Format support is provided by these gems
25
+ (installed automatically):
25
26
 
26
27
  * https://github.com/claricle/emfsvg[emfsvg] (EMF <-> SVG)
27
28
  * https://github.com/claricle/postsvg[postsvg] (PS/EPS <-> SVG)
29
+ * `svgpng ~> 0.1.0` (SVG -> PNG)
28
30
 
29
- No external binaries are required.
31
+ PNG rendering uses the prebuilt native artifact in the platform-specific
32
+ `svgpng` package; it requires no separately installed renderer or compiler.
33
+ The supported native targets are `arm64-darwin`, `x86_64-darwin`,
34
+ `x86_64-linux`, `aarch64-linux`, `x86_64-linux-musl`,
35
+ `aarch64-linux-musl`, and `x64-mingw-ucrt`.
36
+
37
+ On other platforms, RubyGems selects the same-version `ruby` shell package.
38
+ Existing non-PNG conversions remain available. Requesting PNG raises
39
+ `Vectory::UnsupportedPlatformError` (CLI exit status 5). The renderer is loaded
40
+ only when PNG output is requested.
41
+
42
+ NOTE: The PNG integration is under development. Its dependency must not be
43
+ released with Vectory until the tested seven native packages and the `ruby`
44
+ shell package are published together.
30
45
 
31
46
 
32
47
  === Gem install
@@ -48,13 +63,52 @@ $ vectory [-o {output-file-name}] -f {format} {input-file-name}
48
63
 
49
64
  Where,
50
65
 
51
- `format`:: the desired output format (one of: `svg`, `eps`, `ps`, `emf`)
66
+ `format`:: the desired output format (one of: `svg`, `eps`, `ps`, `emf`, `png`)
52
67
  `input-file-name`:: file path to the input file
53
68
  `output-file-name`:: file path to the desired output file (with the
54
69
  file extension) (default: writes to a current directory by the input filename
55
70
  with an extension changed to a desired format)
56
71
 
57
72
 
73
+ === PNG output
74
+
75
+ PNG is output-only. SVG, EMF, EPS, and PS inputs can be converted to PNG:
76
+
77
+ [source,sh]
78
+ ----
79
+ vectory -f png -o diagram.png --width 1200 --background '#ffffff' diagram.svg
80
+ vectory -f png --font 'Example Sans=fonts/ExampleSans-Regular.ttf' \
81
+ --font 'Example Sans=fonts/ExampleSans-Bold.ttf' \
82
+ --fallback-font 'Example Symbols=fonts/ExampleSymbols.ttf' \
83
+ --fallback-font 'Example CJK=fonts/ExampleCJK.otf' diagram.emf
84
+ ----
85
+
86
+ `--font FAMILY=PATH` is repeatable. Repeat a family to supply distinct
87
+ style, weight, or stretch faces. `--fallback-font FAMILY=PATH` is also repeatable;
88
+ fallback faces are tried in the order supplied. FAMILY must be the font's own
89
+ family name, for example `Arial` for Arial.ttf. Fonts are read explicitly from
90
+ these paths; the renderer does not search system fonts. A text-free image needs
91
+ no font options. Font substitution warnings are printed once each to stderr in
92
+ renderer order, separately from the binary output file.
93
+
94
+ These options are valid only with `-f png`:
95
+
96
+ `--width PIXELS`, `--height PIXELS`:: Positive integer output dimensions. One
97
+ specified dimension preserves the source aspect ratio. Both dimensions set the
98
+ canvas size, fitting and centering the image without changing its aspect ratio.
99
+ `--scale NUMBER`:: Positive decimal scale applied to intrinsic dimensions.
100
+ Cannot be combined with width or height.
101
+ `--background COLOR`:: `transparent` (the default), `#RRGGBB`, or `#RRGGBBAA`.
102
+ Quote hexadecimal colors in shell commands.
103
+ `--font FAMILY=PATH`, `--fallback-font FAMILY=PATH`:: Explicit font faces and
104
+ ordered fallbacks as described above.
105
+
106
+ Without size options, the renderer uses the SVG's intrinsic dimensions, then its
107
+ `viewBox`, with a 300 by 150 default. A DOCTYPE with an internal `[...]` subset
108
+ is rejected before XML parsing; a plain DOCTYPE, as SVG editors write it, is
109
+ accepted and its external DTD is never loaded. External resources cannot be
110
+ enabled through a CLI option.
111
+
58
112
  === Using the Ruby library
59
113
 
60
114
  Some examples:
@@ -89,6 +143,137 @@ Vectory::Datauri.new(uri).to_vector.to_emf.to_uri.content
89
143
  ----
90
144
 
91
145
 
146
+ ==== Binary PNG results
147
+
148
+ `to_png` returns a `Vectory::Png` from any supported vector class. Pass explicit
149
+ font and fallback collections, including empty collections for text-free SVG:
150
+
151
+ [source,ruby]
152
+ ----
153
+ require "vectory"
154
+
155
+ svg = Vectory::Svg.from_path("diagram.svg")
156
+ png = svg.to_png(profile: { width: 1200, background: "#ffffff" },
157
+ fonts: {}, fallback_fonts: [])
158
+
159
+ png.content # binary PNG bytes (ASCII-8BIT)
160
+ png.mime # "image/png"
161
+ png.width # output width in pixels
162
+ png.height # output height in pixels
163
+ png.size # byte count in memory
164
+ png.warnings # structured font substitution warnings, in renderer order
165
+ png.write("diagram.png").path
166
+ ----
167
+
168
+ For text, construct faces with the public `Svgpng::FontFace` API. The `fonts`
169
+ hash maps family names to arrays of faces; `fallback_fonts` is an ordered array:
170
+
171
+ [source,ruby]
172
+ ----
173
+ require "svgpng"
174
+
175
+ face = Svgpng::FontFace.new(bytes: File.binread("fonts/ExampleSans.ttf"),
176
+ source_id: "fonts/ExampleSans.ttf")
177
+ symbols = Svgpng::FontFace.new(bytes: File.binread("fonts/ExampleSymbols.ttf"),
178
+ source_id: "fonts/ExampleSymbols.ttf")
179
+ png = svg.to_png(profile: { scale: "2" },
180
+ fonts: { "Example Sans" => [face] }, fallback_fonts: [symbols])
181
+ ----
182
+
183
+ Exact font families are matched against the font metadata after normalization;
184
+ a caller-provided family name must match that metadata. Supply separate faces for
185
+ style, weight, and stretch. Each shaped cluster uses an exact-family face with
186
+ coverage first, then the ordered fallback faces. Missing coverage raises
187
+ `Vectory::FontError`; no system font search or implicit substitution occurs.
188
+ Ruby callers receive structured warnings in `png.warnings` and decide how to
189
+ present them; the CLI prints deduplicated substitutions to stderr.
190
+
191
+ Profile keys correspond to the CLI options. Width and height are integers;
192
+ scale is a decimal string. PNG results share the image file lifecycle below:
193
+ `path` and `file_size` raise before a write, the first no-argument `write` uses a
194
+ temporary file, and subsequent no-argument writes reuse the written path.
195
+ PNG is not accepted as an input format and has no vector data-URI API.
196
+
197
+
198
+ ==== PNG safety, errors, and conformance
199
+
200
+ Output sizing applies explicit width/height first; a single dimension derives
201
+ the other from the intrinsic aspect ratio. Otherwise scale multiplies intrinsic
202
+ size; scale and explicit dimensions are mutually exclusive. Intrinsic size uses
203
+ both SVG root dimensions, or derives a missing dimension from a positive
204
+ `viewBox`; with neither dimension it uses the `viewBox`, then 300 by 150.
205
+ Without a usable `viewBox`, a missing root dimension defaults to 300 or 150.
206
+ Percent root lengths use that 300 by 150 viewport; absolute units use 96 dpi.
207
+ Resolved dimensions round half up and clamp to at least one pixel.
208
+
209
+ The raw SVG byte boundary rejects DOCTYPE internal subsets before parsing,
210
+ including subsets whose entities are unused. A plain DOCTYPE is accepted and its
211
+ external DTD is never loaded. Only same-document fragments
212
+ and inline `data:` resources are allowed. Relative/absolute paths, network URLs,
213
+ other non-inline references, and CSS `@import` are rejected. There is no resource
214
+ loader or opt-in for external access.
215
+
216
+ Enforced limits are 16 MiB of SVG, 64 font faces, 32 MiB per font, 128 MiB of
217
+ fonts total, 32768 pixels per output axis, 64,000,000 output pixels, and a
218
+ 256 MiB output buffer with checked row-stride arithmetic. These are allocation
219
+ bounds, not a time budget. For a wall-clock deadline, render in a separate,
220
+ killable process; the synchronous native call has no safe in-process cancellation.
221
+
222
+ [cols="2,3,1",options="header"]
223
+ |===
224
+ |Ruby error |Typical cause |CLI status
225
+ |`Vectory::RenderProfileError` |Invalid size, scale, background, or profile key |4
226
+ |`Vectory::MalformedSvgError` |Malformed SVG/XML |4
227
+ |`Vectory::FontError` |Invalid, duplicate, missing family, or missing glyph face |4
228
+ |`Vectory::ForbiddenExternalReferenceError` |DOCTYPE internal subset or non-inline reference |4
229
+ |`Vectory::RenderLimitError` |Input, font, dimension, pixel, or buffer bound |4
230
+ |`Vectory::UnsupportedPlatformError`, `Vectory::RendererLoadError`
231
+ |Unsupported platform or unavailable packaged renderer |5
232
+ |`Vectory::NativeRenderError`, `Vectory::PngEncodingError`
233
+ |Native rendering or PNG encoding failure |5
234
+ |`Vectory::SystemCallError` |Unreadable font/input or unwritable output |5
235
+ |===
236
+
237
+ Success returns CLI status 0. PNG-only options with another output format return
238
+ status 4. Unsupported input/output formats retain statuses 2/3, and conversion
239
+ to the same vector format retains status 7.
240
+
241
+ Deterministic bytes require the same SVG bytes, font bytes and order, render
242
+ profile, and qualified renderer/dependency build. Conformance validation checks
243
+ PNG structure; it does not establish visual correctness, cross-build byte
244
+ identity, or general support for every SVG construct. Native details belong to
245
+ https://github.com/claricle/svgpng/blob/main/docs/decisions/svg-to-png.md[svgpng's support, provenance, encoder, and release contract]
246
+ and https://github.com/claricle/svgpng/blob/main/docs/goldens.md[golden compatibility documentation].
247
+
248
+ The test-only `png_conform` dependency is version 0.1.4 at Git commit
249
+ `653abae0d16d9533a37a5d5eca40896d3b307993`. After `bundle install`, validate the
250
+ written file directly (the validator is not a Vectory runtime dependency):
251
+
252
+ [source,ruby]
253
+ ----
254
+ require "png_conform"
255
+ require "png_conform/services/validation_orchestrator"
256
+
257
+ path = png.write("diagram.png").path
258
+ analysis = PngConform::Services::ValidationOrchestrator.validate_file(path)
259
+ raise analysis.to_json unless analysis.valid?
260
+ ----
261
+
262
+ [source,sh]
263
+ ----
264
+ bundle exec rspec spec/integration/png_conform_spec.rb
265
+ bundle exec png_conform check --format json diagram.png
266
+ ----
267
+
268
+ The integration spec validates a real render with explicit font collections and
269
+ a corrupted-file negative control with nonempty diagnostic errors. It tests the
270
+ existing file boundary without an adapter. `Gemfile.lock` remains ignored and
271
+ untracked; the tracked Gemfile's Git ref supplies the validator pin.
272
+
273
+ The transform pipeline may produce the final SVG bytes; PNG rendering consumes
274
+ those bytes and does not depend on transform pipeline internals.
275
+
276
+
92
277
  ==== What is supported?
93
278
 
94
279
  There are several vector classes which support conversion between each other:
@@ -363,6 +548,12 @@ Vector#size
363
548
  Vector#file_size
364
549
  Vector#height
365
550
  Vector#width
551
+ Png#mime
552
+ Png#size
553
+ Png#file_size
554
+ Png#height
555
+ Png#width
556
+ Png#warnings
366
557
  ----
367
558
 
368
559
 
@@ -410,6 +601,39 @@ gem bump --version minor --tag --push
410
601
  ----
411
602
 
412
603
 
604
+ == Serialized SVG transforms
605
+
606
+ Vectory exposes immutable transformations of serialized XML strings. Class
607
+ selectors are parsed with Crass (`~> 1.0`, `>= 1.0.7`); class lists and selectors
608
+ use the same positional `_inject_<index>` suffix as ID disambiguation.
609
+ `SvgClassSuffixer` is the canonical Vectory class-suffix implementation.
610
+
611
+ [source,ruby]
612
+ ----
613
+ cleanup = Vectory::SvgTransform.disambiguate(index: 0, duplicate_ids: collisions) >>
614
+ Vectory::SvgTransform.suffix_classes(index: 0) >>
615
+ Vectory::SvgTransform.bind_namespaces(bind: { "xlink" => "http://www.w3.org/1999/xlink" })
616
+ result = cleanup.call(svg_xml)
617
+ ----
618
+
619
+ The executable profiles are `graft` (`G`), `svg_cleanup` (`D -> S -> N`),
620
+ and `graft_then_svg_cleanup` (`G -> D -> S -> N`). Other sequences are rejected;
621
+ construction prefixes cannot execute until complete. Cleanup accepts a selected
622
+ SVG root, while a graft can accept a complete host document. Reapplying a profile
623
+ with the same captured inputs is XML-equivalent. Step options are deeply frozen
624
+ snapshots, so later changes to a caller's collision map cannot change a pipeline.
625
+
626
+ Namespace binding preserves expanded element and attribute names; it is separate
627
+ from the legacy `SvgDocument#namespace` ID/link cleanup. See the API reference for
628
+ safe binding, unbinding and URI-to-prefix remapping.
629
+
630
+ For multiple embedded SVGs, graft the complete mapped document once, then build a
631
+ fresh cleanup pipeline for each SVG from the current collision map. Merge each
632
+ result's IDs before constructing the next pipeline. Standoc #1298 adopts ID
633
+ disambiguation while retaining its inline Crass helpers; adopting
634
+ `SvgClassSuffixer` is a separate downstream task after a containing release.
635
+ SVG-to-PNG rendering is a separate projection feature.
636
+
413
637
  == Contributing
414
638
 
415
639
  Bug reports and pull requests are welcome on GitHub at:
data/docs/Gemfile CHANGED
@@ -3,6 +3,9 @@ source "https://rubygems.org"
3
3
  # Jekyll plugins
4
4
  gem "jekyll", "~> 3.0"
5
5
  gem "just-the-docs", "~> 0.7"
6
+ # Jekyll 3 dependencies require these gems explicitly on recent Ruby versions.
7
+ gem "base64", "~> 0.2"
8
+ gem "bigdecimal", ">= 3.1", "< 5"
6
9
 
7
10
  # Markdown and AsciiDoc processing
8
11
  gem "asciidoctor", "~> 2.0"
data/docs/lychee.toml CHANGED
@@ -6,20 +6,11 @@ exclude = [
6
6
  'http://localhost:*',
7
7
  'http://127.0.0.1:*',
8
8
  'file:///*',
9
- ]
10
-
11
- # Exclude mailto: links
12
- exclude = [
9
+ # Exclude mailto: links
13
10
  'mailto:*',
14
- ]
15
-
16
- # Exclude version-specific URLs that may break
17
- exclude = [
11
+ # Exclude version-specific URLs that may break
18
12
  'https://github.com/*/releases/tag/*', # GitHub release tags
19
13
  'https://rubygems.org/gems/*/versions/*', # RubyGem version history
20
- ]
21
-
22
- # Allow certain redirects
23
- exclude = [
14
+ # Example domains used in docs
24
15
  'https://example.com/*', # Example domains used in docs
25
16
  ]
@@ -430,8 +430,202 @@ fig1_ISO_17301-1_2016 → fig1_ISO_17301-1_2016_000000000
430
430
  * **ID suffix** (`id_suffix` parameter): Derived from document/container identity. Optional.
431
431
  * **Index suffix** (`index_suffix` parameter): Zero-padded position (0, 1, 2... → _000000000, _000000001). Automatically applied.
432
432
 
433
+ == Serialized SVG transforms
434
+
435
+ All methods consume XML strings and return a new XML string. The input DOM is
436
+ never shared with the result. These content transforms do not render PNG images.
437
+
438
+ * `SvgClassSuffixer.rewrite(content, suffix)` updates XML class lists and CSS class
439
+ selectors using Crass, including escaped identifiers and nested selector rules.
440
+ Reapplying the same suffix is idempotent.
441
+ * `SvgNamespaceBinding.rewrite(content, bind: {}, unbind: [], remap: {})` binds
442
+ prefix-to-URI declarations, unbinds unused prefixes, and remaps URIs to target
443
+ prefixes. An empty or nil prefix means the default namespace. Expanded names
444
+ are preserved; default namespaces never qualify unprefixed attributes.
445
+ Conflicting bindings, used unbinds and identity-changing default remaps raise
446
+ `ArgumentError`. Malformed, rootless or non-SVG input also raises `ArgumentError`.
447
+ * `SvgSubtreeGraft.replace_root_content(host_content, processed_content)` preserves
448
+ the host document/root metadata and replaces only the ordered root children,
449
+ including text, comments, CDATA and processing instructions. Invalid input
450
+ raises `Vectory::ParsingError`, identifying `host_content` or `processed_content`.
451
+ Grafts decode each input's XML encoding and return UTF-8, updating an existing
452
+ encoding declaration while preserving document content and envelope order.
453
+
454
+ `SvgTransform` factories return named immutable steps:
455
+
456
+ * `graft_into(host_content:)` validates and captures the host at construction.
457
+ * `disambiguate(index:, duplicate_ids:)` delegates to `SvgIdDisambiguator` with a
458
+ deeply copied collision map and `_inject_<index>` suffix.
459
+ * `suffix_classes(index:)` uses that same suffix for classes.
460
+ * `bind_namespaces(bind: {}, unbind: [], remap: {})` uses the namespace contract above.
461
+
462
+ Compose steps with `>>`. `SvgTransformPipeline#steps` exposes stable names and
463
+ deeply frozen option snapshots; `#profile` identifies the executable profile.
464
+ `#call(content)` returns serialized XML. Exactly three profiles can execute:
465
+
466
+ [cols="1,1,2",options="header"]
467
+ |===
468
+ |Profile |Steps |Scope
469
+ |`graft` |`G` |A complete rooted processed document grafted into the captured host.
470
+ |`svg_cleanup` |`D -> S -> N` |Exactly one selected SVG root, including its nested SVGs.
471
+ |`graft_then_svg_cleanup` |`G -> D -> S -> N` |A captured host whose root is SVG.
472
+ |===
473
+
474
+ Appending an invalid sequence raises `ArgumentError` containing
475
+ `invalid step sequence`. Calling an incomplete prefix raises `ArgumentError`
476
+ containing `incomplete profile`. A wrong input scope raises `ArgumentError`
477
+ containing `execution-scope mismatch`. Parse errors stop execution and propagate.
478
+
479
+ === Standoc migration boundary
480
+
481
+ Map and graft the complete prepared host once, then process the selected SVGs in
482
+ document order. Preserve the caller's sequential collision map; do not use the
483
+ batch `SvgIdDisambiguator.duplicate_ids` helper for this compatibility flow.
484
+
485
+ [source,ruby]
486
+ ----
487
+ mapped = Vectory::SvgMapping.new(original_host).call.to_xml
488
+ grafted = Vectory::SvgTransform.graft_into(host_content: original_host).call(mapped)
489
+ document = Leptris::XML.parse(grafted)
490
+ collisions = {}
491
+ document.xpath("//*[local-name()='svg' and not(ancestor::*[local-name()='svg'])]").each_with_index do |svg, index|
492
+ # Make inherited namespace bindings explicit before serializing this subtree.
493
+ declared_prefixes = svg.namespace_definitions.map(&:prefix)
494
+ svg.namespaces.each do |name, uri|
495
+ prefix = name == "xmlns" ? nil : name.delete_prefix("xmlns:")
496
+ next if declared_prefixes.include?(prefix)
497
+
498
+ svg.add_namespace_definition(prefix, uri)
499
+ end
500
+ pipeline = Vectory::SvgTransform.disambiguate(index: index, duplicate_ids: collisions) >>
501
+ Vectory::SvgTransform.suffix_classes(index: index) >>
502
+ Vectory::SvgTransform.bind_namespaces(bind: { "xlink" => "http://www.w3.org/1999/xlink" })
503
+ cleaned = pipeline.call(svg.to_xml)
504
+ Leptris::XML.parse(cleaned).xpath("//*[@id]").each { |node| collisions[node["id"]] = true }
505
+ svg.replace(cleaned)
506
+ end
507
+ ----
508
+
509
+ Each pipeline retains the collision map as it existed at construction. The first
510
+ repeated root ID remains unchanged; the later one receives its positional suffix.
511
+ The selected SVG must carry its in-scope namespace declarations across the string
512
+ boundary; a declaration inherited from the host is otherwise lost by `to_xml`.
513
+ Standoc #1298 consumes `SvgIdDisambiguator` and retains its current Crass helpers.
514
+ `SvgClassSuffixer` is the canonical Vectory implementation; later adoption and
515
+ removal of the inline helpers require a separate task after a containing release.
516
+
433
517
  == See Also
434
518
 
435
519
  * link:../guides/error-handling/[Error Handling Guide] - Common errors and solutions
436
520
  * link:../understanding/architecture/[Architecture] - Design patterns
437
521
  * link:../features/conversion/[Conversion Features] - Conversion details
522
+
523
+
524
+ == PNG rendering and conformance
525
+
526
+ PNG is output-only. Every vector class (`Svg`, `Emf`, `Eps`, `Ps`) exposes
527
+ `to_png(profile: {}, fonts:, fallback_fonts:)`, returning `Vectory::Png`.
528
+ The transform pipeline may produce the final SVG bytes; rendering consumes those
529
+ bytes without depending on transform pipeline classes.
530
+
531
+ [source,ruby]
532
+ ----
533
+ require "vectory"
534
+ require "svgpng"
535
+
536
+ svg = Vectory::Svg.from_path("diagram.svg")
537
+ face = Svgpng::FontFace.new(bytes: File.binread("fonts/ExampleSans.ttf"),
538
+ source_id: "fonts/ExampleSans.ttf")
539
+ fallback = Svgpng::FontFace.new(bytes: File.binread("fonts/ExampleSymbols.ttf"),
540
+ source_id: "fonts/ExampleSymbols.ttf")
541
+ png = svg.to_png(profile: { width: 1200, background: "#ffffff" },
542
+ fonts: { "Example Sans" => [face] }, fallback_fonts: [fallback])
543
+ png.write("diagram.png")
544
+ png.warnings.each { |warning| warn warning.inspect }
545
+ ----
546
+
547
+ Font families must match normalized byte-derived metadata. Multiple faces per
548
+ family support style, weight, and stretch. A cluster selects an exact-family
549
+ face with full coverage before trying fallback faces in caller order. Missing
550
+ coverage raises `Vectory::FontError`. No system fonts are searched. Text-free
551
+ SVG uses explicit `fonts: {}, fallback_fonts: []`. Ruby exposes ordered structured
552
+ warnings; the CLI emits each substitution once to stderr, naming families,
553
+ style/weight/stretch, and Unicode scalars.
554
+
555
+ `Png#content` is binary (`ASCII-8BIT`); `#mime` is `image/png`. `#width`, `#height`,
556
+ and `#size` report pixels and byte count. `#warnings` is an immutable collection.
557
+ `#write(path)` writes bytes and returns the image; `#path` and `#file_size` raise
558
+ before writing. The first no-argument `#write` creates a temporary file and later
559
+ calls reuse its path. PNG has no vector data-URI interface and is not accepted
560
+ as conversion input.
561
+
562
+ [source,sh]
563
+ ----
564
+ vectory -f png -o diagram.png --width 1200 --height 800 \
565
+ --background '#ffffff' --font 'Example Sans=fonts/ExampleSans.ttf' \
566
+ --fallback-font 'Example Symbols=fonts/ExampleSymbols.ttf' diagram.svg
567
+ vectory -f png --scale 2 --background transparent diagram.svg
568
+ ----
569
+
570
+ All PNG-only CLI flags are `--width`, `--height`, `--scale`, `--background`,
571
+ repeatable `--font FAMILY=PATH`, and repeatable `--fallback-font FAMILY=PATH`.
572
+ Other output formats reject these options. Profile keys are the corresponding
573
+ Ruby symbols: positive integer width/height, positive decimal-string scale,
574
+ and background `transparent`, `#RRGGBB`, or `#RRGGBBAA`. Scale cannot accompany
575
+ width/height. Both dimensions set an aspect-preserving centered canvas; one
576
+ derives the other. Otherwise scale multiplies intrinsic dimensions.
577
+ Intrinsic size uses both root dimensions, derives a missing dimension from a
578
+ positive `viewBox`, uses `viewBox` alone, then defaults to 300 by 150.
579
+ A missing axis without a usable `viewBox` defaults to 300 or 150; percentage
580
+ root lengths use that viewport and absolute units use 96 dpi. Dimensions round
581
+ half up with a one-pixel minimum.
582
+
583
+ DOCTYPE internal subsets are rejected before parsing or entity expansion. A
584
+ plain DOCTYPE is accepted, and its external DTD is never loaded.
585
+ Same-document fragments and inline `data:` resources are accepted; paths,
586
+ network URLs, other non-inline references, and CSS `@import` are rejected.
587
+ There is no external-resource loader or option to enable one.
588
+
589
+ Enforceable limits: SVG 16 MiB; 64 faces; 32 MiB per font and 128 MiB total;
590
+ 32768 pixels per axis; 64,000,000 pixels; checked row stride and at most
591
+ 256 MiB output buffer. A synchronous native render has no safe cancellation;
592
+ use a killable isolated process for wall-clock deadlines.
593
+
594
+ `RenderProfileError`, `MalformedSvgError`, `FontError`,
595
+ `ForbiddenExternalReferenceError`, and `RenderLimitError` are Vectory conversion
596
+ errors (CLI status 4). `UnsupportedPlatformError`, `RendererLoadError`,
597
+ `NativeRenderError`, `PngEncodingError`, and filesystem `SystemCallError` are
598
+ Vectory system-call errors (CLI status 5). Success is 0; unsupported input/output
599
+ remain 2/3 and same-format vector conversion remains 7.
600
+
601
+ The seven native packages target `arm64-darwin`, `x86_64-darwin`, `x86_64-linux`,
602
+ `aarch64-linux`, `x86_64-linux-musl`, `aarch64-linux-musl`, and `x64-mingw-ucrt`.
603
+ They require no external renderer/compiler. Other platforms install the
604
+ same-version Ruby shell; requiring Vectory and non-PNG conversions still work,
605
+ but PNG requests raise `Vectory::UnsupportedPlatformError` (status 5).
606
+ Release requires the qualified seven native packages and shell together.
607
+
608
+ Byte identity requires identical SVG/font inputs, fallback order, profile, and
609
+ qualified renderer/dependency build. See
610
+ https://github.com/claricle/svgpng/blob/main/docs/decisions/svg-to-png.md[svgpng support, provenance, encoder, and release details]
611
+ and https://github.com/claricle/svgpng/blob/main/docs/goldens.md[golden compatibility].
612
+ Conformance does not prove visual fidelity, arbitrary SVG feature support, or
613
+ byte identity across renderer builds.
614
+
615
+ For development/CI, the tracked Gemfile pins test-only `png_conform` 0.1.4 to
616
+ `653abae0d16d9533a37a5d5eca40896d3b307993`; it is not a runtime dependency.
617
+ The lockfile remains ignored and untracked. After `bundle install`:
618
+
619
+ [source,ruby]
620
+ ----
621
+ require "png_conform"
622
+ require "png_conform/services/validation_orchestrator"
623
+
624
+ analysis = PngConform::Services::ValidationOrchestrator.validate_file(png.path)
625
+ raise analysis.to_json unless analysis.valid?
626
+ ----
627
+
628
+ `bundle exec png_conform check --format json diagram.png` validates a file from the CLI.
629
+ `bundle exec rspec spec/integration/png_conform_spec.rb` proves direct handoff of
630
+ a real written PNG plus rejection of a corrupted copy with diagnostic errors.
631
+ No conformance adapter is required.