lutaml-model 0.8.203 → 0.8.205

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.
Files changed (122) hide show
  1. checksums.yaml +4 -4
  2. data/.gitattributes +5 -0
  3. data/.github/workflows/lml-conformance.yml +71 -0
  4. data/.gitignore +7 -0
  5. data/README.adoc +1 -0
  6. data/docs/_guides/lml-cross-language.adoc +128 -0
  7. data/docs/_guides/native-engines.adoc +10 -0
  8. data/docs/_references/lml-conformance.adoc +78 -0
  9. data/docs/_references/lml-contract.adoc +290 -0
  10. data/lib/lutaml/model/lml/artifact_verifier.rb +205 -0
  11. data/lib/lutaml/model/lml/bundle.rb +171 -0
  12. data/lib/lutaml/model/lml/document.rb +46 -10
  13. data/lib/lutaml/model/lml/document_validator.rb +840 -0
  14. data/lib/lutaml/model/lml/exporter/v1_projector.rb +102 -0
  15. data/lib/lutaml/model/lml/exporter/v2_projector.rb +401 -0
  16. data/lib/lutaml/model/lml/exporter.rb +223 -87
  17. data/lib/lutaml/model/lml/graph_exporter.rb +248 -0
  18. data/lib/lutaml/model/lml/importer.rb +180 -0
  19. data/lib/lutaml/model/lml/mapping_compiler.rb +401 -0
  20. data/lib/lutaml/model/lml/materialization.rb +257 -0
  21. data/lib/lutaml/model/lml/ordered_content.rb +577 -0
  22. data/lib/lutaml/model/lml/portable_json.rb +385 -0
  23. data/lib/lutaml/model/lml/rejected_error.rb +64 -15
  24. data/lib/lutaml/model/lml/round_trip.rb +86 -0
  25. data/lib/lutaml/model/lml/value_declarations.rb +84 -0
  26. data/lib/lutaml/model/lml.rb +61 -0
  27. data/lib/lutaml/model/schema/definitions/attribute.rb +4 -2
  28. data/lib/lutaml/model/schema/registry_generator.rb +1 -1
  29. data/lib/lutaml/model/schema/renderers/member_decls.rb +1 -0
  30. data/lib/lutaml/model/schema/xml_compiler/spec_builder/members.rb +10 -0
  31. data/lib/lutaml/model/sequence.rb +7 -0
  32. data/lib/lutaml/model/serialize/format_conversion.rb +22 -8
  33. data/lib/lutaml/model/serialize/initialization.rb +2 -0
  34. data/lib/lutaml/model/version.rb +1 -1
  35. data/lib/lutaml/xml/leptris/native_emission.rb +85 -3
  36. data/lib/lutaml/xml/leptris/plan_compiler.rb +190 -45
  37. data/lib/lutaml/xml/leptris/plan_hydrator.rb +209 -56
  38. data/lib/lutaml/xml/leptris/plan_serializer.rb +533 -102
  39. data/lib/lutaml/xml/leptris/plan_walk.rb +1 -0
  40. data/lib/lutaml/xml/schema/builder/moxml.rb +7 -3
  41. data/lib/lutaml/xml/transformation/order_reconciler.rb +4 -0
  42. data/lib/lutaml/xml/transformation/ordered_applier.rb +8 -7
  43. data/schema/lml/document.schema.json +179 -0
  44. data/scripts/lml/export_choices.rb +57 -0
  45. data/scripts/lml/export_conformance.rb +23 -0
  46. data/scripts/lml/export_mml.rb +253 -0
  47. data/scripts/lml/export_preservation.rb +421 -0
  48. data/scripts/lml/verify_artifacts.rb +31 -0
  49. data/spec/fixtures/lml_artifacts/model.json +1 -0
  50. data/spec/fixtures/lml_artifacts/valid.json +1 -0
  51. data/spec/fixtures/lml_artifacts/valid.sha256 +1 -0
  52. data/spec/fixtures/lml_conformance/core/index.json +1 -0
  53. data/spec/fixtures/lml_conformance/core/manifest.json +1 -0
  54. data/spec/fixtures/lml_conformance/core/schema.json +1 -0
  55. data/spec/fixtures/lml_conformance/core/schema.yaml +79 -0
  56. data/spec/fixtures/lml_conformance/float_vectors.generator.rb +60 -0
  57. data/spec/fixtures/lml_conformance/float_vectors.json +21550 -0
  58. data/spec/fixtures/lml_conformance/preservation/index.json +1 -0
  59. data/spec/fixtures/lml_conformance/preservation/manifest.json +1 -0
  60. data/spec/fixtures/lml_conformance/preservation/schema.json +1 -0
  61. data/spec/fixtures/lml_conformance/preservation/schema.yaml +319 -0
  62. data/spec/fixtures/lml_conformance/r2_refusals.generator.rb +153 -0
  63. data/spec/fixtures/lml_conformance/r2_refusals.json +1662 -0
  64. data/spec/fixtures/lml_conformance/ruby_portable_interop.generator.rb +40 -0
  65. data/spec/fixtures/lml_conformance/ruby_portable_interop.json +1 -0
  66. data/spec/fixtures/lml_contract/bundle.json +81 -0
  67. data/spec/fixtures/lml_contract/manifest.json +30 -0
  68. data/spec/fixtures/lml_contract/v1_unit.canonical.json +1 -0
  69. data/spec/fixtures/lml_contract/v1_unit.json +1 -0
  70. data/spec/fixtures/lml_contract/v2_node.canonical.json +1 -0
  71. data/spec/fixtures/lml_contract/v2_node.json +32 -0
  72. data/spec/fixtures/lml_mml/inventory.json +1 -0
  73. data/spec/fixtures/lml_mml/manifest.json +1 -0
  74. data/spec/fixtures/lml_mml/oracle.json +1 -0
  75. data/spec/fixtures/lml_mml/v3-mi-mixed.json +1 -0
  76. data/spec/fixtures/lml_mml/v3-mi-mixed.yaml +970 -0
  77. data/spec/fixtures/lml_mml/v4-mi-mixed.json +1 -0
  78. data/spec/fixtures/lml_mml/v4-mi-mixed.yaml +1516 -0
  79. data/spec/fixtures/lml_mml_materialization/replay.rb +37 -0
  80. data/spec/lutaml/model/lml_any_attribute_spec.rb +91 -0
  81. data/spec/lutaml/model/lml_artifact_verifier_spec.rb +86 -0
  82. data/spec/lutaml/model/lml_builtin_types_spec.rb +49 -0
  83. data/spec/lutaml/model/lml_conformance_spec.rb +178 -0
  84. data/spec/lutaml/model/lml_document_spec.rb +279 -0
  85. data/spec/lutaml/model/lml_export_validation_spec.rb +96 -0
  86. data/spec/lutaml/model/lml_exporter_spec.rb +127 -5
  87. data/spec/lutaml/model/lml_graph_exporter_spec.rb +205 -0
  88. data/spec/lutaml/model/lml_importer_spec.rb +290 -0
  89. data/spec/lutaml/model/lml_input_hardening_spec.rb +156 -0
  90. data/spec/lutaml/model/lml_mapping_compiler_spec.rb +256 -0
  91. data/spec/lutaml/model/lml_materialization_spec.rb +138 -0
  92. data/spec/lutaml/model/lml_mml_materialization_spec.rb +54 -0
  93. data/spec/lutaml/model/lml_mml_pilot_spec.rb +150 -0
  94. data/spec/lutaml/model/lml_model_choices_spec.rb +88 -0
  95. data/spec/lutaml/model/lml_ordered_content_spec.rb +243 -0
  96. data/spec/lutaml/model/lml_portable_json_spec.rb +310 -0
  97. data/spec/lutaml/model/lml_preservation_spec.rb +211 -0
  98. data/spec/lutaml/model/lml_review_export_spec.rb +247 -0
  99. data/spec/lutaml/model/lml_review_import_spec.rb +390 -0
  100. data/spec/lutaml/model/lml_review_misc_spec.rb +152 -0
  101. data/spec/lutaml/model/lml_review_round4_spec.rb +200 -0
  102. data/spec/lutaml/model/lml_review_round5_spec.rb +194 -0
  103. data/spec/lutaml/model/lml_ruby_interop_fixture_spec.rb +37 -0
  104. data/spec/lutaml/model/lml_shared_corpus_spec.rb +132 -0
  105. data/spec/lutaml/model/lml_value_declarations_spec.rb +128 -0
  106. data/spec/lutaml/model/schema/class_loader_spec.rb +51 -0
  107. data/spec/lutaml/model/schema/xml_compiler_runtime_spec.rb +20 -0
  108. data/spec/lutaml/model/sequence_spec.rb +48 -0
  109. data/spec/lutaml/xml/cdata_emission_spec.rb +68 -0
  110. data/spec/lutaml/xml/production_lane_parity_spec.rb +632 -0
  111. data/spec/support/lml_any_attribute_fixtures.rb +26 -0
  112. data/spec/support/lml_conformance.rb +292 -0
  113. data/spec/support/lml_corpus.rb +75 -0
  114. data/spec/support/lml_export_fixtures.rb +190 -0
  115. data/spec/support/lml_graph_fixtures.rb +108 -0
  116. data/spec/support/lml_import_fixtures.rb +52 -0
  117. data/spec/support/lml_mapping_fixtures.rb +170 -0
  118. data/spec/support/lml_materialization_fixtures.rb +53 -0
  119. data/spec/support/lml_model_choices_fixtures.rb +150 -0
  120. data/spec/support/lml_order_fixtures.rb +151 -0
  121. metadata +94 -3
  122. data/lib/lutaml/model/schema/schema_builder/nokogiri.rb +0 -41
