moxml 0.6.39 → 0.6.40

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: 9a3825786316eb0e4eea1f6f1e3d25ba4de5b109ff34feab2ef44f7504804850
4
- data.tar.gz: 6422ea830af8635c41fe91b9d377d04d459a6d8c89c885df8a02fa377717bdc5
3
+ metadata.gz: 53fc6b23bdae5df14ca830b2a616efecc34f82e0e564698da620350d80785c78
4
+ data.tar.gz: 2490af752bb90f2da35eaa63092109066ea3945f68876e8a71e679eb02a426e3
5
5
  SHA512:
6
- metadata.gz: 9c5f9b0fdd56ea0833c1d5202a4c30aed5556be00bcffd3967fc6eb8520dfeee3a82630023772def0b4b3d203ec5c2d26cf334f28cf1d4daa4e5b3099fd37ea8
7
- data.tar.gz: 22bbe7083e456b6f2b7f772c57770058b3e726e2fcef3518451afa4ed7a7bc62e2115173aae5510d0a1c180546b815189e020d5878c2d3088fdae9f4a3356509
6
+ metadata.gz: c8f6c67261a307cf3ef686ace814f8e1f0959885a33523781680472b4d09c82b23206181809568aa9a23a4c7b8e02cf5fe7f279178596b17369e497b2fce8cb9
7
+ data.tar.gz: c9b2566f9febf3071ceae8f5ebbf38f5c8d4573bdc525b0ca4bbb1233d98d0e69f42f6b906a3720367a16919493b591fdd3f5237435087f7ab316d5e00d9a3f9
data/README.adoc CHANGED
@@ -1148,8 +1148,19 @@ element.add_namespace('dc', 'http://purl.org/dc/elements/1.1/')
1148
1148
 
1149
1149
  # Create element in namespace
1150
1150
  title = doc.create_element('dc:title')
1151
+
1152
+ # Declare the default namespace — "xmlns" names are declarations
1153
+ element['xmlns'] = 'http://example.org/library'
1151
1154
  ----
1152
1155
 
1156
+ An element declares a prefix once, on every adapter: declaring the URI
1157
+ it already declares is a no-op, and a different URI over an existing
1158
+ declaration raises `Moxml::NamespaceError` — remove the declaration
1159
+ first (`element.remove_namespace(prefix)`) or declare on the element
1160
+ that should carry the new binding. Removal is a named
1161
+ `Moxml::NotImplementedError` on the adapters whose engine has no
1162
+ removal face (nokogiri, libxml).
1163
+
1153
1164
  For complete documentation on XPath querying, namespace handling, and accessing native implementations, see link:docs/_guides/advanced-features.adoc[Advanced Features Guide].
1154
1165
 
1155
1166
 
@@ -254,8 +254,11 @@ Elements are the primary structural nodes with tag names, attributes, and childr
254
254
  | ✅ Yes
255
255
 
256
256
  | `#add_namespace(prefix, uri)`
257
- | Adds a namespace definition
257
+ | Declares the prefix on the element — once: the URI already declared is a no-op, a different URI raises `Moxml::NamespaceError`
258
258
  | ✅ Yes
259
+ | `#remove_namespace(prefix)`
260
+ | Removes the element's declaration of the prefix; a named `Moxml::NotImplementedError` where the engine has no removal face
261
+ | ✅ Yes (nokogiri, libxml: error)
259
262
  |===
260
263
 
261
264
  ==== Attribute Methods
@@ -54,11 +54,24 @@ Attributes::
54
54
  `Moxml::AttributeResolver` — expanded-name resolution lives above the
55
55
  adapter), `set_attribute_value`, `remove_attribute`,
56
56
  `patch_node`/`unpatch_node` for engines needing wrapper natives
