svg_conform 0.2.9 → 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
@@ -215,8 +215,16 @@ module SvgConform
215
215
  def resolve_profile(profile)
216
216
  case profile
217
217
  when Symbol, String
218
- SvgConform::Profiles.get(profile) || raise(ProfileError,
219
- "Unknown profile: #{profile}")
218
+ # A path to a profile file wins over a bundled name: a custom
219
+ # profile ends in .yml and exists on disk, while bundled names
220
+ # never do (claricle/svg_conform#137 - the CLI previously
221
+ # concatenated such paths into config/profiles).
222
+ if profile.to_s.end_with?(".yml") && File.exist?(profile.to_s)
223
+ SvgConform::Profile.load_from_file(profile.to_s)
224
+ else
225
+ SvgConform::Profiles.get(profile) || raise(ProfileError,
226
+ "Unknown profile: #{profile}")
227
+ end
220
228
  when Profile
221
229
  profile
222
230
  else
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module SvgConform
4
- VERSION = "0.2.9"
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
@@ -41,8 +41,12 @@ RSpec.describe "svg_conform.gemspec" do # rubocop:disable RSpec/DescribeClass
41
41
  # guard (ci's words). Without this check, every post-release PR fails
42
42
  # bundler 4's frozen install ("gemspecs for path gems changed") before
43
43
  # anyone sees why.
44
+ # The release flow deletes the lock before bumping; the guard applies
45
+ # only where the committed lock exists (normal CI and dev trees).
46
+ skip "no committed lockfile (release context)" unless File.exist?("Gemfile.lock")
47
+
44
48
  lock = File.read("Gemfile.lock")
45
- 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]
46
50
  expect(path_version).to eq(SvgConform::VERSION)
47
51
  end
48
52
  end
@@ -6,6 +6,17 @@ require "spec_helper"
6
6
  # per SVG (metanorma-pdfa#106).
7
7
  METANORMA_PROFILE_CONTAINER_TAGS = %w[g a defs].freeze
8
8
  METANORMA_PROFILE_CLIP_ATTRIBUTES = %w[clip-path mask].freeze
9
+ METANORMA_PROFILE_SHAPE_TAGS = %w[path rect circle ellipse line polyline polygon].freeze
10
+ METANORMA_PROFILE_SHAPE_QUALITY_ATTRIBUTES = %w[clip-rule opacity].freeze
11
+ METANORMA_PROFILE_SHAPE_GEOMETRY = {
12
+ "path" => 'd="M20,20 H50 V50"',
13
+ "rect" => 'x="20" y="20" width="30" height="30"',
14
+ "circle" => 'cx="35" cy="35" r="15"',
15
+ "ellipse" => 'cx="35" cy="35" rx="15" ry="10"',
16
+ "line" => 'x1="20" y1="35" x2="50" y2="35"',
17
+ "polyline" => 'points="20,35 35,20 50,35"',
18
+ "polygon" => 'points="20,35 35,20 50,35"',
19
+ }.freeze
9
20
 
10
21
  RSpec.describe "Metanorma Profile" do
11
22
  let(:metanorma_sample_profile_path) { "config/profiles/metanorma-sample.yml" }
@@ -111,6 +122,29 @@ RSpec.describe "Metanorma Profile" do
111
122
  end
112
123
  end
113
124
  end
125
+
126
+ # claricle/svg_conform#136: drawing exports carry clip-rule and
127
+ # opacity on every graphics element, not only containers; the sample
128
+ # mirrors the owned baseline (metanorma-standoc#1362).
129
+ METANORMA_PROFILE_SHAPE_TAGS.each do |tag|
130
+ METANORMA_PROFILE_SHAPE_QUALITY_ATTRIBUTES.each do |attribute|
131
+ it "accepts #{attribute} on the shape #{tag}" do
132
+ svg = <<~SVG
133
+ <svg xmlns="http://www.w3.org/2000/svg" version="1.2" baseProfile="tiny" width="70" height="70" viewBox="0 0 70 70">
134
+ <clipPath id="cp">
135
+ <path d="M10,10 H60 V60"/>
136
+ </clipPath>
137
+ <g>
138
+ <#{tag} #{METANORMA_PROFILE_SHAPE_GEOMETRY[tag]} fill="red" #{attribute}="#{attribute == 'clip-rule' ? 'evenodd' : '0.85'}" clip-path="url(#cp)"/>
139
+ </g>
140
+ </svg>
141
+ SVG
142
+ result = validator.validate(svg, profile: profile)
143
+ attribute_errors = result.errors.select { |e| e.message.include?("'#{attribute}'") }
144
+ expect(attribute_errors).to be_empty
145
+ end
146
+ end
147
+ end
114
148
  end
115
149
 
116
150
  def shape_geometry(tag)
@@ -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
@@ -169,4 +169,40 @@ RSpec.describe SvgConform::Validator do
169
169
  # Remediation should have been attempted
170
170
  end
171
171
  end
172
+
173
+ context "with a profile file path (claricle/svg_conform#137)" do
174
+ # the name lookup, so a profile file path was joined onto config/
175
+ # profiles and always failed. An existing .yml path now loads as a
176
+ # profile; anything else keeps the name semantics (including the
177
+ # not-found error listing available profiles).
178
+ describe "profile resolution from a file path" do
179
+ let(:profile_path) do
180
+ File.expand_path("../../config/profiles/metanorma-sample.yml", __dir__)
181
+ end
182
+ let(:tiny_svg) do
183
+ <<~SVG
184
+ <svg xmlns="http://www.w3.org/2000/svg" version="1.2" baseProfile="tiny" width="70" height="70" viewBox="0 0 70 70">
185
+ <rect x="20" y="20" width="30" height="30" fill="red"/>
186
+ </svg>
187
+ SVG
188
+ end
189
+
190
+ it "loads an existing .yml path instead of treating it as a name" do
191
+ validator = described_class.new(mode: :sax, profile: profile_path)
192
+ result = validator.validate(tiny_svg)
193
+ expect(result).to be_valid
194
+ end
195
+
196
+ it "keeps name semantics when the value is not a path on disk" do
197
+ validator = described_class.new(mode: :sax, profile: :"metanorma-sample")
198
+ expect(validator.validate(tiny_svg)).to be_valid
199
+ end
200
+
201
+ it "raises the not-found error, listing profiles, for a missing path" do
202
+ validator = described_class.new(mode: :sax, profile: "/tmp/definitely-missing-9f2.yml")
203
+ expect { validator.validate(tiny_svg) }
204
+ .to raise_error(SvgConform::ProfileError, /not found/i)
205
+ end
206
+ end
207
+ end
172
208
  end