ref-id 0.7.0__tar.gz

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 (37) hide show
  1. ref_id-0.7.0/.gitignore +7 -0
  2. ref_id-0.7.0/LICENSE +202 -0
  3. ref_id-0.7.0/PKG-INFO +70 -0
  4. ref_id-0.7.0/README.md +58 -0
  5. ref_id-0.7.0/pyproject.toml +36 -0
  6. ref_id-0.7.0/src/ref_id/__init__.py +69 -0
  7. ref_id-0.7.0/src/ref_id/build.py +146 -0
  8. ref_id-0.7.0/src/ref_id/canonical.py +171 -0
  9. ref_id-0.7.0/src/ref_id/digest.py +45 -0
  10. ref_id-0.7.0/src/ref_id/encoding.py +78 -0
  11. ref_id-0.7.0/src/ref_id/envelope.py +64 -0
  12. ref_id-0.7.0/src/ref_id/errors.py +65 -0
  13. ref_id-0.7.0/src/ref_id/grammar.py +92 -0
  14. ref_id-0.7.0/src/ref_id/parse.py +236 -0
  15. ref_id-0.7.0/src/ref_id/py.typed +0 -0
  16. ref_id-0.7.0/src/ref_id/relations.py +464 -0
  17. ref_id-0.7.0/src/ref_id/serialise.py +109 -0
  18. ref_id-0.7.0/src/ref_id/spec/ref-id.json +5258 -0
  19. ref_id-0.7.0/src/ref_id/spec/ref-id.json.sha256 +1 -0
  20. ref_id-0.7.0/src/ref_id/spec.py +192 -0
  21. ref_id-0.7.0/src/ref_id/types.py +264 -0
  22. ref_id-0.7.0/src/ref_id/validators.py +258 -0
  23. ref_id-0.7.0/tests/test_build.py +100 -0
  24. ref_id-0.7.0/tests/test_canonical.py +109 -0
  25. ref_id-0.7.0/tests/test_conformance.py +224 -0
  26. ref_id-0.7.0/tests/test_digest.py +65 -0
  27. ref_id-0.7.0/tests/test_encoding.py +37 -0
  28. ref_id-0.7.0/tests/test_envelope.py +43 -0
  29. ref_id-0.7.0/tests/test_errors.py +32 -0
  30. ref_id-0.7.0/tests/test_grammar.py +97 -0
  31. ref_id-0.7.0/tests/test_parse.py +62 -0
  32. ref_id-0.7.0/tests/test_relations.py +193 -0
  33. ref_id-0.7.0/tests/test_spec.py +129 -0
  34. ref_id-0.7.0/tests/test_surface.py +106 -0
  35. ref_id-0.7.0/tests/test_validators.py +73 -0
  36. ref_id-0.7.0/tools/parse_lines.py +83 -0
  37. ref_id-0.7.0/uv.lock +394 -0
