svg_conform 0.2.10 → 0.2.11

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.
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "nokogiri"
3
+ require "moxml"
4
+ require "leptris"
4
5
 
5
6
  module SvgConform
6
7
  module Validation
@@ -13,10 +14,9 @@ module SvgConform
13
14
  # from a separate parse of it, and a document that declares an external
14
15
  # entity is rejected before any entity is expanded.
15
16
  #
16
- # Library choice (see the validator spec for the probe results): the
17
- # bundled Moxml/Leptris stack parses the flat DTD but does not apply its
18
- # conditional sections, so it accepts every document. Nokogiri (libxml2)
19
- # validates the flat DTD offline.
17
+ # Library choice (see the validator spec for the probe results): leptris
18
+ # validates the flat DTD offline once the DTD is flattened into an
19
+ # internal subset, because leptris never loads external DTDs.
20
20
  class Svg11DocumentConformance
21
21
  SVG_NS = "http://www.w3.org/2000/svg"
22
22
  XLINK_NS = "http://www.w3.org/1999/xlink"
@@ -26,6 +26,12 @@ module SvgConform
26
26
  MANIFEST_PATH = File.join(DATA_DIR, "manifest.yml")
27
27
  EXTERNAL_ENTITY = /<!ENTITY\s+(?:%\s+)?[^\s>]+\s+(?:SYSTEM|PUBLIC)\b/m
28
28
 