@@ -0,0 +1,205 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "lutaml/model"
4
+ require "lutaml/model/lml/graph_exporter"
5
+ require_relative "../../support/lml_graph_fixtures"
6
+
7
+ RSpec.describe Lutaml::Model::Lml::GraphExporter do
8
+ let(:fx) { LmlGraphFixtures }
9
+ let(:graph) { described_class }
10
+
11
+ def id(klass, register = "default")
12
+ "#{klass.name}@#{register}"
13
+ end
14
+
15
+ def export(roots, **opts)
16
+ graph.export(roots, projector: fx.projector, **opts)
17
+ end
18
+
19
+ it "exports a self-referential model once and terminates" do
20
+ calls = []
21
+ bundle = graph.export([fx::Node], projector: fx.projector({}, calls))
22
+
23
+ expect(bundle.models.keys).to eq([id(fx::Node)])
24
+ expect(bundle.roots).to eq([id(fx::Node)])
25
+ expect(calls.size).to eq(1)
26
+ end
27
+
28
+ it "closes mutual cycles from either root and yields identical bundles" do
29
+ from_left = export([fx::Left])
30
+ from_right = export([fx::Right])
31
+
32
+ expect(from_left.models.keys).to eq([id(fx::Left), id(fx::Right)].sort)
33
+ expect(from_left.models).to eq(from_right.models)
34
+ expect(from_left.roots).not_to eq(from_right.roots)
35
+ end
36
+
37
+ it "follows discriminator targets" do
38
+ bundle = export([fx::Shape])
39
+ expect(bundle.models.keys).to eq([fx::Circle, fx::Shape, fx::Square].map { |k| id(k) }.sort)
40
+ end
41
+
42
+ it "hoists value types to the bundle and requires them to exist" do
43
+ bundle = export([fx::Holder])
44
+ expect(bundle.value_types.keys).to eq(["Size"])
45
+ expect(bundle.models[id(fx::Holder)]).not_to have_key("value_types")
46
+ end
47
+
48
+ it "sorts roots and capabilities and ignores root order and duplicates" do
49
+ a = export([fx::Node, fx::Leaf, fx::Node])
50
+ b = export([fx::Leaf, fx::Node])
51
+
52
+ expect(a.roots).to eq([id(fx::Leaf), id(fx::Node)])
53
+ expect(a.capabilities).to eq(["xml"])
54
+ expect(a.canonical_json).to eq(b.canonical_json)
55
+ expect(a.checksum).to eq(b.checksum)
56
+ end
57
+
58
+ it "excludes provenance from the checksum but keeps it in the document" do
59
+ plain = export([fx::Leaf])
60
+ tagged = export([fx::Leaf], provenance: { "source_revision" => "abc" })
61
+
62
+ expect(tagged.checksum).to eq(plain.checksum)
63
+ expect(tagged.to_h["provenance"]).to eq("source_revision" => "abc")
64
+ expect(tagged.canonical_json).not_to eq(plain.canonical_json)
65
+ expect(plain.checksum).to match(/\Asha256:\h{64}\z/)
66
+ end
67
+
68
+ it "changes the checksum when a model definition changes" do
69
+ changed = graph.export(
70
+ [fx::Leaf],
71
+ projector: fx.projector(id(fx::Leaf) => fx.document(fx::Leaf, "default", [fx.attribute("x", { "kind" => "builtin", "name" => "string" })])),
72
+ )
73
+ expect(changed.checksum).not_to eq(export([fx::Leaf]).checksum)
74
+ expect(changed.model_checksum(id(fx::Leaf))).to match(/\Asha256:\h{64}\z/)
75
+ end
76
+
77
+ it "emits compact key-sorted JSON without escaping slashes or non-ASCII" do
78
+ doc = fx.document(fx::Leaf, "default", [], "zeta" => "a/é", "alpha" => 1)
79
+ bundle = graph.export([fx::Leaf], projector: fx.projector(id(fx::Leaf) => doc))
80
+ json = bundle.canonical_json
81
+
82
+ expect(json).to include('"alpha":1,"attributes":[],"lml":2')
83
+ expect(json).to include('"zeta":"a/é"')
84
+ expect(json).not_to match(/\s|\n\z/)
85
+ end
86
+
87
+ it "is immutable and unaffected by later mutation of projector output" do
88
+ doc = fx.document(fx::Leaf, "default")
89
+ bundle = graph.export([fx::Leaf], projector: fx.projector(id(fx::Leaf) => doc))
90
+ before = bundle.checksum
91
+ doc["attributes"] << { "name" => "late" }
92
+
93
+ expect(bundle.checksum).to eq(before)
94
+ expect(bundle.models).to be_frozen
95
+ expect { bundle.models[id(fx::Leaf)]["lml"] = 3 }.to raise_error(FrozenError)
96
+ end
97
+
98
+ describe "register contexts" do
99
+ before { Lutaml::Model::GlobalRegister.register(Lutaml::Model::Register.new(:alt)) }
100
+
101
+ after { Lutaml::Model::GlobalRegister.remove(:alt) }
102
+
103
+ it "keys the same class separately per register without contamination" do
104
+ alt = export([fx::Left], register: :alt)
105
+ default = export([fx::Left])
106
+
107
+ expect(alt.models.keys).to eq([id(fx::Left, "alt"), id(fx::Right, "alt")].sort)
108
+ expect(alt.models[id(fx::Left, "alt")]["attributes"][0]["type"]["id"]).to eq(id(fx::Right, "alt"))
109
+ expect(default.models.keys).to eq([id(fx::Left), id(fx::Right)].sort)
110
+ expect(alt.checksum).not_to eq(default.checksum)
111
+ end
112
+
113
+ it "accepts [class, register] roots and class default registers" do
114
+ fx::Leaf.define_singleton_method(:lutaml_default_register) { :mml_v2 }
115
+ begin
116
+ expect(export([fx::Leaf]).roots).to eq([id(fx::Leaf, "mml_v2")])
117
+ expect(export([[fx::Leaf, "x"]]).roots).to eq([id(fx::Leaf, "x")])
118
+ ensure
119
+ fx::Leaf.singleton_class.send(:remove_method, :lutaml_default_register)
120
+ end
121
+ end
122
+
123
+ it "keeps the original schema ID when the register substitutes a class" do
124
+ resolver = lambda { |name, register|
125
+ name == fx::Right.name && register == "alt" ? fx::Substitute : Object.const_get(name)
126
+ }
127
+ projector = fx.projector(
128
+ id(fx::Substitute, "alt") => fx.document(fx::Substitute, "alt"),
129
+ )
130
+ bundle = graph.export([fx::Left], register: "alt", projector: projector, resolver: resolver)
131
+
132
+ expect(bundle.models.keys).to include(id(fx::Right, "alt"))
133
+ expect(bundle.models[id(fx::Right, "alt")]["model"]).to eq(fx::Right.name)
134
+ expect(bundle.models.keys).not_to include(id(fx::Substitute, "alt"))
135
+ end
136
+
137
+ it "rejects non-portable register names" do
138
+ expect { export([fx::Leaf], register: "bad register") }
139
+ .to raise_error(Lutaml::Model::Lml::RejectedError) { |e| expect(e.reason).to eq(:invalid_document) }
140
+ end
141
+ end
142
+
143
+ describe "rejections" do
144
+ def reason_of
145
+ yield
146
+ nil
147
+ rescue Lutaml::Model::Lml::RejectedError => e
148
+ e.reason
149
+ end
150
+
151
+ it "rejects anonymous classes" do
152
+ expect(reason_of { export([Class.new]) }).to eq(:invalid_document)
153
+ end
154
+
155
+ it "rejects an unresolvable target as dangling" do
156
+ projector = fx.projector(
157
+ id(fx::Leaf) => fx.document(fx::Leaf, "default", [fx.attribute("m", fx.model_ref("Nope::Missing@default"))]),
158
+ )
159
+ expect(reason_of { graph.export([fx::Leaf], projector: projector) }).to eq(:dangling_reference)
160
+ end
161
+
162
+ it "rejects a value type that is never defined" do
163
+ projector = fx.projector(
164
+ id(fx::Leaf) => fx.document(fx::Leaf, "default", [fx.attribute("v", { "kind" => "value", "id" => "Ghost" })]),
165
+ )
166
+ expect(reason_of { graph.export([fx::Leaf], projector: projector) }).to eq(:dangling_reference)
167
+ end
168
+
169
+ it "rejects one ID defined differently by two classes" do
170
+ twin = Class.new
171
+ stub_const("LmlGraphFixtures::Twin", twin)
172
+ allow(twin).to receive(:name).and_return(fx::Leaf.name)
173
+ projector = lambda { |klass, register|
174
+ extra = klass.equal?(twin) ? [fx.attribute("z", { "kind" => "builtin", "name" => "string" })] : []
175
+ fx.document(fx::Leaf, register, extra)
176
+ }
177
+ expect(reason_of { graph.export([fx::Leaf, twin], projector: projector) }).to eq(:duplicate_id)
178
+ end
179
+
180
+ it "accepts two classes projecting an identical definition" do
181
+ twin = Class.new
182
+ allow(twin).to receive(:name).and_return(fx::Leaf.name)
183
+ projector = ->(_klass, register) { fx.document(fx::Leaf, register) }
184
+ expect(graph.export([fx::Leaf, twin], projector: projector).models.size).to eq(1)
185
+ end
186
+
187
+ it "rejects a document whose identity disagrees with its ID" do
188
+ projector = fx.projector(id(fx::Leaf) => fx.document(fx::Node, "default"))
189
+ expect(reason_of { graph.export([fx::Leaf], projector: projector) }).to eq(:invalid_document)
190
+ end
191
+
192
+ it "rejects a projector result that is not a Hash" do
193
+ expect(reason_of { graph.export([fx::Leaf], projector: ->(*) { [] }) }).to eq(:invalid_document)
194
+ end
195
+
196
+ it "does not return a partial bundle when a nested target fails" do
197
+ projector = lambda { |klass, register|
198
+ raise Lutaml::Model::Lml::RejectedError.new(:custom_initialize, klass) if klass == fx::Right
199
+
200
+ fx.projector.call(klass, register)
201
+ }
202
+ expect(reason_of { graph.export([fx::Left], projector: projector) }).to eq(:custom_initialize)
203
+ end
204
+ end
205
+ end
@@ -0,0 +1,290 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "spec_helper"
4
+ require "json"
5
+ require "open3"
6
+ require "rbconfig"
7
+ require "tmpdir"
8
+ require_relative "../../support/lml_import_fixtures"
9
+ require_relative "../../support/lml_materialization_fixtures"
10
+
11
+ # lutaml-model#1033 card 03c: additive export_bundle / import_bundle /
12
+ # verify_materialization, and a true round trip in a fresh process that
13
+ # has none of the source constants.
14
+ RSpec.describe "LML bundle import/export" do
15
+ let(:lml) { Lutaml::Model::Lml }
16
+ let(:fx) { LmlImportFixtures }
17
+ let(:rejected) { lml::RejectedError }
18
+ let(:roots) { fx::GRAPH_ROOTS }
19
+ let(:bundle) { lml.export_bundle(roots) }
20
+ let(:repo_root) { File.expand_path("../../..", __dir__) }
21
+
22
+ def doc_sample
23
+ item = LmlMappingFixtures::Item.new(id: "i1", label: "<one>")
24
+ LmlMappingFixtures::Doc.new(
25
+ title: "T", count: 2, items: [item],
26
+ entries: [LmlMappingFixtures::Entry.new(name: "n", value: "v")]
27
+ )
28
+ end
29
+
30
+ def kennel_json
31
+ '{"animals":[{"kind":"dog","name":"Rex"},{"kind":"animal","name":"Tom"}],"owner":"Ann"}'
32
+ end
33
+
34
+ def refusal
35
+ yield
36
+ nil
37
+ rescue rejected => e
38
+ e
39
+ end
40
+
41
+ describe ".export_bundle" do
42
+ it "exports the closed graph reachable from the roots, keyed by Model@register" do
43
+ expect(bundle).to be_a(lml::Bundle)
44
+ expect(bundle.models.keys).to include("LmlMappingFixtures::Item@default", "LmlImportFixtures::Dog@default",
45
+ "LmlOrderFixtures::Emphasis@default")
46
+ expect(bundle.roots).to eq(roots.map { |k| "#{k.name}@default" }.sort)
47
+ end
48
+
49
+ it "resolves a nil register the same as the default and as an explicit default" do
50
+ by_default = lml.export_bundle(fx::Animal)
51
+ expect(lml.export_bundle(fx::Animal, register: nil).checksum).to eq(by_default.checksum)
52
+ expect(lml.export_bundle([[fx::Animal, "default"]]).checksum).to eq(by_default.checksum)
53
+ expect(lml.export_bundle([fx::Animal], register: "default").checksum).to eq(by_default.checksum)
54
+ end
55
+
56
+ context "with a non-default named register" do
57
+ let(:child) do
58
+ Class.new(Lutaml::Model::Serializable) do
59
+ attribute :label, :string
60
+ xml do
61
+ element "child"
62
+ map_element "label", to: :label
63
+ end
64
+ end
65
+ end
66
+
67
+ before do
68
+ stub_const("LmlNamedRegisterChild", child)
69
+ stub_const("LmlNamedRegisterParent", Class.new(Lutaml::Model::Serializable) do
70
+ attribute :child, :lml_named_child
71
+ xml do
72
+ element "parent"
73
+ map_element "child", to: :child
74
+ end
75
+ end)
76
+ registry = Lutaml::Model::TypeRegistry.new
77
+ Lutaml::Model::Type.register_builtin_types_in(registry)
78
+ registry.register(:lml_named_child, child)
79
+ Lutaml::Model::GlobalContext.create_context(id: :lml_named_register, registry: registry)
80
+ end
81
+
82
+ after { Lutaml::Model::GlobalContext.unregister_context(:lml_named_register) }
83
+
84
+ it "resolves that register's context (a String register must not fall back to default)" do
85
+ [:lml_named_register, "lml_named_register"].each do |name|
86
+ exported = lml.export_bundle(LmlNamedRegisterParent, register: name)
87
+ expect(exported.models.keys).to contain_exactly("LmlNamedRegisterChild@lml_named_register",
88
+ "LmlNamedRegisterParent@lml_named_register")
89
+ attribute = exported.models.fetch("LmlNamedRegisterParent@lml_named_register").fetch("attributes").first
90
+ expect(attribute.fetch("type")).to eq("kind" => "model", "id" => "LmlNamedRegisterChild@lml_named_register")
91
+ end
92
+ end
93
+ end
94
+
95
+ it "exports the same documents as the per-class projection" do
96
+ doc = lml::Exporter.project(LmlMappingFixtures::Item)
97
+ expect(bundle.models["LmlMappingFixtures::Item@default"]).to eq(doc)
98
+ end
99
+
100
+ it "excludes provenance from the checksum" do
101
+ tagged = lml.export_bundle(fx::Animal, provenance: { "tool" => "spec" })
102
+ expect(tagged.provenance).to eq("tool" => "spec")
103
+ expect(tagged.checksum).to eq(lml.export_bundle(fx::Animal).checksum)
104
+ end
105
+ end
106
+
107
+ describe "existing entry points" do
108
+ it "keeps export and verify returning the v1 Document" do
109
+ document = lml.export(LmlMappingFixtures::Item)
110
+ expect(document).to be_a(lml::Document)
111
+ expect(lml.verify(document)).to be_a(lml::Document)
112
+ expect(lml.verify(document).checksum).to eq(document.checksum)
113
+ end
114
+
115
+ it "keeps the named mismatch error of verify for an unloadable model" do
116
+ document = lml::Document.new(model_name: "Nope::Gone", attributes: [], mappings: {})
117
+ expect(refusal { lml.verify(document) }.reason).to eq(:unknown_type)
118
+ end
119
+ end
120
+
121
+ describe ".import_bundle" do
122
+ let(:holder) { stub_const("LmlImported", Module.new) }
123
+
124
+ it "builds working classes whose output equals the source classes in xml, json and yaml" do
125
+ classes = lml.import_bundle(bundle, namespace: holder)
126
+ generated = classes["LmlMappingFixtures::Doc@default"]
127
+ source = doc_sample
128
+
129
+ expect(generated).not_to equal(LmlMappingFixtures::Doc)
130
+ %i[xml json yaml].each do |format|
131
+ text = source.public_send(:"to_#{format}")
132
+ oracle = LmlMappingFixtures::Doc.public_send(:"from_#{format}", text).public_send(:"to_#{format}")
133
+ expect(generated.public_send(:"from_#{format}", text).public_send(:"to_#{format}")).to eq(oracle)
134
+ end
135
+ end
136
+
137
+ it "accepts a Bundle, its Hash form and its JSON text alike" do
138
+ plain = lml.export_bundle(LmlMappingFixtures::Doc)
139
+ forms = [plain, plain.to_h, JSON.generate(plain.to_h)]
140
+ ids = forms.map { |form| lml.import_bundle(form).keys }
141
+ expect(ids.uniq.length).to eq(1)
142
+ expect(ids.first).to eq(plain.models.keys.sort)
143
+ end
144
+
145
+ it "names an invalid bundle instead of importing part of it" do
146
+ broken = JSON.parse(JSON.generate(bundle.to_h))
147
+ broken["roots"] = ["Missing@default"]
148
+ expect(refusal { lml.import_bundle(broken) }.reason).to eq(:dangling_reference)
149
+ expect(refusal { lml.import_bundle("{not json") }.reason).to eq(:invalid_document)
150
+ end
151
+
152
+ it "needs an installed namespace for polymorphic discriminator targets" do
153
+ error = refusal { lml.import_bundle(lml.export_bundle(fx::Kennel)) }
154
+ expect(error.reason).to eq(:unsupported_mapping)
155
+ expect(error.message).to include("installed constant")
156
+
157
+ classes = lml.import_bundle(lml.export_bundle(fx::Kennel), namespace: holder)
158
+ kennel = classes["LmlImportFixtures::Kennel@default"].from_json(kennel_json)
159
+ expect(kennel.animals.map(&:class)).to eq(
160
+ [classes["LmlImportFixtures::Dog@default"], classes["LmlImportFixtures::Animal@default"]],
161
+ )
162
+ expect(kennel.to_json).to eq(JSON.generate(JSON.parse(kennel_json)))
163
+ end
164
+ end
165
+
166
+ describe ".verify_materialization" do
167
+ it "returns the re-exported bundle, equal to the input" do
168
+ verified = lml.verify_materialization(bundle, namespace: stub_const("LmlVerified", Module.new))
169
+ expect(verified).to eq(bundle)
170
+ expect(verified.checksum).to eq(bundle.checksum)
171
+ expect(verified.models).to eq(bundle.models)
172
+ end
173
+
174
+ it "works without a namespace, including polymorphism, and leaves no constant behind" do
175
+ before = Object.constants.grep(/\ALmlVerify/)
176
+ expect(lml.verify_materialization(bundle).checksum).to eq(bundle.checksum)
177
+ expect(Object.constants.grep(/\ALmlVerify/)).to eq(before)
178
+ end
179
+
180
+ it "removes the transient namespace when verification fails" do
181
+ before = Object.constants.grep(/\ALmlVerify/)
182
+ sparse = LmlMaterializationFixtures.cyclic
183
+ expect(refusal { lml.verify_materialization(sparse) }.reason).to eq(:round_trip_mismatch)
184
+ expect(Object.constants.grep(/\ALmlVerify/)).to eq(before)
185
+ end
186
+
187
+ it "keeps non-default registers in the identifiers" do
188
+ Lutaml::Model::GlobalRegister.register(Lutaml::Model::Register.new(:lml_alt))
189
+ alt = lml.export_bundle(fx::Animal, register: "lml_alt")
190
+ expect(alt.roots).to eq(["LmlImportFixtures::Animal@lml_alt"])
191
+ expect(lml.verify_materialization(alt).checksum).to eq(alt.checksum)
192
+ ensure
193
+ Lutaml::Model::GlobalRegister.remove(:lml_alt)
194
+ end
195
+
196
+ it "names a bundle that is valid but not in exporter form as a round_trip_mismatch" do
197
+ sparse = LmlMaterializationFixtures.cyclic
198
+ holder = stub_const("LmlSparse", Module.new)
199
+
200
+ expect(lml.import_bundle(sparse, namespace: holder).keys).to eq(sparse["models"].keys.sort)
201
+ error = refusal { lml.verify_materialization(sparse) }
202
+ expect(error.reason).to eq(:round_trip_mismatch)
203
+ expect(error.message).to match(/sha256:\h{13}.* vs sha256:\h{13}/)
204
+ end
205
+ end
206
+
207
+ describe "true reconstruction in a fresh process" do
208
+ # Pin one real adapter for both sides: other specs may leave the global
209
+ # XML slot holding a pre-resolved class (FIXED_ADAPTER_TYPE), which a
210
+ # fresh process cannot reproduce by name.
211
+ around { |example| Lutaml::Model::Config.with_adapter(xml: :nokogiri) { example.run } }
212
+
213
+ let(:child_script) do
214
+ <<~'RUBY'
215
+ require "json"
216
+ require "lutaml/model"
217
+ payload = JSON.parse(File.read(ARGV.fetch(0)))
218
+ Lutaml::Model::Config.xml_adapter_type = payload.fetch("xml_adapter").to_sym
219
+ lml = Lutaml::Model::Lml
220
+ result = { "source_constants" => %w[LmlMappingFixtures LmlOrderFixtures LmlImportFixtures]
221
+ .select { |name| Object.const_defined?(name) } }
222
+ module Imported; end
223
+
224
+ bundle = lml::Importer.bundle(payload.fetch("bundle"))
225
+ classes = lml.import_bundle(bundle, namespace: Imported)
226
+ verified = lml.verify_materialization(bundle, namespace: Module.new.tap { |m| Object.const_set(:Second, m) })
227
+ reexported = lml.export_bundle(classes.values_at(*bundle.roots))
228
+
229
+ result["verified_checksum"] = verified.checksum
230
+ result["verified_canonical"] = verified.canonical_json
231
+ result["generated_model_names"] = reexported.models.values.map { |d| d["model"] }.sort
232
+ result["generated_documents_renamed_equal"] =
233
+ reexported.models.transform_keys { |k| k.delete_prefix("Imported::") }
234
+ .transform_values { |d| JSON.parse(JSON.generate(d).gsub("Imported::", "")) } ==
235
+ bundle.models.transform_values { |d| JSON.parse(JSON.generate(d)) }
236
+
237
+ doc = classes.fetch("LmlMappingFixtures::Doc@default")
238
+ result["doc"] = %w[xml json yaml].to_h do |format|
239
+ [format, doc.public_send(:"from_#{format}", payload.dig("doc", format)).public_send(:"to_#{format}")]
240
+ end
241
+ para = classes.fetch("LmlOrderFixtures::Para@default")
242
+ result["para"] = para.from_xml(payload.fetch("para")).to_xml
243
+ kennel = classes.fetch("LmlImportFixtures::Kennel@default").from_json(payload.fetch("kennel"))
244
+ result["kennel"] = kennel.to_json
245
+ result["kennel_classes"] = kennel.animals.map(&:class).map(&:name)
246
+ puts JSON.generate(result)
247
+ RUBY
248
+ end
249
+
250
+ let(:para_xml) { "<p>one <em>two</em> three<b>x</b> <em>four</em><note>n</note> end</p>" }
251
+
252
+ def run_child(payload)
253
+ Dir.mktmpdir("lml-child") do |dir|
254
+ path = File.join(dir, "payload.json")
255
+ File.write(path, JSON.generate(payload))
256
+ out, err, status = Open3.capture3(RbConfig.ruby, "-I#{File.join(repo_root, 'lib')}", "-e", child_script, path,
257
+ chdir: repo_root)
258
+ raise "child failed (#{status.exitstatus}): #{err}" unless status.success?
259
+
260
+ JSON.parse(out.lines.last)
261
+ end
262
+ end
263
+
264
+ it "imports, re-exports and verifies equal declarations and checksum, with equal behaviour" do
265
+ source = doc_sample
266
+ payload = {
267
+ "bundle" => bundle.to_h,
268
+ "xml_adapter" => "nokogiri",
269
+ "doc" => { "xml" => source.to_xml, "json" => source.to_json, "yaml" => source.to_yaml },
270
+ "oracle" => %w[xml json yaml].to_h do |format|
271
+ text = source.public_send(:"to_#{format}")
272
+ [format, LmlMappingFixtures::Doc.public_send(:"from_#{format}", text).public_send(:"to_#{format}")]
273
+ end,
274
+ "para" => para_xml,
275
+ "kennel" => kennel_json,
276
+ }
277
+ result = run_child(payload)
278
+
279
+ expect(result["source_constants"]).to eq([])
280
+ expect(result["verified_checksum"]).to eq(bundle.checksum)
281
+ expect(result["verified_canonical"]).to eq(bundle.canonical_json)
282
+ expect(result["generated_documents_renamed_equal"]).to be(true)
283
+ expect(result["generated_model_names"]).to all(start_with("Imported::"))
284
+ expect(result["doc"]).to eq(payload["oracle"])
285
+ expect(result["para"]).to eq(LmlOrderFixtures::Para.from_xml(para_xml).to_xml)
286
+ expect(result["kennel"]).to eq(JSON.generate(JSON.parse(kennel_json)))
287
+ expect(result["kennel_classes"]).to eq(%w[Imported::LmlImportFixtures::Dog Imported::LmlImportFixtures::Animal])
288
+ end
289
+ end
290
+ end
@@ -0,0 +1,156 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "spec_helper"
4
+ require "lutaml/model/lml"
5
+ require "tmpdir"
6
+ require "digest"
7
+
8
+ RSpec.describe "LML input hardening (RB-INPUT)" do
9
+ let(:lml) { Lutaml::Model::Lml }
10
+ let(:validator) { lml::DocumentValidator }
11
+ let(:verifier) { lml::ArtifactVerifier }
12
+
13
+ def bundle_hash(attributes: nil)
14
+ attributes ||= [{ "name" => "label", "type" => { "kind" => "builtin", "name" => "string" } }]
15
+ { "lml_bundle" => 1, "roots" => ["Hard::Node@default"],
16
+ "models" => { "Hard::Node@default" => { "lml" => 2, "model" => "Hard::Node", "register" => "default",
17
+ "attributes" => attributes } },
18
+ "value_types" => {}, "capabilities" => ["json"] }
19
+ end
20
+
21
+ def refusal
22
+ yield
23
+ nil
24
+ rescue lml::RejectedError => e
25
+ e
26
+ end
27
+
28
+ describe "M1: JSON comments" do
29
+ it "refuses a // comment" do
30
+ text = "{ // note\n#{JSON.generate(bundle_hash).delete_prefix('{')}"
31
+ error = refusal { lml::Importer.bundle(text) }
32
+ expect([error&.reason]).to eq([:invalid_document])
33
+ end
34
+
35
+ it "refuses a /* */ comment hiding a duplicate key" do
36
+ text = %({"lml_bundle":1,"roots":[]/*"*/,"roots":[]/*"*/,"models":{},"value_types":{},"capabilities":[]})
37
+ error = refusal { lml::Importer.bundle(text) }
38
+ expect([error&.reason, error&.detail]).to eq([:invalid_document, "not valid JSON: comments are not allowed"])
39
+ end
40
+
41
+ it "still accepts a slash inside a string" do
42
+ text = JSON.generate(bundle_hash(attributes: [{ "name" => "a", "type" => { "kind" => "builtin", "name" => "string" },
43
+ "default" => { "present" => true, "value" => "a//b/*c*/" } }]))
44
+ expect(lml::Importer.bundle(text).roots).to eq(["Hard::Node@default"])
45
+ end
46
+ end
47
+
48
+ describe "M7: default of the wrong type" do
49
+ [7, -0, true, { "a" => 1 }].each do |value|
50
+ it "refuses #{value.inspect} on a string attribute" do
51
+ attrs = [{ "name" => "label", "type" => { "kind" => "builtin", "name" => "string" },
52
+ "default" => { "present" => true, "value" => value } }]
53
+ error = refusal { validator.validate!(bundle_hash(attributes: attrs), kind: :bundle) }
54
+ expect(error&.reason).to eq(:non_serializable_default)
55
+ end
56
+ end
57
+
58
+ it "refuses a string on an integer attribute and accepts a matching one" do
59
+ mk = lambda { |v|
60
+ [{ "name" => "n", "type" => { "kind" => "builtin", "name" => "integer" },
61
+ "default" => { "present" => true, "value" => v } }]
62
+ }
63
+ expect(refusal { validator.validate!(bundle_hash(attributes: mk.call("7")), kind: :bundle) }&.reason)
64
+ .to eq(:non_serializable_default)
65
+ expect(refusal { validator.validate!(bundle_hash(attributes: mk.call(7)), kind: :bundle) }).to be_nil
66
+ end
67
+ end
68
+
69
+ describe "R1: invalid UTF-8 text" do
70
+ it "raises a named error, not ArgumentError" do
71
+ text = %({"lml_bundle":1,"x":"\xFF"}).b
72
+ error = refusal { lml::Importer.bundle(text) }
73
+ expect(error&.reason).to eq(:invalid_document)
74
+ end
75
+
76
+ it "does the same for a UTF-8 tagged string" do
77
+ text = (+%({"lml_bundle":1,"x":"\xFF"})).force_encoding("UTF-8")
78
+ expect(refusal { lml::Importer.bundle(text) }&.reason).to eq(:invalid_document)
79
+ end
80
+ end
81
+
82
+ describe "R2: v1 non-finite defaults" do
83
+ [Float::NAN, Float::INFINITY].each do |value|
84
+ it "refuses #{value} at validation" do
85
+ doc = { "lml" => 1, "model" => "A",
86
+ "attributes" => [{ "name" => "f", "type" => "float", "default" => value }], "mappings" => {} }
87
+ error = refusal { lml::Document.from_hash(doc) }
88
+ expect(error&.reason).to eq(:invalid_document)
89
+ end
90
+ end
91
+
92
+ it "still accepts a finite v1 float" do
93
+ doc = { "lml" => 1, "model" => "A", "attributes" => [{ "name" => "f", "default" => 1.5 }], "mappings" => {} }
94
+ expect { lml::Document.from_hash(doc).checksum }.not_to raise_error
95
+ end
96
+ end
97
+
98
+ describe "R4: ArtifactVerifier depth" do
99
+ it "refuses deep nesting with a named error" do
100
+ deep = 1
101
+ 100_000.times { deep = [deep] }
102
+ expect { verifier.checksum("a" => deep) }.to raise_error(verifier::Error) { |e| expect(e.reason).to eq(:invalid_document) }
103
+ end
104
+
105
+ it "accepts nesting within the limit" do
106
+ deep = 1
107
+ 50.times { deep = [deep] }
108
+ expect(verifier.checksum("a" => deep)).to match(/\Asha256:/)
109
+ end
110
+ end
111
+
112
+ describe "R5: case-exact artifact paths" do
113
+ it "refuses A.TXT when the file is a.txt" do
114
+ Dir.mktmpdir do |root|
115
+ File.write(File.join(root, "a.txt"), "hi")
116
+ sha = "sha256:#{Digest::SHA256.hexdigest('hi')}"
117
+ manifest = lambda { |path|
118
+ { "manifest" => 1, "schema_version" => 2, "target" => "ruby", "lml_checksum" => "sha256:#{'0' * 64}",
119
+ "generator_version" => "1", "capabilities" => [], "corpora" => [], "dependencies" => [],
120
+ "files" => [{ "path" => path, "sha256" => sha }] }
121
+ }
122
+ ok = manifest.call("a.txt")
123
+ expect { verifier.new(root: root, expected_sha256: verifier.checksum(ok)).verify(ok) }.not_to raise_error
124
+ bad = manifest.call("A.TXT")
125
+ expect { verifier.new(root: root, expected_sha256: verifier.checksum(bad)).verify(bad) }
126
+ .to raise_error(verifier::Error) { |e| expect(e.reason).to eq(:invalid_document) }
127
+ end
128
+ end
129
+ end
130
+
131
+ describe "R6: import wording" do
132
+ it "does not say export" do
133
+ error = refusal { lml::Importer.bundle("{not json") }
134
+ expect(error.message).to include("cannot import")
135
+ expect(error.message).not_to include("export")
136
+ end
137
+
138
+ it "keeps export wording for export errors" do
139
+ expect(lml::RejectedError.new(:custom_initialize, "Foo", "x").message).to start_with("cannot export")
140
+ end
141
+ end
142
+
143
+ describe "R7: v1 model names" do
144
+ ["x; 1", "lower", "A::", "A B", ""].each do |name|
145
+ it "refuses #{name.inspect}" do
146
+ error = refusal { lml::Document.from_hash("lml" => 1, "model" => name, "attributes" => [], "mappings" => {}) }
147
+ expect([error&.reason, error&.location]).to eq([:invalid_document, "/model"])
148
+ end
149
+ end
150
+
151
+ it "accepts a constant path" do
152
+ expect(lml::Document.from_hash("lml" => 1, "model" => "A::B", "attributes" => [], "mappings" => {}).model_name)
153
+ .to eq("A::B")
154
+ end
155
+ end
156
+ end