@@ -0,0 +1,7 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ __pycache__/
3
+ .venv/
4
+ dist/
5
+ .mypy_cache/
6
+ .ruff_cache/
7
+ .pytest_cache/
ref_id-0.7.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 The ref-id Authors
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
ref_id-0.7.0/PKG-INFO ADDED
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.5
2
+ Name: ref-id
3
+ Version: 0.7.0
4
+ Summary: The ref: identifier scheme — a Python port held to the specification's conformance vectors
5
+ Project-URL: Repository, https://github.com/entelekheia-ai/ref-id
6
+ Project-URL: Issues, https://github.com/entelekheia-ai/ref-id/issues
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.11
10
+ Requires-Dist: packageurl-python<0.18,>=0.17.6
11
+ Description-Content-Type: text/markdown
12
+
13
+ # ref-id
14
+
15
+ **The `ref:` identifier scheme, as a Python package held to the specification's conformance vectors.**
16
+ An identifier names a thing by what somebody declared about it — a package, a folder, a domain, a mailbox,
17
+ an agent — never by where a file happens to sit.
18
+
19
+ The specification is data: `ref-id.json` (grammar, tables, digest rules, conformance vectors) ships inside
20
+ the package byte-for-byte and is verified against its digest at load. The package implements the behaviour
21
+ the vectors bind — parse, serialise, build, comparison, digest and the envelope invariant — and restates
22
+ none of the specification's tables. It is one of four implementations of the scheme (TypeScript, Rust,
23
+ Swift, Python) that a differential test holds to the same answers on every input the specification names.
24
+
25
+ ## Install
26
+
27
+ ```sh
28
+ pip install ref-id
29
+ ```
30
+
31
+ Python 3.11 or later. The one dependency is `packageurl-python`, which validates Package URL locators.
32
+
33
+ ## Usage
34
+
35
+ Parse an identifier, then re-serialise it. `parse` never raises for an identifier problem: a malformed
36
+ string comes back with `status == "malformed"` and the part that failed; an unknown type comes back
37
+ `uncovered`, carried whole.
38
+
39
+ ```python
40
+ import ref_id
41
+
42
+ parsed = ref_id.parse("ref:pkg:npm/@acme/scanner-core@0.1.0#Observation")
43
+ assert parsed.status == "ok"
44
+ assert parsed.type == "pkg"
45
+ assert parsed.delegated == "pkg:npm/@acme/scanner-core@0.1.0"
46
+ assert ref_id.serialise(parsed) == "ref:pkg:npm/@acme/scanner-core@0.1.0#Observation"
47
+ ```
48
+
49
+ The other entry points: `build(ref_id.BuildParts(...))` composes an identifier from declared parts and
50
+ refuses what the grammar cannot carry; `digest([...])` hashes an ordered list of identifiers the way the
51
+ specification prescribes; `validate_envelope(requested_id, envelope)` checks a stored record against the
52
+ identifier it was requested under. `covers(general, specific)`, `same_package(a, b)` and
53
+ `same_identifier(a, b)` compare two identifiers — each accepts a `str` or a `ParseResult` — and
54
+ `relate(a, b)` reports the full per-dimension relation the others reduce from, while `verdict(a, b)` reads
55
+ it once location qualifiers are hints: an identity axis, a content axis and what decided each.
56
+ `canonical_identifier` and `canonicalise` produce canonical forms. `load_spec()` returns the embedded
57
+ specification, `load_spec_from(directory)` one read from a directory holding `ref-id.json` and its
58
+ `.sha256` sidecar.
59
+
60
+ Every function but `validate_envelope` takes its arguments by position only, as the specification declares
61
+ them unlabelled. Results are frozen dataclasses; `to_json()` gives the specification's own field names.
62
+ Errors are `RefIdError` and its five kinds.
63
+
64
+ `packageurl-python` decides whether a Package URL locator is valid and how its `canonical` field is spelled,
65
+ and the other implementations use other validators. Where they differ is measured in
66
+ [Known differences between implementations](https://github.com/entelekheia-ai/ref-id/blob/main/docs/reference/implementation-differences.md).
67
+
68
+ ## License
69
+
70
+ Apache-2.0. Source, specification and issues: <https://github.com/entelekheia-ai/ref-id>.
ref_id-0.7.0/README.md ADDED
@@ -0,0 +1,58 @@
1
+ # ref-id
2
+
3
+ **The `ref:` identifier scheme, as a Python package held to the specification's conformance vectors.**
4
+ An identifier names a thing by what somebody declared about it — a package, a folder, a domain, a mailbox,
5
+ an agent — never by where a file happens to sit.
6
+
7
+ The specification is data: `ref-id.json` (grammar, tables, digest rules, conformance vectors) ships inside
8
+ the package byte-for-byte and is verified against its digest at load. The package implements the behaviour
9
+ the vectors bind — parse, serialise, build, comparison, digest and the envelope invariant — and restates
10
+ none of the specification's tables. It is one of four implementations of the scheme (TypeScript, Rust,
11
+ Swift, Python) that a differential test holds to the same answers on every input the specification names.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ pip install ref-id
17
+ ```
18
+
19
+ Python 3.11 or later. The one dependency is `packageurl-python`, which validates Package URL locators.
20
+
21
+ ## Usage
22
+
23
+ Parse an identifier, then re-serialise it. `parse` never raises for an identifier problem: a malformed
24
+ string comes back with `status == "malformed"` and the part that failed; an unknown type comes back
25
+ `uncovered`, carried whole.
26
+
27
+ ```python
28
+ import ref_id
29
+
30
+ parsed = ref_id.parse("ref:pkg:npm/@acme/scanner-core@0.1.0#Observation")
31
+ assert parsed.status == "ok"
32
+ assert parsed.type == "pkg"
33
+ assert parsed.delegated == "pkg:npm/@acme/scanner-core@0.1.0"
34
+ assert ref_id.serialise(parsed) == "ref:pkg:npm/@acme/scanner-core@0.1.0#Observation"
35
+ ```
36
+
37
+ The other entry points: `build(ref_id.BuildParts(...))` composes an identifier from declared parts and
38
+ refuses what the grammar cannot carry; `digest([...])` hashes an ordered list of identifiers the way the
39
+ specification prescribes; `validate_envelope(requested_id, envelope)` checks a stored record against the
40
+ identifier it was requested under. `covers(general, specific)`, `same_package(a, b)` and
41
+ `same_identifier(a, b)` compare two identifiers — each accepts a `str` or a `ParseResult` — and
42
+ `relate(a, b)` reports the full per-dimension relation the others reduce from, while `verdict(a, b)` reads
43
+ it once location qualifiers are hints: an identity axis, a content axis and what decided each.
44
+ `canonical_identifier` and `canonicalise` produce canonical forms. `load_spec()` returns the embedded
45
+ specification, `load_spec_from(directory)` one read from a directory holding `ref-id.json` and its
46
+ `.sha256` sidecar.
47
+
48
+ Every function but `validate_envelope` takes its arguments by position only, as the specification declares
49
+ them unlabelled. Results are frozen dataclasses; `to_json()` gives the specification's own field names.
50
+ Errors are `RefIdError` and its five kinds.
51
+
52
+ `packageurl-python` decides whether a Package URL locator is valid and how its `canonical` field is spelled,
53
+ and the other implementations use other validators. Where they differ is measured in
54
+ [Known differences between implementations](https://github.com/entelekheia-ai/ref-id/blob/main/docs/reference/implementation-differences.md).
55
+
56
+ ## License
57
+
58
+ Apache-2.0. Source, specification and issues: <https://github.com/entelekheia-ai/ref-id>.
@@ -0,0 +1,36 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ [project]
3
+ name = "ref-id"
4
+ version = "0.7.0"
5
+ description = "The ref: identifier scheme — a Python port held to the specification's conformance vectors"
6
+ readme = "README.md"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ requires-python = ">=3.11"
10
+ dependencies = [
11
+ "packageurl-python>=0.17.6,<0.18",
12
+ ]
13
+
14
+ [project.urls]
15
+ Repository = "https://github.com/entelekheia-ai/ref-id"
16
+ Issues = "https://github.com/entelekheia-ai/ref-id/issues"
17
+
18
+ [build-system]
19
+ requires = ["hatchling"]
20
+ build-backend = "hatchling.build"
21
+
22
+ [tool.hatch.build.targets.wheel]
23
+ packages = ["src/ref_id"]
24
+
25
+ [dependency-groups]
26
+ dev = [
27
+ "pytest",
28
+ "mypy",
29
+ "ruff",
30
+ ]
31
+
32
+ [tool.mypy]
33
+ strict = true
34
+
35
+ [tool.ruff]
36
+ target-version = "py311"
@@ -0,0 +1,69 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """The `ref:` identifier scheme — a Python port held to `spec/ref-id.json`'s conformance vectors.
3
+
4
+ Track 2 lands the embedded specification, its integrity check, the canonical serialisation and the set
5
+ digest. Parse, serialise, build and the envelope are Track 3; relations are Track 4.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from .build import build
10
+ from .canonical import canonicalise
11
+ from .digest import digest
12
+ from .envelope import validate_envelope
13
+ from .errors import (
14
+ BuildError,
15
+ DigestError,
16
+ RefIdError,
17
+ SerialiseError,
18
+ SpecIntegrityError,
19
+ SpecVersionError,
20
+ )
21
+ from .parse import parse
22
+ from .relations import covers, relate, same_identifier, same_package, verdict
23
+ from .serialise import canonical_identifier, serialise
24
+ from .spec import Spec, embedded_spec_text, load_spec, load_spec_from
25
+ from .types import (
26
+ BuildParts,
27
+ EnvelopeResult,
28
+ Fragment,
29
+ NestedValue,
30
+ ParseResult,
31
+ QualifierRelation,
32
+ RelateResult,
33
+ VerdictDecidedBy,
34
+ VerdictResult,
35
+ )
36
+
37
+ __all__ = [
38
+ "BuildError",
39
+ "BuildParts",
40
+ "DigestError",
41
+ "EnvelopeResult",
42
+ "Fragment",
43
+ "NestedValue",
44
+ "ParseResult",
45
+ "QualifierRelation",
46
+ "RefIdError",
47
+ "RelateResult",
48
+ "SerialiseError",
49
+ "Spec",
50
+ "SpecIntegrityError",
51
+ "SpecVersionError",
52
+ "VerdictDecidedBy",
53
+ "VerdictResult",
54
+ "build",
55
+ "canonical_identifier",
56
+ "canonicalise",
57
+ "covers",
58
+ "digest",
59
+ "embedded_spec_text",
60
+ "load_spec",
61
+ "load_spec_from",
62
+ "parse",
63
+ "relate",
64
+ "same_identifier",
65
+ "same_package",
66
+ "serialise",
67
+ "validate_envelope",
68
+ "verdict",
69
+ ]
@@ -0,0 +1,146 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Assembles a `ref:` identifier string from its parts. A part the grammar cannot carry is refused with
3
+ `BuildError` naming it — the builder never emits a string that means something else, which is proven at
4
+ the end by parsing what was built and comparing it with what was asked.
5
+
6
+ Ported from `crates/ref-id/src/build.rs`.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from .encoding import contains_any, encode, table_for
13
+ from .errors import BuildError
14
+ from .grammar import (
15
+ FIELD,
16
+ FRAGMENT_INTRODUCER,
17
+ LINE_BREAKS,
18
+ PAIR,
19
+ scheme_prefix,
20
+ )
21
+ from .parse import parse
22
+ from .spec import Spec, load_spec
23
+ from .types import BuildParts, Fragment, NestedValue
24
+ from .validators import folds_type
25
+
26
+ __all__ = ["build"]
27
+
28
+
29
+ def _nesting_form(spec: Spec, key: str) -> dict[str, Any] | None:
30
+ declared = spec.get_object("qualifiers")
31
+ entry = declared.get(key) if declared is not None else None
32
+ if not isinstance(entry, dict):
33
+ return None
34
+ forms = spec.get_object("forms") or {}
35
+ for name in entry.get("forms", []):
36
+ if not isinstance(name, str):
37
+ continue
38
+ form = forms.get(name)
39
+ if isinstance(form, dict) and form.get("nested") is True:
40
+ return form
41
+ return None
42
+
43
+
44
+ def _refuse(spec: Spec, part: str, why: str) -> BuildError:
45
+ return _refuse_at(spec.part(part), why)
46
+
47
+
48
+ def _refuse_at(part: str, why: str) -> BuildError:
49
+ """The message names the refused part, so a caller reads what to change instead of guessing and
50
+ retrying. A part `parse` already reported is used verbatim: it may be a key the identifier carries
51
+ and the spec never declared."""
52
+ return BuildError(part, f"cannot build: {why} — refused at the {part}")
53
+
54
+
55
+ def build(parts: BuildParts, /) -> str:
56
+ """Builds a `ref:` identifier string."""
57
+ spec = load_spec()
58
+ grammar = spec.grammar()
59
+ state_separator = spec.get_str("grammar", "state", "separator")
60
+ fragment_separator = spec.get_str("grammar", "fragment", "separator")
61
+ separators = state_separator + FRAGMENT_INTRODUCER + "".join(LINE_BREAKS)
62
+ fragment_reserved = fragment_separator + "".join(LINE_BREAKS)
63
+
64
+ locator = parts.locator
65
+ fold = f"{parts.type}{FIELD}"
66
+ if folds_type(spec, parts.type) and locator.startswith(fold):
67
+ locator = locator[len(fold) :]
68
+
69
+ if not locator or contains_any(locator, separators):
70
+ raise _refuse(spec, "locator", "a locator is handed to its validator verbatim and cannot carry a reserved character")
71
+
72
+ out = [f"{scheme_prefix(spec)}{parts.type}{FIELD}{locator}"]
73
+
74
+ if parts.qualifiers:
75
+ rendered = []
76
+ for pair in parts.qualifiers:
77
+ # `parts.qualifiers` is declared as a tuple of `(key, value)` pairs; a caller who hands a
78
+ # `dict` instead bypasses the type checker (as `BuildParts.from_json`'s own malformed-shape
79
+ # guard already does for the JSON entry point) and would otherwise unpack each dict *key*
80
+ # string into `key, value` — silently wrong for a two-character key, a bare `ValueError` for
81
+ # any other length. Checked and refused here the same way `from_json` refuses its own shape.
82
+ if not isinstance(pair, (tuple, list)) or len(pair) != 2 or not isinstance(pair[0], str):
83
+ raise _refuse(spec, "state", "a qualifier is a (key, value) pair with a string key")
84
+ key, value = pair
85
+ if isinstance(value, NestedValue):
86
+ if not isinstance(value.nested, str):
87
+ raise _refuse(spec, key, "a qualifier value is a string or NestedValue holding a string")
88
+ form = _nesting_form(spec, key)
89
+ if form is None:
90
+ raise _refuse(spec, key, "this qualifier declares no nesting form")
91
+ encoded = encode(value.nested, table_for(spec, form))
92
+ elif isinstance(value, str):
93
+ if value.startswith(scheme_prefix(spec)) or contains_any(value, separators):
94
+ raise _refuse(spec, key, "a nested identifier is passed as Nested, never as a plain string")
95
+ encoded = value
96
+ else:
97
+ raise _refuse(spec, key, "a qualifier value is a string or NestedValue holding a string")
98
+ rendering = f"{key}{PAIR}{encoded}"
99
+ if grammar.state_pair.fullmatch(rendering) is None:
100
+ raise _refuse(spec, key, "the key does not fit the pair grammar")
101
+ rendered.append(rendering)
102
+ out.append(state_separator)
103
+ out.append(state_separator.join(rendered))
104
+
105
+ wanted_path: str | None = None
106
+ wanted_refinements: tuple[tuple[str, str], ...] = ()
107
+ if parts.fragment is not None:
108
+ if isinstance(parts.fragment, str):
109
+ path = parts.fragment
110
+ elif isinstance(parts.fragment, Fragment):
111
+ path = parts.fragment.path
112
+ wanted_refinements = parts.fragment.refinements
113
+ else:
114
+ raise _refuse(spec, "fragment", "a fragment is a string or Fragment")
115
+ if not path or contains_any(path, fragment_reserved):
116
+ raise _refuse(spec, "fragment", "a declared-name path cannot be empty or carry the refinement separator")
117
+ for key, value in wanted_refinements:
118
+ if contains_any(value, fragment_reserved):
119
+ raise _refuse(spec, key, "a refinement value cannot carry the separator")
120
+ out.append(FRAGMENT_INTRODUCER)
121
+ out.append(path)
122
+ if wanted_refinements:
123
+ out.append(fragment_separator)
124
+ out.append(fragment_separator.join(f"{key}{PAIR}{value}" for key, value in wanted_refinements))
125
+ wanted_path = path
126
+
127
+ assembled = "".join(out)
128
+
129
+ # The last word is the grammar's: what was built must decompose to exactly what was asked.
130
+ if grammar.top.fullmatch(assembled) is None:
131
+ raise _refuse(spec, "grammar", "the assembled string does not match the grammar")
132
+ check = parse(assembled)
133
+ if check.status == spec.status("malformed"):
134
+ refused = check.part if check.part is not None else spec.part("grammar")
135
+ raise _refuse_at(refused, "the assembled string is malformed")
136
+ if check.explicit_version or check.type != parts.type:
137
+ raise _refuse(spec, "type", "the type re-split into other parts")
138
+ if check.locator != locator:
139
+ raise _refuse(spec, "locator", "the locator re-split into other parts")
140
+ if len(check.qualifiers) != len(parts.qualifiers):
141
+ raise _refuse(spec, "state", "a qualifier re-split into other parts")
142
+ check_path = check.fragment.path if check.fragment is not None else None
143
+ check_refinements = len(check.fragment.refinements) if check.fragment is not None else 0
144
+ if check_path != wanted_path or check_refinements != len(wanted_refinements):
145
+ raise _refuse(spec, "fragment", "the fragment re-split into other parts")
146
+ return assembled