29
+ PUBLIC_DOCTYPE_RE = /<!DOCTYPE[^>]*>/
30
+ XML_DECL_VERSION = /\A\s*<\?xml[^?]*\bversion\s*=\s*["']([^"']+)["']/
31
+ ELEMENT_DECL = /<!ELEMENT\s+([A-Za-z_:][A-Za-z0-9._:-]*)/
32
+ ATTLIST_DECL = /<!ATTLIST\s+([A-Za-z_:][A-Za-z0-9._:-]*)(.*?)>/m
33
+ ATTR_DECL = /([A-Za-z_:][A-Za-z0-9._:-]*)\s+(?:CDATA|ID|IDREF|IDREFS|ENTITY|ENTITIES|NMTOKEN|NMTOKENS|NOTATION|\()/m
34
+
29
35
  Issue = Struct.new(:kind, :message, :line, keyword_init: true)
30
36
 
31
37
  # Outcome of one validation. +transformed+ is the Appendix G.2 copy
@@ -47,7 +53,7 @@ module SvgConform
47
53
  parsed = parse_expanded(source)
48
54
  return parsed if parsed.is_a?(Result)
49
55
 
50
- copy = transform(parsed)
56
+ copy = transform(parsed, xml_decl_version(source))
51
57
  return failure(:no_svg_root, "document element is not an SVG element") unless copy
52
58
 
53
59
  Result.new(issues: dtd_issues(copy), transformed: copy)
@@ -57,18 +63,100 @@ module SvgConform
57
63
  # keep xlink attributes under the xlink prefix, and set the two
58
64
  # namespace declarations on the document element. Returns the serialized
59
65
  # copy (with the DOCTYPE for the local DTD) or nil without an SVG root.
60
- def transform(doc)
66
+ def transform(doc, decl_version = "1.0")
61
67
  root = doc.root
62
- return unless root&.namespace&.href == SVG_NS
68
+ return unless root&.namespace&.uri == SVG_NS
63
69
 
64
70
  body = +""
65
71
  write_element(root, body, root: true)
66
- %(<?xml version="#{doc.version || '1.0'}" encoding="UTF-8"?>\n) +
72
+ %(<?xml version="#{decl_version}" encoding="UTF-8"?>\n) +
67
73
  %(<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "#{dtd_uri}">\n#{body}\n)
68
74
  end
75
+ # A sequential DTD preprocessor. libxml2 expands a parameter-entity
76
+ # reference to the definition in effect at the reference point, and the
77
+ # flat DTD leans on that: attribute PEs are redeclared per module and
78
+ # qname PEs are redeclared to literal element names after the modular
79
+ # machinery. A batch expansion cannot reproduce it, so the text is
80
+ # walked in order: PE declarations register and vanish, conditional
81
+ # sections resolve to INCLUDE content or nothing, and every remaining
82
+ # reference expands live. The result is an internal-subset-safe
83
+ # declaration stream (no PE references, no conditional sections).
84
+
85
+ def self.flatten_dtd(dtd_text)
86
+ current = {}
87
+ out = +""
88
+ process_section(dtd_text, current, out)
89
+ out
90
+ end
91
+
92
+ PE_TOKEN = %r{
93
+ <!ENTITY\s+%\s+([A-Za-z0-9._-]+)\s+(["'])(.*?)\2\s*>
94
+ |<!\[\s*(?:(INCLUDE|IGNORE)|%([A-Za-z0-9._-]+);?)\s*\[
95
+ |%([A-Za-z0-9._-]+);
96
+ }xm
97
+ CONDITIONAL_BODY_OPEN = /<!\[\s*(?:(?:INCLUDE|IGNORE)|%[A-Za-z0-9._-]+;?)\s*\[/i
98
+ MAX_PE_DEPTH = 50
99
+
100
+ def self.process_section(text, current, out)
101
+ pos = 0
102
+ while (match = PE_TOKEN.match(text, pos))
103
+ out << expand_refs(text[pos...match.begin(0)], current)
104
+ if match[1]
105
+ # libxml2 keeps the first declaration of a parameter entity and
106
+ # ignores later duplicates.
107
+ current[match[1]] ||= match[3]
108
+ pos = match.end(0)
109
+ elsif match[4] || match[5]
110
+ keyword = expand_refs(match[4] || current[match[5]] || "", current)
111
+ .to_s.strip.upcase
112
+ body_start, body_end, pos = conditional_extent(text, match.end(0))
113
+ process_section(text[body_start...body_end], current, out) if keyword == "INCLUDE"
114
+ else
115
+ out << expand_refs(match[0], current)
116
+ pos = match.end(0)
117
+ end
118
+ end
119
+ out << expand_refs(text[pos..], current)
120
+ end
121
+
122
+ # Offsets of one conditional section's body: [start, end, after_close],
123
+ # honouring nested conditional sections.
124
+ def self.conditional_extent(text, open_end)
125
+ depth = 1
126
+ pos = open_end
127
+ while depth.positive?
128
+ close = text.index("]]>", pos)
129
+ raise ArgumentError, "unterminated conditional section" unless close
130
+
131
+ inner = CONDITIONAL_BODY_OPEN.match(text, pos)
132
+ if inner && inner.end(0) <= close + 3
133
+ depth += 1
134
+ pos = inner.end(0)
135
+ else
136
+ depth -= 1
137
+ pos = close + 3
138
+ end
139
+ end
140
+ [open_end, pos - 3, pos]
141
+ end
142
+
143
+ def self.expand_refs(text, current, depth = 0)
144
+ raise ArgumentError, "parameter entity recursion too deep" if depth > MAX_PE_DEPTH
145
+
146
+ text.gsub(/%([A-Za-z0-9._-]+);/) do
147
+ value = current[Regexp.last_match(1)]
148
+ value ? expand_refs(value, current, depth + 1) : Regexp.last_match(0)
149
+ end
150
+ end
69
151
 
70
152
  private
71
153
 
154
+ # Moxml documents do not expose the XML declaration; read it from the
155
+ # source text.
156
+ def xml_decl_version(source)
157
+ source.match(XML_DECL_VERSION)&.captures&.first || "1.0"
158
+ end
159
+
72
160
  # A file URI that libxml2 accepts for POSIX paths and for Windows drive
73
161
  # paths ("D:\\a\\x" becomes "file:///D:/a/x").
74
162
  def dtd_uri
@@ -89,8 +177,8 @@ module SvgConform
89
177
  # Entities are expanded (Appendix G.2) only after the source is known
90
178
  # to declare no external entity, so expansion cannot read a file.
91
179
  def parse_expanded(source)
92
- Nokogiri::XML::Document.parse(source) { |config| config.strict.noent.nonet }
93
- rescue Nokogiri::XML::SyntaxError => e
180
+ Moxml.parse(source)
181
+ rescue Moxml::ParseError => e
94
182
  failure(:malformed_xml, e.message, e.line)
95
183
  end
96
184
 
@@ -99,7 +187,7 @@ module SvgConform
99
187
  if root
100
188
  out << %( xmlns="#{SVG_NS}" xmlns:xlink="#{XLINK_NS}")
101
189
  end
102
- node.attribute_nodes.each { |attr| write_attribute(attr, out) }
190
+ node.attributes.each { |attr| write_attribute(attr, out) }
103
191
  children = node.children
104
192
  if children.empty?
105
193
  out << "/>"
@@ -111,7 +199,7 @@ module SvgConform
111
199
  end
112
200
 
113
201
  def write_attribute(attr, out)
114
- href = attr.namespace&.href
202
+ href = attr.namespace&.uri
115
203
  name = case href
116
204
  when nil then attr.name
117
205
  when XLINK_NS then "xlink:#{attr.name}"
@@ -121,12 +209,12 @@ module SvgConform
121
209
  end
122
210
 
123
211
  def write_node(node, out)
124
- case node.type
125
- when Nokogiri::XML::Node::ELEMENT_NODE
126
- write_element(node, out) if node.namespace&.href == SVG_NS
127
- when Nokogiri::XML::Node::TEXT_NODE, Nokogiri::XML::Node::CDATA_SECTION_NODE
212
+ case node.node_type
213
+ when :element
214
+ write_element(node, out) if node.namespace&.uri == SVG_NS
215
+ when :text, :cdata
128
216
  out << escape_text(node.content)
129
- when Nokogiri::XML::Node::COMMENT_NODE
217
+ when :comment
130
218
  out << "<!--" << node.content << "-->"
131
219
  end
132
220
  end
@@ -140,15 +228,89 @@ module SvgConform
140
228
  .gsub("\n", "&#10;").gsub("\r", "&#13;")
141
229
  end
142
230
 
231
+ # leptris never loads external DTDs, so the flat DTD cannot be applied
232
+ # through the DOCTYPE the transform emits. For validation only, the
233
+ # vendored DTD is flattened into an internal subset: parameter entities
234
+ # are expanded textually and conditional sections resolved, because
235
+ # libxml2 permits neither PE references nor conditional sections in an
236
+ # internal subset and silently drops the whole subset otherwise.
237
+ #
238
+ # leptris also does not flag undeclared elements and attributes, so the
239
+ # same flattened DTD is scanned for its ELEMENT and ATTLIST
240
+ # declarations to reproduce those checks offline. Messages keep the
241
+ # libxml2 wording the validator contract is written against.
143
242
  def dtd_issues(copy)
144
- doc = Nokogiri::XML::Document.parse(copy) do |config|
145
- config.dtdload.dtdvalid.nonet
243
+ validation_source = copy.sub(PUBLIC_DOCTYPE_RE, inline_doctype)
244
+ doc = Leptris::XML.parse(validation_source)
245
+ issues = Leptris::XML::DTD.from_document(doc).validate(doc)
246
+ .map { |error| normalize_dtd_error(error) }
247
+ issues.concat(declaration_issues(Moxml.parse(validation_source)))
248
+ issues.map { |issue| Issue.new(kind: :dtd, message: issue[:message], line: issue[:line]) }
249
+ rescue Leptris::XML::Error, Moxml::ParseError => e
250
+ [Issue.new(kind: :dtd, message: e.message, line: nil)]
251
+ end
252
+
253
+ def normalize_dtd_error(error)
254
+ message = error[:message].to_s.sub(/\A\d+:\d+: ERROR: /, "")
255
+ message = case message
256
+ when /\AElement '([^']+)' missing #REQUIRED attribute '([^']+)'\z/
257
+ "Element #{Regexp.last_match(1)} does not carry attribute #{Regexp.last_match(2)}"
258
+ when /\AElement '([^']+)' content model requires (.+)\z/m
259
+ "Element #{Regexp.last_match(1)} content does not follow the DTD, " \
260
+ "expecting #{Regexp.last_match(2)}"
261
+ else
262
+ message
263
+ end
264
+ { message: message, line: error[:line] }
265
+ end
266
+
267
+ def declaration_issues(doc)
268
+ issues = []
269
+ doc.traverse do |node|
270
+ next unless node.node_type == :element
271
+
272
+ name = node.name
273
+ unless declared_elements.include?(name)
274
+ issues << { message: "No declaration for element #{name}", line: node.line_number }
275
+ end
276
+ node.attributes.each do |attr|
277
+ key = prefixed_attribute_name(attr)
278
+ next if key.start_with?("xmlns")
279
+ next if declared_attributes[name]&.include?(key)
280
+
281
+ issues << { message: "No declaration for attribute #{key} on element #{name}",
282
+ line: node.line_number }
283
+ end
146
284
  end
147
- doc.errors.map do |error|
148
- Issue.new(kind: :dtd, message: error.message.sub(/\A\d+:\d+: ERROR: /, ""),
149
- line: error.line)
285
+ issues
286
+ end
287
+
288
+ def prefixed_attribute_name(attr)
289
+ case attr.namespace&.uri
290
+ when XLINK_NS then "xlink:#{attr.name}"
291
+ when XML_NS then "xml:#{attr.name}"
292
+ else attr.name
150
293
  end
151
294
  end
295
+
296
+ def declared_elements
297
+ @declared_elements ||= flattened_dtd.scan(ELEMENT_DECL).to_set(&:first)
298
+ end
299
+
300
+ def declared_attributes
301
+ @declared_attributes ||= flattened_dtd.scan(ATTLIST_DECL)
302
+ .each_with_object({}) do |(element, body), map|
303
+ map[element] = body.scan(ATTR_DECL).to_set(&:first)
304
+ end
305
+ end
306
+
307
+ def inline_doctype
308
+ @inline_doctype ||= "<!DOCTYPE svg [#{flattened_dtd}]>"
309
+ end
310
+
311
+ def flattened_dtd
312
+ @flattened_dtd ||= self.class.flatten_dtd(File.read(@dtd_path))
313
+ end
152
314
  end
153
315
  end
154
316
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module SvgConform
4
- VERSION = "0.2.10"
4
+ VERSION = "0.2.11"
5
5
  end
data/lib/svg_conform.rb CHANGED
@@ -1,6 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "lutaml/model"
4
+ require "lutaml/yaml/adapter/yeptris_adapter"
5
+ require "yeptris/psych"
4
6
 
5
7
  # lens_core is optional (0.2.5 shipped it as a hard dependency while the
6
8
  # gem is still unpublished, which made every fresh resolve unsolvable).
@@ -16,7 +18,7 @@ end
16
18
  Lutaml::Model::Config.configure do |config|
17
19
  config.xml_adapter_type = :leptris
18
20
  config.json_adapter_type = :standard_json
19
- config.yaml_adapter_type = :standard_yaml
21
+ config.yaml_adapter_type = :yeptris
20
22
  end
21
23
 
22
24
  require_relative "svg_conform/version"
@@ -43,6 +45,33 @@ require_relative "svg_conform/fixer"
43
45
  require_relative "svg_conform/external_checkers"
44
46
 
45
47
  module SvgConform
48
+ # The native lutaml-model loader loses binary decoding and accepts Ruby
49
+ # object tags. Keep its permitted classes, using yeptris's safe loader.
50
+ module ModelYamlSafeLoad
51
+ def parse(yaml, _options = {})
52
+ Yeptris::Psych.safe_load(
53
+ yaml, permitted_classes: Lutaml::Yaml::Adapter::StandardAdapter::PERMITTED_CLASSES
54
+ )
55
+ rescue Yeptris::Psych::SyntaxError => e
56
+ # Preserve the adapter's Psych error boundary so lutaml-model wraps
57
+ # malformed input in InvalidFormatError as it does for other formats.
58
+ raise syntax_error(e)
59
+ rescue Yeptris::Psych::AliasesError
60
+ raise ::Psych::AliasesNotEnabled
61
+ end
62
+ end
63
+
64
+ # Keep stored YAML byte-compatible until yeptris's emitter matches the
65
+ # standard adapter for non-BMP text. Reads still use yeptris throughout.
66
+ module ModelYamlStableDump
67
+ def to_yaml(options = {})
68
+ Lutaml::Yaml::Adapter::StandardAdapter.new(@attributes).to_yaml(options)
69
+ end
70
+ end
71
+
72
+ Lutaml::Yaml::Adapter::YeptrisAdapter.singleton_class.prepend(ModelYamlSafeLoad)
73
+ Lutaml::Yaml::Adapter::YeptrisAdapter.prepend(ModelYamlStableDump)
74
+
46
75
  class Error < StandardError; end
47
76
  class ParseError < Error; end
48
77
  class ValidationError < Error; end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "spec_helper"
4
+ require "psych"
5
+ require "tempfile"
6
+
7
+ RSpec.describe SvgConform::ExternalCheckers::Svgcheck::Parser do
8
+ describe "mapping config loading" do
9
+ let(:yaml) do
10
+ <<~YAML
11
+ message_patterns:
12
+ - pattern: "Element (\\\\w+) is not allowed"
13
+ requirement: forbidden_content
14
+ requirement_mappings:
15
+ forbidden_content:
16
+ - script
17
+ skip_patterns:
18
+ - "^Warning:"
19
+ special_rules: {}
20
+ YAML
21
+ end
22
+
23
+ let(:file) { Tempfile.new(["svgcheck_mapping", ".yml"]) }
24
+ let(:path) { file.path }
25
+
26
+ before do
27
+ file.write(yaml)
28
+ file.flush
29
+ end
30
+
31
+ after { file.close! }
32
+
33
+ it "loads message_patterns, requirement_mappings and skip_patterns" do
34
+ config = described_class.new(path).mapping_config
35
+
36
+ expect(config["message_patterns"]).to be_an(Array)
37
+ expect(config["requirement_mappings"]).to eq("forbidden_content" => ["script"])
38
+ expect(config["skip_patterns"]).to eq(["^Warning:"])
39
+ end
40
+
41
+ it "loads the same hash as Psych" do
42
+ expect(described_class.new(path).mapping_config).to eq(Psych.load_file(path))
43
+ end
44
+
45
+ it "loads the bundled mapping config the same as Psych" do
46
+ path = File.expand_path("../../../../config/svgcheck_mapping.yml", __dir__)
47
+ skip "no bundled mapping" unless File.exist?(path)
48
+
49
+ expect(described_class.new(path).mapping_config).to eq(Psych.load_file(path))
50
+ end
51
+ end
52
+ end
@@ -46,7 +46,7 @@ RSpec.describe "svg_conform.gemspec" do # rubocop:disable RSpec/DescribeClass
46
46
  skip "no committed lockfile (release context)" unless File.exist?("Gemfile.lock")
47
47
 
48
48
  lock = File.read("Gemfile.lock")
49
- path_version = lock[/\APATH\n remote: \.\n specs:\n svg_conform \(([^)]+)\)/, 1]
49
+ path_version = lock[/^PATH\n remote: \.\n specs:\n svg_conform \(([^)]+)\)/, 1]
50
50
  expect(path_version).to eq(SvgConform::VERSION)
51
51
  end
52
52
  end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "spec_helper"
4
- require "nokogiri"
4
+ require "moxml"
5
5
 
6
6
  RSpec.describe SvgConform::Profiles do
7
7
  let(:validator) { SvgConform::Validator.new(mode: :sax) }
@@ -19,6 +19,14 @@ RSpec.describe SvgConform::Profiles do
19
19
  SVG
20
20
  end
21
21
 
22
+ def svg_namespace
23
+ "http://www.w3.org/2000/svg"
24
+ end
25
+
26
+ def xlink_namespace
27
+ "http://www.w3.org/1999/xlink"
28
+ end
29
+
22
30
  it "accepts the five explicit layout and link attributes" do
23
31
  result = validator.validate(svg, profile: profile)
24
32
  expect(result.errors.map(&:message)).to be_empty
@@ -68,14 +76,15 @@ RSpec.describe SvgConform::Profiles do
68
76
  end
69
77
 
70
78
  def text_layout(xml)
71
- Nokogiri::XML(xml).xpath("//svg:text", "svg" => "http://www.w3.org/2000/svg").map do |node|
72
- [node.text, node["x"], node["y"], node["textLength"], node["lengthAdjust"]]
79
+ Moxml.parse(xml).xpath("//svg:text", "svg" => svg_namespace).map do |node|
80
+ [node.content, node["x"], node["y"], node["textLength"], node["lengthAdjust"]]
73
81
  end
74
82
  end
75
83
 
76
84
  def diagram_links(xml)
77
- Nokogiri::XML(xml).xpath("//svg:a", "svg" => "http://www.w3.org/2000/svg").map do |node|
78
- [node["title"], node.attribute_with_ns("href", "http://www.w3.org/1999/xlink")&.value]
85
+ Moxml.parse(xml).xpath("//svg:a", "svg" => svg_namespace).map do |node|
86
+ href = node.attributes.find { |attr| attr.namespace&.uri == xlink_namespace }
87
+ [node["title"], href&.value]
79
88
  end
80
89
  end
81
90
  end
@@ -37,8 +37,6 @@ RSpec.describe SvgConform::QualityMetrics::Configuration do
37
37
  end
38
38
 
39
39
  it "preserves quoted Symbol values" do
40
- pending "yeptris differs from Psych: quoted Symbols retain quotes; upstream issue to be filed, see PR description"
41
-
42
40
  config = load_yaml('a: :"x y"')
43
41
 
44
42
  expect(config.instance_variable_get(:@hash)).to eq("a" => :"x y")
@@ -50,8 +48,6 @@ RSpec.describe SvgConform::QualityMetrics::Configuration do
50
48
  end
51
49
 
52
50
  it "rejects disallowed times with the yeptris error naming Time" do
53
- pending "yeptris differs from Psych: disallowed Time is reported as Date; upstream issue to be filed, see PR description"
54
-
55
51
  expect { load_yaml("f: 2024-01-02 10:00:00\n") }
56
52
  .to raise_error(Yeptris::Psych::DisallowedClass, /Time/)
57
53
  end
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "spec_helper"
4
+
5
+ RSpec.describe SvgConform::Remediations::DisallowedAttributeRemediation do
6
+ # svg_1_2_rfc#88: Inkscape-authored documents carry enable-background
7
+ # on the root svg element; the attribute is removed in SVG 1.2 RFC
8
+ # (never rendered), so the remediation strips it wherever it rides.
9
+
10
+ let(:remediation) do
11
+ described_class.new(
12
+ id: "enable_background_removal",
13
+ description: "Remove enable-background",
14
+ targets: ["allowed_elements"],
15
+ attributes: ["enable-background"],
16
+ )
17
+ end
18
+
19
+ let(:document) { SvgConform::Document.from_content(src) }
20
+
21
+ context "with enable-background on the root svg element" do
22
+ let(:src) do
23
+ <<~SVG
24
+ <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"
25
+ enable-background="new 0 0 10 10">
26
+ <rect width="5" height="5"/>
27
+ </svg>
28
+ SVG
29
+ end
30
+
31
+ it "removes the attribute" do
32
+ changes = remediation.apply(document, nil)
33
+
34
+ expect(changes.map { |c| c[:attribute] }).to eq(["enable-background"])
35
+ expect(document.to_xml).not_to include("enable-background")
36
+ end
37
+
38
+ it "leaves every other attribute in place" do
39
+ remediation.apply(document, nil)
40
+
41
+ expect(document.to_xml).to include(%(width="10"))
42
+ expect(document.to_xml).to include(%(height="10"))
43
+ end
44
+ end
45
+
46
+ context "with enable-background on nested elements" do
47
+ let(:src) do
48
+ <<~SVG
49
+ <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10">
50
+ <g enable-background="new">
51
+ <rect enable-background="new" width="5" height="5"/>
52
+ </g>
53
+ </svg>
54
+ SVG
55
+ end
56
+
57
+ it "removes every occurrence" do
58
+ changes = remediation.apply(document, nil)
59
+
60
+ expect(changes.size).to eq(2)
61
+ expect(document.to_xml).not_to include("enable-background")
62
+ end
63
+ end
64
+
65
+ context "with the attribute absent" do
66
+ let(:src) do
67
+ <<~SVG
68
+ <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10">
69
+ <rect width="5" height="5"/>
70
+ </svg>
71
+ SVG
72
+ end
73
+
74
+ it "reports no changes" do
75
+ expect(remediation.apply(document, nil)).to be_empty
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "spec_helper"
4
+ require "yeptris/psych"
5
+
6
+ RSpec.describe "SvgConform" do
7
+ it "uses yeptris for lutaml-model YAML serialization" do
8
+ expect(Lutaml::Model::Config.yaml_adapter_type).to eq(:yeptris)
9
+ end
10
+
11
+ Dir.glob(File.join(SvgConform::Profile::PROFILES_DIR, "*.yml")).each do |path|
12
+ it "loads the bundled #{File.basename(path)} profile through yeptris" do
13
+ expect(Lutaml::Yaml::Adapter::YeptrisAdapter).to receive(:parse).and_call_original
14
+
15
+ profile = SvgConform::Profile.load_from_file(path)
16
+ expected = Psych.safe_load_file(path)
17
+
18
+ expect(profile.name).to eq(expected.fetch("name"))
19
+ expect(profile.requirements.map(&:id))
20
+ .to eq(expected.fetch("requirements", []).map { |requirement| requirement.fetch("id") })
21
+ expect(Array(profile.remediations).map(&:id))
22
+ .to eq(expected.fetch("remediations", []).map { |remediation| remediation.fetch("id") })
23
+ end
24
+ end
25
+
26
+ it "loads conformance reports through yeptris" do
27
+ expect(Lutaml::Yaml::Adapter::YeptrisAdapter).to receive(:parse).and_call_original
28
+
29
+ report = SvgConform::ConformanceReport.from_yaml(<<~YAML)
30
+ filename: example.svg
31
+ valid: false
32
+ errors:
33
+ total_count: 1
34
+ by_requirement:
35
+ viewbox_required: 1
36
+ issues:
37
+ - requirement_id: viewbox_required
38
+ message: Missing viewBox
39
+ line: 2
40
+ YAML
41
+
42
+ expect(report.filename).to eq("example.svg")
43
+ expect(report.valid).to be(false)
44
+ expect(report.errors.total_count).to eq(1)
45
+ expect(report.errors.by_requirement).to eq("viewbox_required" => 1)
46
+ expect(report.errors.issues.first.message).to eq("Missing viewBox")
47
+ expect(report.errors.issues.first.line).to eq(2)
48
+ end
49
+
50
+ it "rejects non-permitted Ruby object tags in model YAML" do
51
+ yaml = "filename: !ruby/object:OpenStruct {}\nvalid: false\n"
52
+
53
+ expect { SvgConform::ConformanceReport.from_yaml(yaml) }
54
+ .to raise_error(Yeptris::Psych::DisallowedClass, /OpenStruct/)
55
+ end
56
+
57
+ it "decodes binary values in model YAML" do
58
+ report = SvgConform::ConformanceReport.from_yaml("filename: !!binary aGVsbG8=\n")
59
+
60
+ expect(report.filename).to eq("hello")
61
+ end
62
+
63
+ it "wraps malformed profile YAML in lutaml-model's format error" do
64
+ expect { SvgConform::Profile.from_yaml("name: [unclosed\n") }
65
+ .to raise_error(Lutaml::Model::InvalidFormatError)
66
+ end
67
+
68
+ it "wraps malformed conformance report YAML in lutaml-model's format error" do
69
+ expect { SvgConform::ConformanceReport.from_yaml("filename: \"x\n valid: : :\n") }
70
+ .to raise_error(Lutaml::Model::InvalidFormatError)
71
+ end
72
+
73
+ it "preserves the Psych alias rejection class for model YAML" do
74
+ expect do
75
+ SvgConform::ConformanceReport.from_yaml("a: &x foo.svg\nfilename: *x\n")
76
+ end.to raise_error(Psych::AliasesNotEnabled)
77
+ end
78
+
79
+ it "preserves the standard adapter's emitted bytes for non-ASCII model text" do
80
+ report = SvgConform::ConformanceReport.new(filename: "émoji 🚀")
81
+ expected = Lutaml::Model::Config.with_adapter(yaml: :standard_yaml) do
82
+ report.to_yaml
83
+ end
84
+
85
+ expect(report.to_yaml).to eq(expected)
86
+ end
87
+
88
+ it "keeps lib free of yaml requires and bare YAML or Psych calls" do
89
+ lib_dir = File.expand_path("../../lib", __dir__)
90
+ forbidden = /\brequire\s*(?:\(\s*)?["']yaml["']|(?<![\w:])(?:::)?(?:YAML|Psych)\s*\./
91
+ violations = Dir.glob("#{lib_dir}/**/*").select { |path| File.file?(path) }
92
+ .flat_map do |path|
93
+ File.readlines(path).each_with_index.filter_map do |line, index|
94
+ next unless line.match?(forbidden)
95
+
96
+ "#{path.delete_prefix("#{lib_dir}/")}:#{index + 1}: #{line.strip}"
97
+ end
98
+ end
99
+
100
+ expect(violations).to be_empty,
101
+ "Use SvgConform::YamlIO or Yeptris::Psych in lib/:\n#{violations.join("\n")}"
102
+ end
103
+ end
data/svg_conform.gemspec CHANGED
@@ -35,9 +35,9 @@ Gem::Specification.new do |spec|
35
35
  # crashed on strict bundler deployments, claricle/svg_conform#130).
36
36
  # lens_core 0.1.0 is published, so the 0.2.5-era optionality is obsolete.
37
37
  spec.add_dependency "lens_core", "~> 0.1"
38
+ spec.add_dependency "leptris", "~> 1.9"
38
39
  spec.add_dependency "lutaml-model", "~> 0.8.155"
39
40
  spec.add_dependency "moxml", "~> 0.6.0"
40
- spec.add_dependency "nokogiri", "~> 1.16"
41
41
  spec.add_dependency "rainbow"
42
42
  spec.add_dependency "table_tennis"
43
43
  spec.add_dependency "thor"