57
- (libxml, ox).
57
+ (libxml, ox). A namespace-declaration name (`xmlns`, `xmlns:p`) never
58
+ reaches these: the resolver routes it to the declaration faces below
59
+ (#653).
58
60
 
59
61
  Namespaces::
60
62
  `namespace`, `namespace_definitions` (the element's own declarations),
61
- `in_scope_namespaces`, `set_namespace`, `remove_namespace`.
63
+ `in_scope_namespaces`, `create_namespace` / `create_native_namespace`
64
+ (declaration — the wrapper applies the one-declaration rule first: the
65
+ URI already declared is a no-op, a different URI is a named error),
66
+ `set_namespace`, `remove_namespace_definition` (the declaration's
67
+ removal; the base takes the raw attribute spelling for engines that
68
+ keep declarations among attributes — rexml, ox — leptris and oga have
69
+ faces of their own, and nokogiri and libxml have none and raise
70
+ `Moxml::NotImplementedError`), `namespace_resolves_runtime_declarations?`
71
+ (whether the engine's element→namespace link follows a default
72
+ declaration added at runtime) with `rebind_default_subtree` (the
73
+ binding handed to the existing unprefixed descendants where it does
74
+ not — nokogiri and libxml; the base is a no-op).
62
75
 
63
76
  Mutation::
64
77
  `add_child`, `add_next_sibling`, `add_previous_sibling`, `remove`,
@@ -197,4 +197,17 @@ space (XML 1.0 §3.3.3). The committed answer is the escaped form
197
197
  (nokogiri, leptris emit it). Pinned in
198
198
  `spec/consistency/serialization_family_spec.rb` (the family pins
199
199
  the primary adapters).
200
+
201
+ | D-26
202
+ | oga
203
+ | A default namespace declared at RUNTIME on an ancestor overrides
204
+ the default declarations of the descendants: after
205
+ `root.add_namespace(nil, uri)`, an `<i xmlns="…">` island below the
206
+ root and its children resolve to the runtime URI instead of their own
207
+ (parsed documents resolve correctly; leptris, nokogiri, libxml, rexml
208
+ and ox answer the island's own declaration after the same write).
209
+ Oga's registration path flushes its namespace caches and the
210
+ nearest-declaration precedence is lost. Pinned in
211
+ `spec/consistency/namespace_declarations_spec.rb`. Decided permanent
212
+ with the adapter's deprecation (#552).
200
213
  |===
@@ -28,6 +28,9 @@ Generated by `bundle exec rake docs:coverage` from the coverage matrix and the d
28
28
  | document order of mixed node-sets | equivalent | equivalent | equivalent | equivalent | equivalent | equivalent | equivalent
29
29
  | name resolution | equivalent | equivalent | equivalent | equivalent | equivalent | equivalent | equivalent
30
30
  | namespace resolution and bindings normalization | equivalent | equivalent | equivalent | equivalent | equivalent | equivalent | equivalent
31
+ | namespace declaration writes | equivalent | equivalent | equivalent | equivalent | equivalent | equivalent | equivalent
32
+ | namespace declaration removal | loud (NotImplementedError) | equivalent | equivalent | equivalent | equivalent | loud (NotImplementedError) | equivalent
33
+ | default declaration reach | equivalent | D-26 | equivalent | equivalent | equivalent | equivalent | equivalent
31
34
  | attribute access | equivalent | equivalent | equivalent | equivalent | equivalent | equivalent | equivalent
32
35
  | text/content/raw_content | equivalent | equivalent | equivalent | equivalent | equivalent | equivalent | equivalent
33
36
  | parsing modes and diagnostics | equivalent | equivalent | equivalent | equivalent | equivalent | equivalent | equivalent
@@ -108,7 +108,7 @@ Pins:: `spec/consistency/adapter_parity_spec.rb`, `spec/consistency/xpath_idioms
108
108
 
109
109
  === Names and namespaces
110
110
 
111
- Pins:: `spec/consistency/xpath_idioms_spec.rb`
111
+ Pins:: `spec/consistency/namespace_declarations_spec.rb`, `spec/consistency/xpath_idioms_spec.rb`
112
112
 
113
113
  * Names are **expanded names**: a name test matches by namespace *URI*,
114
114
  never by prefix spelling.
@@ -132,6 +132,29 @@ Pins:: `spec/consistency/xpath_idioms_spec.rb`
132
132
  deduplicated or re-ordered keeps the wrappers, never their natives.
133
133
  A namespace node's `name()` is its prefix, its string-value its URI,
134
134
  and its `namespace-uri()` the empty string.
135
+ * Namespace declarations are not attributes. `xmlns` and `xmlns:*` are
136
+ declarations: a read through the attribute face answers `nil`, and
137
+ the attribute listings omit them. A write — `element["xmlns"] = uri`,
138
+ `element["xmlns:p"] = uri`, or `add_namespace` — declares the prefix
139
+ on that element, so children and prefixed names resolve against it,
140
+ and `remove_attribute` of such a name removes the declaration. An
141
+ element declares a prefix **at most once**: declaring the URI already
142
+ declared is a no-op, and a different URI over an existing declaration
143
+ raises `Moxml::NamespaceError` (remove the declaration first, or
144
+ declare on the element that should carry the new binding) — never a
145
+ duplicate `xmlns` attribute, an ignored write, or a silent
146
+ replacement. A declaration made by a write is one exactly as a
147
+ declaration parsed with the document is — in resolution, in the
148
+ serialized form, and in removal. An engine without a
149
+ declaration-removal face (nokogiri, libxml) answers
150
+ `Moxml::NotImplementedError` for the removal.
151
+ * A default declaration reaches the unprefixed elements already below
152
+ the declaring element — the binding a node attached under it gets —
153
+ and the lane's own XPath answers the same namespace; a descendant
154
+ that declares a default of its own governs itself and its subtree.
155
+ An empty default declaration (`xmlns=""`) undeclares: unprefixed
156
+ elements below it are in no namespace, and nothing further out
157
+ applies.
135
158
  * The `namespace::` axis, and any expression evaluated with an
136
159
  attribute or namespace node as the context node, run on the
137
160
  reference engine on every adapter: the native lanes either lack the
@@ -159,7 +182,10 @@ values are entity-restored when the document bears markers.
159
182
  `attribute_pairs` is the read-only listing ([name, value] pairs,
160
183
  document order, duplicates included). `remove_attribute` returns the
161
184
  removed attribute or nil — including for namespace-prefixed targets
162
- with an unambiguous local name.
185
+ with an unambiguous local name. A namespace-declaration name (`xmlns`,
186
+ `xmlns:p`) is not an attribute: the read answers nil, the write
187
+ declares, and the removal takes the declaration away and answers nil
188
+ (§Names and namespaces).
163
189
 
164
190
  `remove`/mutation returns:: Mutators return the contract object
165
191
  (removed node, new node) — never a silent no-op self.
@@ -500,6 +500,19 @@ namespace_validation_mode: :strict)
500
500
  create_native_namespace(element, prefix, uri)
501
501
  end
502
502
 
503
+ # Remove the element's own declaration of +prefix+ (nil = the
504
+ # default namespace; the wrapper has checked it is declared).
505
+ # The default is the raw removal of the declaration's spelling:
506
+ # engines that keep declarations among the attributes (rexml,
507
+ # ox) remove them that way. An engine with a declaration face
508
+ # or registry of its own overrides (leptris, oga); one with no
509
+ # removal at all raises Moxml::NotImplementedError (nokogiri,
510
+ # libxml) — never a silent no-op (#653).
511
+ def remove_namespace_definition(element, prefix)
512
+ remove_attribute(element, prefix ? "xmlns:#{prefix}" : "xmlns")
513
+ nil
514
+ end
515
+
503
516
  def create_entity_reference(name, owner_doc = nil)
504
517
  validate_entity_reference_name(name)
505
518
  create_native_entity_reference(name, owner_doc)
@@ -821,6 +834,21 @@ namespace_validation_mode: :strict)
821
834
  true
822
835
  end
823
836
 
837
+ # Whether the engine's element→namespace link follows a default
838
+ # declaration added at runtime: libxml2 never re-resolves nodes
839
+ # that existed before the declaration (Nokogiri and libxml
840
+ # answer false), so the wrapper hands them the binding at
841
+ # declaration time (#655).
842
+ def namespace_resolves_runtime_declarations?
843
+ true
844
+ end
845
+
846
+ # Give the element's EXISTING unprefixed descendants the binding
847
+ # a node attached under a default declaration gets. Engines
848
+ # whose link already follows the declaration need nothing;
849
+ # libxml2's do not (Nokogiri and libxml override).
850
+ def rebind_default_subtree(_element, _namespace); end
851
+
824
852
  # Returns all namespaces in scope for this element, including
825
853
  # inherited from ancestors. Adapters with native support (Nokogiri)
826
854
  # override this. Default walks the ancestor chain.
@@ -2347,6 +2347,16 @@ module Moxml
2347
2347
  element.add_namespace_definition(prefix, uri)
2348
2348
  end
2349
2349
 
2350
+ # The engine's declaration face (present on the binding floor,
2351
+ # 1.9.462.0); the raw attribute removal raises "Not found"
2352
+ # here — a declaration was never an attribute on this lane
2353
+ # (#653).
2354
+ def remove_namespace_definition(element, prefix)
2355
+ element = to_binding(element) if NATIVE_READ_LAYER
2356
+ element.remove_namespace_definition(prefix)
2357
+ nil
2358
+ end
2359
+
2350
2360
  def set_namespace(node, namespace)
2351
2361
  node = to_binding(node) if NATIVE_READ_LAYER
2352
2362
  if node.is_a?(::Leptris::XML::Attr) || node.is_a?(SnapshotAttribute)
@@ -1019,6 +1019,18 @@ module Moxml
1019
1019
  ns
1020
1020
  end
1021
1021
 
1022
+ # libxml-ruby exposes readers only on XML::Namespace — no
1023
+ # removal face; a named error where the raw attribute removal
1024
+ # used to leave the declaration in place (#653).
1025
+ def remove_namespace_definition(_element, prefix)
1026
+ raise Moxml::NotImplementedError.new(
1027
+ "removing the declaration of #{prefix ? "prefix #{prefix.inspect}" : 'the default namespace'} " \
1028
+ "is not supported by the libxml adapter",
1029
+ feature: "remove_namespace_definition",
1030
+ adapter: name,
1031
+ )
1032
+ end
1033
+
1022
1034
  def set_namespace(element, ns)
1023
1035
  native_elem = unpatch_node(element)
1024
1036
  return element unless native_elem
@@ -1063,6 +1075,19 @@ module Moxml
1063
1075
  namespace_list.to_a
1064
1076
  end
1065
1077
 
1078
+ # libxml2 binds a node attached under a default declaration but
1079
+ # never revisits the nodes that were already there (#655).
1080
+ def namespace_resolves_runtime_declarations?
1081
+ false
1082
+ end
1083
+
1084
+ # Give those nodes the binding at declaration time, on the
1085
+ # native tree (unpatched: the walk reads no wrappers).
1086
+ def rebind_default_subtree(element, namespace)
1087
+ native = unpatch_node(element)
1088
+ bind_default_below(native, namespace) if native
1089
+ end
1090
+
1066
1091
  # Doctype accessor methods
1067
1092
  def doctype_name(native)
1068
1093
  # LibXML uses DoctypeWrapper which stores the values
@@ -1261,6 +1286,26 @@ module Moxml
1261
1286
 
1262
1287
  private
1263
1288
 
1289
+ # Only unprefixed, still-unbound elements, and only where no
1290
+ # descendant of the declaring element carries a default
1291
+ # declaration of its own (an empty one undeclares): such an
1292
+ # element governs itself and its subtree (#655).
1293
+ def bind_default_below(element, namespace)
1294
+ element.each_child do |child|
1295
+ next unless child.element?
1296
+
1297
+ scopes = child.namespaces
1298
+ next unless scopes
1299
+
1300
+ next if scopes.definitions.any? { |definition| definition.prefix.to_s.empty? }
1301
+
1302
+ if scopes.namespace.nil? && !child.name.to_s.include?(":")
1303
+ scopes.namespace = namespace
1304
+ end
1305
+ bind_default_below(child, namespace)
1306
+ end
1307
+ end
1308
+
1264
1309
  def import_and_add(doc, element, child)
1265
1310
  return unless element && child
1266
1311
 
@@ -418,6 +418,19 @@ module Moxml
418
418
  element.add_namespace_definition(prefix, uri)
419
419
  end
420
420
 
421
+ # libxml2 exposes no declaration removal through Nokogiri (no
422
+ # public face on Node or Namespace) — a named error, where the
423
+ # raw attribute removal used to answer nil and leave the
424
+ # declaration in place (#653).
425
+ def remove_namespace_definition(_element, prefix)
426
+ raise Moxml::NotImplementedError.new(
427
+ "removing the declaration of #{prefix ? "prefix #{prefix.inspect}" : 'the default namespace'} " \
428
+ "is not supported by the nokogiri adapter",
429
+ feature: "remove_namespace_definition",
430
+ adapter: name,
431
+ )
432
+ end
433
+
421
434
  def node_type(node)
422
435
  case node
423
436
  when ::Nokogiri::XML::Element then :element
@@ -633,6 +646,19 @@ module Moxml
633
646
  node.namespace_definitions
634
647
  end
635
648
 
649
+ # libxml2 binds a node attached under a default declaration but
650
+ # never revisits the nodes that were already there (#655).
651
+ def namespace_resolves_runtime_declarations?
652
+ false
653
+ end
654
+
655
+ # Give those nodes the binding at declaration time, on the
656
+ # native tree: the wrapper reads and the native XPath then
657
+ # agree with the serialized form.
658
+ def rebind_default_subtree(element, namespace)
659
+ bind_default_below(element, namespace)
660
+ end
661
+
636
662
  def in_scope_namespaces(element)
637
663
  element.namespace_scopes
638
664
  end
@@ -761,6 +787,22 @@ module Moxml
761
787
 
762
788
  private
763
789
 
790
+ # Only unprefixed, still-unbound elements, and only where no
791
+ # descendant of the declaring element carries a default
792
+ # declaration of its own (an empty one undeclares): such an
793
+ # element governs itself and its subtree (#655).
794
+ def bind_default_below(element, namespace)
795
+ element.children.each do |child|
796
+ next unless child.element?
797
+ next if child.namespace_definitions.any? { |definition| definition.prefix.nil? }
798
+
799
+ if child.namespace.nil? && !child.name.include?(":")
800
+ child.namespace = namespace
801
+ end
802
+ bind_default_below(child, namespace)
803
+ end
804
+ end
805
+
764
806
  def build_declaration_attrs(version, encoding, standalone)
765
807
  attrs = { "version" => version }
766
808
  attrs["encoding"] = encoding if encoding
@@ -196,6 +196,34 @@ module Moxml
196
196
  ::Oga::XML::Namespace.new(name: prefix, uri: uri)
197
197
  end
198
198
 
199
+ # The raw removal takes the declaration out of the tree, but Oga
200
+ # keeps the element's declarations in a hash of its own and
201
+ # serves it from a cache: the registration goes with the
202
+ # attribute (#653). Both are matched by what they ARE — a name
203
+ # in the xmlns namespace — because Oga's prefixed lookup
204
+ # resolves "xmlns:" through the registered namespaces and
205
+ # misses a declaration made at runtime; a parsed default is
206
+ # registered under "xmlns", a runtime one under nil.
207
+ def remove_namespace_definition(element, prefix)
208
+ xmlns = ::Oga::XML::Element::XMLNS_PREFIX
209
+ attr = element.attributes.find do |candidate|
210
+ if prefix
211
+ candidate.name == prefix.to_s && candidate.namespace_name == xmlns
212
+ else
213
+ candidate.name == xmlns && candidate.namespace_name.nil?
214
+ end
215
+ end
216
+ element.attributes.delete(attr) if attr
217
+ if prefix
218
+ element.namespaces.delete(prefix)
219
+ else
220
+ element.namespaces.delete(xmlns)
221
+ element.namespaces.delete(nil)
222
+ end
223
+ element.flush_namespaces_cache
224
+ nil
225
+ end
226
+
199
227
  def set_namespace(element, ns_or_string)
200
228
  if ns_or_string.nil?
201
229
  element.namespace_name = nil
@@ -227,7 +255,11 @@ module Moxml
227
255
 
228
256
  element.namespace
229
257
  when ::Oga::XML::Element
230
- element.namespace
258
+ # An empty declaration undeclares (Namespaces 1.0 §5.2):
259
+ # Oga keeps an empty-URI namespace for it; the model
260
+ # answers no namespace (#655).
261
+ resolved = element.namespace
262
+ resolved unless resolved&.uri.to_s.empty?
231
263
  end
232
264
  rescue NoMethodError
233
265
  # Oga attributes fail with NoMethodError:
@@ -234,11 +234,14 @@ module Moxml
234
234
  ([element] + ancestors(element)).each do |node|
235
235
  next unless node.is_a?(::Ox::Element) && node.attributes
236
236
 
237
- if node[attr_name]
238
- return ::Moxml::Adapter::CustomizedOx::Namespace.new(
239
- prefix, node[attr_name], element
240
- )
241
- end
237
+ uri = node[attr_name]
238
+ next if uri.nil?
239
+
240
+ # An empty declaration undeclares (Namespaces 1.0 §5.2):
241
+ # no namespace, and nothing below it to resolve against.
242
+ return nil if uri.to_s.empty?
243
+
244
+ return ::Moxml::Adapter::CustomizedOx::Namespace.new(prefix, uri, element)
242
245
  end
243
246
 
244
247
  nil
@@ -538,6 +538,20 @@ module Moxml
538
538
  ::REXML::Attribute.new(prefix.to_s, uri, element)
539
539
  end
540
540
 
541
+ # REXML keys a default declaration made at runtime as "xmlns:"
542
+ # and one parsed with the document as "xmlns", the Attribute
543
+ # being named "xmlns" either way — a lookup by name finds only
544
+ # the parsed one, so the declaration is found by its shape and
545
+ # removed under its own key.
546
+ def remove_namespace_definition(element, prefix)
547
+ namespace_definitions(element).each do |attr|
548
+ next unless attr.name == (prefix || "xmlns").to_s
549
+
550
+ element.attributes.delete(attr.expanded_name)
551
+ end
552
+ nil
553
+ end
554
+
541
555
  # add a namespace prefix to the element name AND a namespace definition
542
556
  def set_namespace(element, ns)
543
557
  if ns.nil?
@@ -16,7 +16,9 @@ module Moxml
16
16
  # prefixes are bound to the same URI.
17
17
  # - "xml" is prebound to the XML namespace URI; it never needs a
18
18
  # declaration (Namespaces 1.0 §4).
19
- # - "xmlns"/"xmlns:*" are declarations, not attributes: never match.
19
+ # - "xmlns"/"xmlns:*" are declarations, not attributes: a read never
20
+ # matches them; a write or removal through this face is the
21
+ # declaration's own (Element#add_namespace / #remove_namespace).
20
22
  # - An undeclared prefix names nothing: nil. No silent prefix-string
21
23
  # or bare-name fallback.
22
24
  #
@@ -80,12 +82,24 @@ module Moxml
80
82
  .find { |candidate| candidate.prefix == prefix }&.uri
81
83
  end
82
84
 
85
+ # "xmlns" / "xmlns:prefix" — exactly those two shapes. An attribute
86
+ # merely starting with the letters ("xmlns:url") is an attribute.
87
+ def declaration_name?(name)
88
+ name == "xmlns" || name.start_with?("xmlns:")
89
+ end
90
+
91
+ # The prefix a declaration name declares: nil for the default.
92
+ def declaration_prefix(name)
93
+ name == "xmlns" ? nil : name.delete_prefix("xmlns:")
94
+ end
95
+
83
96
  # Assign a value to the attribute named by XML-correct resolution,
84
97
  # mirroring #resolve:
85
98
  #
86
99
  # - "xmlns"/"xmlns:*" are namespace declarations, not attributes:
87
- # delegated verbatim to the adapter (declaration creation is
88
- # adapter territory).
100
+ # the write declares the prefix on the element (the one
101
+ # declaration rule — a no-op for the URI already declared, a
102
+ # named error over a different one).
89
103
  # - A bare name replaces the no-namespace attribute only — a
90
104
  # namespaced attribute sharing the local name is left alone.
91
105
  # - A prefixed name replaces by expanded name: assigning p:x
@@ -103,21 +117,19 @@ module Moxml
103
117
  # @return [String] the assigned value
104
118
  def assign(element, name, value)
105
119
  name = name.to_s
106
- adapter = element.adapter
107
- # One probe covers both spellings ("xmlns" and "xmlns:*"); a
108
- # plain attribute literally starting with "xmlns" would only
109
- # over-invalidate (global bump instead of local) — a no-op
110
- # for correctness.
111
- if name.start_with?("xmlns")
112
- # Introducing (or rewriting) a namespace declaration: mark the
113
- # context BEFORE the invalidation, so this write's generation
114
- # bump fans out to every wrapper's memoized scope reads.
115
- element.context.mark_namespaces_active!
116
- adapter.set_attribute(element.native, name, value)
120
+ # "xmlns" and "xmlns:p" are declarations, not attributes: the
121
+ # write declares the prefix through the one declaration rule
122
+ # (Element#add_namespace) — never a raw attribute the engine may
123
+ # duplicate, ignore, or store as a look-alike (#653).
124
+ if declaration_name?(name)
125
+ value = value.to_s
126
+ element.add_namespace(declaration_prefix(name), value)
117
127
  element.invalidate_attribute_cache!
118
128
  return value
119
129
  end
120
130
 
131
+ adapter = element.adapter
132
+
121
133
  # Fast path: every adapter's set_attribute writes by qualified
122
134
  # name, and XML cannot namespace an unprefixed attribute — so
123
135
  # a bare-name set replaces only the no-namespace attribute and
@@ -159,13 +171,16 @@ module Moxml
159
171
  # @return [Moxml::Attribute, nil] the removed attribute
160
172
  def remove(element, name)
161
173
  name = name.to_s
162
- adapter = element.adapter
163
- if name.start_with?("xmlns")
164
- adapter.remove_attribute(element.native, name)
174
+ # A declaration is not an attribute: nothing attribute-shaped is
175
+ # handed back; the declaration itself goes (#653).
176
+ if declaration_name?(name)
177
+ element.remove_namespace(declaration_prefix(name))
165
178
  element.invalidate_attribute_cache!
166
179
  return nil
167
180
  end
168
181
 
182
+ adapter = element.adapter
183
+
169
184
  attr = resolve(element, name)
170
185
  attr ||= resolve_unique_local(element, name) unless name.include?(":")
171
186
 
data/lib/moxml/element.rb CHANGED
@@ -287,24 +287,45 @@ module Moxml
287
287
  self
288
288
  end
289
289
 
290
+ # Declare +prefix+ (nil = the default namespace) as +uri+ on THIS
291
+ # element — the one primitive behind the Builder's xmlns: keys,
292
+ # the attribute face (element["xmlns"] / element["xmlns:p"]) and
293
+ # default_namespace= (model §Names and namespaces).
294
+ #
295
+ # An element declares a prefix at most once: declaring the URI it
296
+ # already declares is a no-op, and a different URI over an existing
297
+ # declaration raises Moxml::NamespaceError. XML has no second
298
+ # declaration of one prefix on an element, and no engine offers a
299
+ # safe in-place rebind — the lanes used to answer four ways
300
+ # (a duplicate xmlns attribute on leptris/oga/rexml, an ignored
301
+ # write on nokogiri, a silent replacement on ox; #653). Remove the
302
+ # declaration first (#remove_namespace), or declare on the element
303
+ # that should carry the new binding.
304
+ #
305
+ # @return [self]
290
306
  def add_namespace(prefix, uri)
291
- adapter.create_namespace(@native, prefix, uri,
292
- namespace_validation_mode: context.config.namespace_validation_mode)
293
- context.mark_namespaces_active!
307
+ declare_namespace(prefix, uri)
294
308
  invalidate_namespace_cache!
295
309
  self
296
- rescue ValidationError => e
297
- # Re-raise as NamespaceError, provide attributes for error context
298
- # but the to_s will only add details if provided
299
- raise Moxml::NamespaceError.new(
300
- e.message,
301
- prefix: prefix,
302
- uri: uri,
303
- element: self,
304
- )
305
310
  end
306
311
  alias add_namespace_definition add_namespace
307
312
 
313
+ # Remove THIS element's declaration of +prefix+ (nil = the default
314
+ # namespace); nothing happens when it declares no such prefix.
315
+ # Nodes bound through the declaration resolve as their engine then
316
+ # sees scope. Engines without a declaration-removal face raise
317
+ # Moxml::NotImplementedError (nokogiri, libxml — #653).
318
+ #
319
+ # @return [self]
320
+ def remove_namespace(prefix)
321
+ prefix = nil if prefix.to_s.empty?
322
+ return self unless declared_namespace(prefix)
323
+
324
+ adapter.remove_namespace_definition(@native, prefix)
325
+ invalidate_namespace_cache!
326
+ self
327
+ end
328
+
308
329
  # it's NOT the same as namespaces.first
309
330
  # Per-read namespace resolution pays an FFI fetch plus a wrapper
310
331
  # mint on every call (moxml#329: a top attribution site in the
@@ -324,11 +345,8 @@ module Moxml
324
345
  # and add the namespace to the list of namespace definitions
325
346
  def namespace=(ns_or_hash)
326
347
  if ns_or_hash.is_a?(Hash)
327
- adapter.set_namespace(
328
- @native,
329
- adapter.create_namespace(@native, *ns_or_hash.to_a.first,
330
- namespace_validation_mode: context.config.namespace_validation_mode),
331
- )
348
+ prefix, uri = ns_or_hash.to_a.first
349
+ adapter.set_namespace(@native, declare_namespace(prefix, uri))
332
350
  else
333
351
  adapter.set_namespace(@native, ns_or_hash&.native)
334
352
  end
@@ -338,9 +356,9 @@ module Moxml
338
356
  # Nokogiri-compatible: bind the element to +uri+ as its DEFAULT
339
357
  # namespace — the name drops any prefix and the declaration lands
340
358
  # on this element. Children keep their own bindings. Skip when an
341
- # identical default namespace is already in scope: declaring again
342
- # serializes a duplicate xmlns attribute. (add_namespace is the
343
- # primitive: namespace=({nil => uri}) declares twice on leptris.)
359
+ # identical default namespace is already in scope: the element
360
+ # would carry a redundant declaration below the one already
361
+ # binding it.
344
362
  def default_namespace=(uri)
345
363
  self.name = name.split(":", 2)[-1] if name.to_s.include?(":")
346
364
  return if namespace_prefix.to_s.empty? && namespace_uri.to_s == uri.to_s
@@ -563,6 +581,55 @@ module Moxml
563
581
  @in_scope_namespaces = nil
564
582
  context.bump_namespace_scope_generation
565
583
  end
584
+
585
+ private
586
+
587
+ # The one declaration rule (see #add_namespace). Answers the native
588
+ # of the declaration in effect afterwards: the existing one on the
589
+ # no-op path, the fresh one otherwise.
590
+ def declare_namespace(prefix, uri)
591
+ prefix = nil if prefix.to_s.empty?
592
+ uri = uri.to_s
593
+ if (current = declared_namespace(prefix)) && current.uri != uri
594
+ raise Moxml::NamespaceError.new(
595
+ "already declares #{prefix ? "prefix #{prefix.inspect}" : 'the default namespace'} " \
596
+ "as #{current.uri.inspect}; remove the declaration to rebind it as #{uri.inspect}",
597
+ prefix: prefix,
598
+ uri: uri,
599
+ element: self,
600
+ )
601
+ end
602
+ return current.native if current
603
+
604
+ # Marked BEFORE the creation: the caller's invalidation bumps the
605
+ # scope generation only while scopes are active, and this write's
606
+ # bump must fan out to every wrapper's memoized scope reads.
607
+ context.mark_namespaces_active!
608
+ created = adapter.create_namespace(@native, prefix, uri,
609
+ namespace_validation_mode: context.config.namespace_validation_mode)
610
+ # A default declaration reaches the unprefixed elements already
611
+ # below, exactly as a node attached under it is bound (#655) —
612
+ # on the engines whose link does not follow the declaration.
613
+ if prefix.nil? && !adapter.namespace_resolves_runtime_declarations?
614
+ adapter.rebind_default_subtree(@native, created)
615
+ end
616
+ created
617
+ rescue ValidationError => e
618
+ # Re-raise as NamespaceError, provide attributes for error context
619
+ # but the to_s will only add details if provided
620
+ raise Moxml::NamespaceError.new(e.message, prefix: prefix, uri: uri, element: self)
621
+ end
622
+
623
+ # This element's OWN declaration of +prefix+ (nil = the default
624
+ # namespace) as a Namespace wrapper, or nil. Read off the adapter,
625
+ # not the memo: the declaration memo lags this very write.
626
+ def declared_namespace(prefix)
627
+ adapter.namespace_definitions(@native).each do |native|
628
+ wrapper = owned_namespace(native)
629
+ return wrapper if wrapper.prefix.to_s == prefix.to_s
630
+ end
631
+ nil
632
+ end
566
633
  end
567
634
 
568
635
  module Element
data/lib/moxml/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Moxml
4
- VERSION = "0.6.39"
4
+ VERSION = "0.6.40"
5
5
  end
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Processing model §Names and namespaces (normative): pinned here.
4
+ require "spec_helper"
5
+
6
+ # Namespace declarations are not attributes (#653). "xmlns" and
7
+ # "xmlns:*" name declarations on every adapter: a read answers nil and
8
+ # the attribute listings omit them; a write through the attribute face
9
+ # declares the prefix — a real declaration, never a look-alike
10
+ # attribute — under the one declaration rule: the URI already declared
11
+ # is a no-op, a different URI is a named error, never a duplicate
12
+ # attribute, an ignored write, or a silent replacement. Removal takes
13
+ # the declaration away where the engine has a removal face and is a
14
+ # named NotImplementedError where it has none — never a silent no-op.
15
+ # Engines whose native library exposes no declaration removal.
16
+ NO_REMOVAL_FACE = %i[nokogiri libxml].freeze
17
+
18
+ RSpec.describe "Namespace declarations across adapters" do
19
+ Moxml::Adapter::AVAILABLE_ADAPTERS.each do |adapter_name|
20
+ next if adapter_name == :headed_ox # same engine as :ox
21
+
22
+ context "with #{adapter_name}" do
23
+ let(:ctx) { Moxml.new(adapter_name) }
24
+
25
+ def declarations(element)
26
+ element.namespace_definitions.map { |ns| [ns.prefix, ns.uri] }
27
+ end
28
+
29
+ it "reads xmlns names as no attribute and omits them from the listings" do
30
+ root = ctx.parse('<r xmlns="http://d.org/" xmlns:p="http://p.org/" a="1"/>').root
31
+ expect(root["xmlns"]).to be_nil
32
+ expect(root["xmlns:p"]).to be_nil
33
+ expect(root.attribute_pairs.map(&:first)).to eq(["a"])
34
+ expect(declarations(root)).to contain_exactly([nil, "http://d.org/"], ["p", "http://p.org/"])
35
+ end
36
+
37
+ it "declares a fresh prefix through the attribute face" do
38
+ root = ctx.parse("<r><a/></r>").root
39
+ root["xmlns"] = "http://d.org/"
40
+ root["xmlns:p"] = "http://p.org/"
41
+
42
+ expect(declarations(root)).to contain_exactly([nil, "http://d.org/"], ["p", "http://p.org/"])
43
+ expect(root.to_xml).to include('xmlns="http://d.org/"', 'xmlns:p="http://p.org/"')
44
+ expect(root["xmlns"]).to be_nil
45
+ end
46
+
47
+ it "treats a rewrite with the declared URI as a no-op" do
48
+ root = ctx.parse('<r xmlns="http://d.org/" xmlns:p="http://p.org/"/>').root
49
+ root["xmlns"] = "http://d.org/"
50
+ root["xmlns:p"] = "http://p.org/"
51
+ root.add_namespace(nil, "http://d.org/")
52
+ root.add_namespace("p", "http://p.org/")
53
+
54
+ expect(root.to_xml.scan("xmlns=").size).to eq(1)
55
+ expect(root.to_xml.scan("xmlns:p=").size).to eq(1)
56
+ expect(declarations(root)).to contain_exactly([nil, "http://d.org/"], ["p", "http://p.org/"])
57
+ end
58
+
59
+ # #655: libxml2 binds a node attached under a default declaration
60
+ # but never revisited the nodes already there — the lanes read
61
+ # the same subtree two ways.
62
+ it "lets a default declaration reach the element's existing unprefixed descendants" do
63
+ root = ctx.parse('<r><a><b/></a><i xmlns="http://other.org/"><c/></i><u xmlns=""><d/></u></r>').root
64
+ root.add_namespace(nil, "http://ud.org/")
65
+ local = ->(name) { "*[local-name()='#{name}']" }
66
+ resolved = lambda do |path|
67
+ element = root.at_xpath(path)
68
+ [element.namespace&.uri, element.xpath("namespace-uri(.)").to_s]
69
+ end
70
+
71
+ expect(root.namespace&.uri).to eq("http://ud.org/")
72
+ expect(resolved.call(local.call("a"))).to eq(["http://ud.org/", "http://ud.org/"])
73
+ expect(resolved.call("#{local.call('a')}/#{local.call('b')}")).to eq(["http://ud.org/", "http://ud.org/"])
74
+ # oga's runtime registration overrides the islands' own
75
+ # declarations, the empty one included (D-26).
76
+ unless adapter_name == :oga # D-26
77
+ island = "#{local.call('i')}/#{local.call('c')}"
78
+ expect(resolved.call(island)).to eq(["http://other.org/", "http://other.org/"])
79
+ undeclared = "#{local.call('u')}/#{local.call('d')}"
80
+ expect(resolved.call(undeclared)).to eq([nil, ""])
81
+ end
82
+ expect(root.to_xml[/^<r[^>]*>/]).to eq('<r xmlns="http://ud.org/">')
83
+ end
84
+
85
+ it "names a different URI over a declared prefix instead of duplicating it" do
86
+ root = ctx.parse('<r xmlns="http://d.org/" xmlns:p="http://p.org/"/>').root
87
+ expect { root["xmlns"] = "http://other.org/" }
88
+ .to raise_error(Moxml::NamespaceError) { |error| expect(error.uri).to eq("http://other.org/") }
89
+ expect { root["xmlns:p"] = "http://other.org/" }
90
+ .to raise_error(Moxml::NamespaceError) { |error| expect(error.prefix).to eq("p") }
91
+ expect { root.add_namespace("p", "http://other.org/") }
92
+ .to raise_error(Moxml::NamespaceError)
93
+
94
+ expect(declarations(root)).to contain_exactly([nil, "http://d.org/"], ["p", "http://p.org/"])
95
+ end
96
+
97
+ it "removes a declared prefix, or names the missing face" do
98
+ root = ctx.parse('<r xmlns="http://d.org/" xmlns:p="http://p.org/"/>').root
99
+ if NO_REMOVAL_FACE.include?(adapter_name)
100
+ expect { root.remove_attribute("xmlns") }
101
+ .to raise_error(Moxml::NotImplementedError, /removing the declaration/)
102
+ else
103
+ expect(root.remove_attribute("xmlns:p")).to be_nil
104
+ expect(root.remove_attribute("xmlns")).to be_nil
105
+ expect(declarations(root)).to be_empty
106
+ expect(root.to_xml.strip).to eq("<r></r>")
107
+ end
108
+ expect(root.remove_attribute("xmlns:zz")).to be_nil
109
+ end
110
+
111
+ # A declaration made at runtime goes as completely as one parsed
112
+ # with the document — out of the listings AND out of the
113
+ # serialized form.
114
+ it "removes a declaration made at runtime as completely as a parsed one" do
115
+ root = ctx.parse("<r/>").root
116
+ root["xmlns"] = "http://d.org/"
117
+ root["xmlns:p"] = "http://p.org/"
118
+ expect(root.to_xml).to include('xmlns="http://d.org/"', 'xmlns:p="http://p.org/"')
119
+
120
+ if NO_REMOVAL_FACE.include?(adapter_name)
121
+ expect { root.remove_namespace("p") }
122
+ .to raise_error(Moxml::NotImplementedError, /removing the declaration/)
123
+ expect(declarations(root)).to contain_exactly([nil, "http://d.org/"], ["p", "http://p.org/"])
124
+ else
125
+ expect(root.remove_namespace("p")).to equal(root)
126
+ expect(declarations(root)).to contain_exactly([nil, "http://d.org/"])
127
+ expect(root.to_xml).to include('xmlns="http://d.org/"')
128
+ expect(root.to_xml).not_to include("xmlns:p=")
129
+ expect(root.remove_namespace(nil)).to equal(root)
130
+ expect(declarations(root)).to be_empty
131
+ expect(root.to_xml.strip).to eq("<r></r>")
132
+ end
133
+ end
134
+ end
135
+ end
136
+ end
@@ -67,9 +67,40 @@ RSpec.describe Moxml::AttributeResolver do
67
67
  end
68
68
 
69
69
  describe ".assign" do
70
- it "delegates xmlns declarations to the adapter" do
70
+ def declarations
71
+ element.namespace_definitions.map { |ns| [ns.prefix, ns.uri] }
72
+ end
73
+
74
+ it "declares xmlns names through the declaration face (#653)" do
75
+ described_class.assign(element, "xmlns:r", "http://r.org")
76
+ described_class.assign(element, "xmlns", "http://d.org")
77
+
78
+ expect(doc.to_xml).to include('xmlns:r="http://r.org"', 'xmlns="http://d.org"')
79
+ expect(declarations).to include(["r", "http://r.org"], [nil, "http://d.org"])
80
+ expect(element["xmlns:r"]).to be_nil
81
+ end
82
+
83
+ it "answers the assigned declaration value" do
84
+ expect(described_class.assign(element, "xmlns:r", "http://r.org")).to eq("http://r.org")
85
+ end
86
+
87
+ it "treats a rewrite with the declared URI as a no-op" do
71
88
  described_class.assign(element, "xmlns:r", "http://r.org")
72
- expect(doc.to_xml).to include('xmlns:r="http://r.org"')
89
+ described_class.assign(element, "xmlns:r", "http://r.org")
90
+
91
+ expect(doc.to_xml.scan('xmlns:r="http://r.org"').size).to eq(1)
92
+ end
93
+
94
+ it "names a different URI over a declared prefix" do
95
+ described_class.assign(element, "xmlns:r", "http://r.org")
96
+
97
+ expect { described_class.assign(element, "xmlns:r", "http://other.org") }
98
+ .to raise_error(Moxml::NamespaceError) do |error|
99
+ expect(error.prefix).to eq("r")
100
+ expect(error.uri).to eq("http://other.org")
101
+ expect(error.element).to equal(element)
102
+ end
103
+ expect(declarations).to include(["r", "http://r.org"])
73
104
  end
74
105
 
75
106
  it "replaces the matching attribute in place" do
@@ -98,6 +129,10 @@ RSpec.describe Moxml::AttributeResolver do
98
129
  it "returns nil when nothing matches" do
99
130
  expect(described_class.remove(element, "z:type")).to be_nil
100
131
  end
132
+
133
+ it "answers nil for a declaration name the element does not declare" do
134
+ expect(described_class.remove(element, "xmlns:zz")).to be_nil
135
+ end
101
136
  end
102
137
 
103
138
  describe ".attribute_test?" do
@@ -24,6 +24,21 @@ module ModelCoverage
24
24
  section: "Names and namespaces",
25
25
  pin: "spec/consistency/xpath_idioms_spec.rb",
26
26
  },
27
+ "namespace declaration writes" => {
28
+ section: "Names and namespaces",
29
+ pin: "spec/consistency/namespace_declarations_spec.rb",
30
+ },
31
+ "namespace declaration removal" => {
32
+ section: "Names and namespaces",
33
+ pin: "spec/consistency/namespace_declarations_spec.rb",
34
+ loud: { nokogiri: "Moxml::NotImplementedError",
35
+ libxml: "Moxml::NotImplementedError" },
36
+ },
37
+ "default declaration reach" => {
38
+ section: "Names and namespaces",
39
+ pin: "spec/consistency/namespace_declarations_spec.rb",
40
+ exempt: { oga: "D-26" },
41
+ },
27
42
  "attribute access" => {
28
43
  section: "Access semantics",
29
44
  pin: "spec/moxml/attribute_resolver_spec.rb",
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: moxml
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.39
4
+ version: 0.6.40
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ribose Inc.
@@ -343,6 +343,7 @@ files:
343
343
  - spec/consistency/metamorphic_properties_spec.rb
344
344
  - spec/consistency/metamorphic_spec.rb
345
345
  - spec/consistency/model_coverage_audit_spec.rb
346
+ - spec/consistency/namespace_declarations_spec.rb
346
347
  - spec/consistency/published_docs_spec.rb
347
348
  - spec/consistency/reference_differential_spec.rb
348
349
  - spec/consistency/round_trip_spec.rb