jentic-openapi-transformer 1.0.0a18__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.
@@ -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 [yyyy] [name of copyright owner]
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.
@@ -0,0 +1,4 @@
1
+ Jentic OpenAPI Tools
2
+ Copyright (c) 2025 Jentic
3
+ Jentic OpenAPI Tools is licensed under Apache 2.0 license.
4
+ Copy of the Apache 2.0 license can be found in `LICENSE` file.
@@ -0,0 +1,198 @@
1
+ Metadata-Version: 2.4
2
+ Name: jentic-openapi-transformer
3
+ Version: 1.0.0a18
4
+ Summary: Jentic OpenAPI Transformer
5
+ Author: Jentic
6
+ Author-email: Jentic <hello@jentic.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ License-File: NOTICE
10
+ Requires-Dist: jentic-openapi-common~=1.0.0a18
11
+ Requires-Dist: jentic-openapi-parser~=1.0.0a18
12
+ Requires-Dist: jentic-openapi-traverse~=1.0.0a18
13
+ Requires-Dist: jentic-openapi-transformer-redocly~=1.0.0a18 ; extra == 'redocly'
14
+ Requires-Python: >=3.11
15
+ Project-URL: Homepage, https://github.com/jentic/jentic-openapi-tools
16
+ Provides-Extra: redocly
17
+ Description-Content-Type: text/markdown
18
+
19
+ # jentic-openapi-transformer
20
+
21
+ A Python library for transforming and bundling OpenAPI documents. This package is part of the Jentic OpenAPI Tools ecosystem and provides a flexible, extensible architecture for OpenAPI document transformation with support for pluggable backends.
22
+
23
+ ## Features
24
+
25
+ - **Pluggable Backend Architecture**: Support for multiple bundling strategies via entry points
26
+ - **Multiple Input Formats**: Accept OpenAPI documents as file paths, URIs, or Python dictionaries
27
+ - **Flexible Output Types**: Return bundled documents as JSON strings or Python dictionaries
28
+ - **Type Safety**: Full type hints with overloaded methods for precise return types
29
+ - **Extensible Design**: Easy integration of third-party bundling backends
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pip install jentic-openapi-transformer
35
+ ```
36
+
37
+ **Prerequisites:**
38
+ - Python 3.11+
39
+
40
+ **Optional Backends:**
41
+
42
+ For advanced bundling with external reference resolution:
43
+
44
+ ```bash
45
+ pip install jentic-openapi-transformer-redocly
46
+ ```
47
+
48
+ ## Quick Start
49
+
50
+ ### Basic Bundling
51
+
52
+ ```python
53
+ from jentic.apitools.openapi.transformer.bundler.core import OpenAPIBundler
54
+
55
+ # Create a bundler with the default backend
56
+ bundler = OpenAPIBundler()
57
+
58
+ # Bundle from a file URI and return as dictionary
59
+ result = bundler.bundle("file:///path/to/openapi.yaml", return_type=dict)
60
+ print(result["info"]["title"])
61
+
62
+ # Bundle from a file URI and return as JSON string
63
+ json_result = bundler.bundle("file:///path/to/openapi.yaml", return_type=str)
64
+ print(json_result)
65
+ ```
66
+
67
+ ### Bundle from Dictionary
68
+
69
+ ```python
70
+ # Bundle an OpenAPI document from a Python dictionary
71
+ openapi_doc = {
72
+ "openapi": "3.1.0",
73
+ "info": {"title": "My API", "version": "1.0.0"},
74
+ "paths": {
75
+ "/users": {
76
+ "get": {
77
+ "summary": "Get users",
78
+ "responses": {"200": {"description": "Success"}}
79
+ }
80
+ }
81
+ }
82
+ }
83
+
84
+ result = bundler.bundle(openapi_doc, return_type=dict)
85
+ ```
86
+
87
+ ### Using Different Backends
88
+
89
+ ```python
90
+ # Use the default backend (no external reference resolution)
91
+ bundler = OpenAPIBundler("default")
92
+ result = bundler.bundle("/path/to/openapi.yaml", return_type=dict)
93
+
94
+ # Use the Redocly backend (requires jentic-openapi-transformer-redocly)
95
+ bundler = OpenAPIBundler("redocly")
96
+ result = bundler.bundle("/path/to/openapi.yaml", return_type=dict)
97
+ ```
98
+
99
+ ## Configuration Options
100
+
101
+ ### Backend Selection
102
+
103
+ ```python
104
+ # Use default backend by name
105
+ bundler = OpenAPIBundler("default")
106
+
107
+ # Pass a backend instance directly
108
+ from jentic.apitools.openapi.transformer.bundler.backends.default import DefaultBundlerBackend
109
+ backend = DefaultBundlerBackend()
110
+ bundler = OpenAPIBundler(backend=backend)
111
+
112
+ # Pass a backend class
113
+ bundler = OpenAPIBundler(backend=DefaultBundlerBackend)
114
+ ```
115
+
116
+ ### Custom Parser
117
+
118
+ ```python
119
+ from jentic.apitools.openapi.parser.core import OpenAPIParser
120
+
121
+ # Use a custom parser instance
122
+ parser = OpenAPIParser()
123
+ bundler = OpenAPIBundler(parser=parser)
124
+ ```
125
+
126
+ ### Return Type Control
127
+
128
+ ```python
129
+ # Return as dictionary (typed)
130
+ dict_result: dict = bundler.bundle(document, return_type=dict)
131
+
132
+ # Return as JSON string (typed)
133
+ str_result: str = bundler.bundle(document, return_type=str)
134
+
135
+ # Return as plain (auto-detected type)
136
+ plain_result = bundler.bundle(document)
137
+ ```
138
+
139
+ ### Strict Mode
140
+
141
+ ```python
142
+ # Enable strict type checking for return type
143
+ try:
144
+ result = bundler.bundle(document, return_type=dict, strict=True)
145
+ except TypeError as e:
146
+ print(f"Type mismatch: {e}")
147
+ ```
148
+
149
+ ## Testing
150
+
151
+ Run the test suite:
152
+
153
+ ```bash
154
+ uv run --package jentic-openapi-transformer pytest packages/jentic-openapi-transformer -v
155
+ ```
156
+
157
+ ### Integration Tests
158
+
159
+ The package includes integration tests for backend discovery and bundling. Tests requiring external backends (like Redocly) will be automatically skipped if the backend package is not installed.
160
+
161
+ ## API Reference
162
+
163
+ ### OpenAPIBundler
164
+
165
+ ```python
166
+ class OpenAPIBundler:
167
+ def __init__(
168
+ self,
169
+ backend: str | BaseBundlerBackend | Type[BaseBundlerBackend] | None = None,
170
+ parser: OpenAPIParser | None = None,
171
+ ) -> None
172
+ ```
173
+
174
+ **Parameters:**
175
+ - `backend`: Backend name, instance, or class. Defaults to "default"
176
+ - `parser`: Custom OpenAPIParser instance (optional)
177
+
178
+ **Methods:**
179
+
180
+ - `bundle(document: str | dict, base_url: str | None = None, *, return_type: type[T] | None = None, strict: bool = False) -> T`
181
+ - Bundles an OpenAPI document with specified return type
182
+ - `document`: File path, URI, JSON/YAML string, or dictionary
183
+ - `base_url`: Optional base URL for resolving relative references
184
+ - `return_type`: Desired output type (str, dict, or None for auto)
185
+ - `strict`: Enable strict return type validation
186
+
187
+ ## Available Backends
188
+
189
+ ### base
190
+ Abstract base class for custom bundler backends. Not for direct use.
191
+
192
+ ### default
193
+ Basic bundling backend without external reference resolution. Suitable for single-file OpenAPI documents.
194
+
195
+ ### redocly (Optional)
196
+ Advanced bundling backend using Redocly CLI with full reference resolution across multiple files.
197
+
198
+ Install: `pip install jentic-openapi-transformer-redocly`
@@ -0,0 +1,180 @@
1
+ # jentic-openapi-transformer
2
+
3
+ A Python library for transforming and bundling OpenAPI documents. This package is part of the Jentic OpenAPI Tools ecosystem and provides a flexible, extensible architecture for OpenAPI document transformation with support for pluggable backends.
4
+
5
+ ## Features
6
+
7
+ - **Pluggable Backend Architecture**: Support for multiple bundling strategies via entry points
8
+ - **Multiple Input Formats**: Accept OpenAPI documents as file paths, URIs, or Python dictionaries
9
+ - **Flexible Output Types**: Return bundled documents as JSON strings or Python dictionaries
10
+ - **Type Safety**: Full type hints with overloaded methods for precise return types
11
+ - **Extensible Design**: Easy integration of third-party bundling backends
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pip install jentic-openapi-transformer
17
+ ```
18
+
19
+ **Prerequisites:**
20
+ - Python 3.11+
21
+
22
+ **Optional Backends:**
23
+
24
+ For advanced bundling with external reference resolution:
25
+
26
+ ```bash
27
+ pip install jentic-openapi-transformer-redocly
28
+ ```
29
+
30
+ ## Quick Start
31
+
32
+ ### Basic Bundling
33
+
34
+ ```python
35
+ from jentic.apitools.openapi.transformer.bundler.core import OpenAPIBundler
36
+
37
+ # Create a bundler with the default backend
38
+ bundler = OpenAPIBundler()
39
+
40
+ # Bundle from a file URI and return as dictionary
41
+ result = bundler.bundle("file:///path/to/openapi.yaml", return_type=dict)
42
+ print(result["info"]["title"])
43
+
44
+ # Bundle from a file URI and return as JSON string
45
+ json_result = bundler.bundle("file:///path/to/openapi.yaml", return_type=str)
46
+ print(json_result)
47
+ ```
48
+
49
+ ### Bundle from Dictionary
50
+
51
+ ```python
52
+ # Bundle an OpenAPI document from a Python dictionary
53
+ openapi_doc = {
54
+ "openapi": "3.1.0",
55
+ "info": {"title": "My API", "version": "1.0.0"},
56
+ "paths": {
57
+ "/users": {
58
+ "get": {
59
+ "summary": "Get users",
60
+ "responses": {"200": {"description": "Success"}}
61
+ }
62
+ }
63
+ }
64
+ }
65
+
66
+ result = bundler.bundle(openapi_doc, return_type=dict)
67
+ ```
68
+
69
+ ### Using Different Backends
70
+
71
+ ```python
72
+ # Use the default backend (no external reference resolution)
73
+ bundler = OpenAPIBundler("default")
74
+ result = bundler.bundle("/path/to/openapi.yaml", return_type=dict)
75
+
76
+ # Use the Redocly backend (requires jentic-openapi-transformer-redocly)
77
+ bundler = OpenAPIBundler("redocly")
78
+ result = bundler.bundle("/path/to/openapi.yaml", return_type=dict)
79
+ ```
80
+
81
+ ## Configuration Options
82
+
83
+ ### Backend Selection
84
+
85
+ ```python
86
+ # Use default backend by name
87
+ bundler = OpenAPIBundler("default")
88
+
89
+ # Pass a backend instance directly
90
+ from jentic.apitools.openapi.transformer.bundler.backends.default import DefaultBundlerBackend
91
+ backend = DefaultBundlerBackend()
92
+ bundler = OpenAPIBundler(backend=backend)
93
+
94
+ # Pass a backend class
95
+ bundler = OpenAPIBundler(backend=DefaultBundlerBackend)
96
+ ```
97
+
98
+ ### Custom Parser
99
+
100
+ ```python
101
+ from jentic.apitools.openapi.parser.core import OpenAPIParser
102
+
103
+ # Use a custom parser instance
104
+ parser = OpenAPIParser()
105
+ bundler = OpenAPIBundler(parser=parser)
106
+ ```
107
+
108
+ ### Return Type Control
109
+
110
+ ```python
111
+ # Return as dictionary (typed)
112
+ dict_result: dict = bundler.bundle(document, return_type=dict)
113
+
114
+ # Return as JSON string (typed)
115
+ str_result: str = bundler.bundle(document, return_type=str)
116
+
117
+ # Return as plain (auto-detected type)
118
+ plain_result = bundler.bundle(document)
119
+ ```
120
+
121
+ ### Strict Mode
122
+
123
+ ```python
124
+ # Enable strict type checking for return type
125
+ try:
126
+ result = bundler.bundle(document, return_type=dict, strict=True)
127
+ except TypeError as e:
128
+ print(f"Type mismatch: {e}")
129
+ ```
130
+
131
+ ## Testing
132
+
133
+ Run the test suite:
134
+
135
+ ```bash
136
+ uv run --package jentic-openapi-transformer pytest packages/jentic-openapi-transformer -v
137
+ ```
138
+
139
+ ### Integration Tests
140
+
141
+ The package includes integration tests for backend discovery and bundling. Tests requiring external backends (like Redocly) will be automatically skipped if the backend package is not installed.
142
+
143
+ ## API Reference
144
+
145
+ ### OpenAPIBundler
146
+
147
+ ```python
148
+ class OpenAPIBundler:
149
+ def __init__(
150
+ self,
151
+ backend: str | BaseBundlerBackend | Type[BaseBundlerBackend] | None = None,
152
+ parser: OpenAPIParser | None = None,
153
+ ) -> None
154
+ ```
155
+
156
+ **Parameters:**
157
+ - `backend`: Backend name, instance, or class. Defaults to "default"
158
+ - `parser`: Custom OpenAPIParser instance (optional)
159
+
160
+ **Methods:**
161
+
162
+ - `bundle(document: str | dict, base_url: str | None = None, *, return_type: type[T] | None = None, strict: bool = False) -> T`
163
+ - Bundles an OpenAPI document with specified return type
164
+ - `document`: File path, URI, JSON/YAML string, or dictionary
165
+ - `base_url`: Optional base URL for resolving relative references
166
+ - `return_type`: Desired output type (str, dict, or None for auto)
167
+ - `strict`: Enable strict return type validation
168
+
169
+ ## Available Backends
170
+
171
+ ### base
172
+ Abstract base class for custom bundler backends. Not for direct use.
173
+
174
+ ### default
175
+ Basic bundling backend without external reference resolution. Suitable for single-file OpenAPI documents.
176
+
177
+ ### redocly (Optional)
178
+ Advanced bundling backend using Redocly CLI with full reference resolution across multiple files.
179
+
180
+ Install: `pip install jentic-openapi-transformer-redocly`
@@ -0,0 +1,42 @@
1
+ [project]
2
+ name = "jentic-openapi-transformer"
3
+ version = "1.0.0-alpha.18"
4
+ description = "Jentic OpenAPI Transformer"
5
+ readme = "README.md"
6
+ authors = [{ name = "Jentic", email = "hello@jentic.com" }]
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE", "NOTICE"]
9
+ requires-python = ">=3.11"
10
+ dependencies = [
11
+ "jentic-openapi-common~=1.0.0-alpha.18",
12
+ "jentic-openapi-parser~=1.0.0-alpha.18",
13
+ "jentic-openapi-traverse~=1.0.0-alpha.18",
14
+ ]
15
+
16
+ [tool.uv]
17
+ package = true
18
+
19
+ [tool.uv.build-backend]
20
+ namespace = true
21
+ module-name = "jentic.apitools.openapi.transformer"
22
+ module-root = "src/"
23
+
24
+ [project.optional-dependencies]
25
+ redocly = ["jentic-openapi-transformer-redocly~=1.0.0-alpha.18"]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/jentic/jentic-openapi-tools"
29
+
30
+ [tool.uv.sources]
31
+ jentic-openapi-common = { workspace = true }
32
+ jentic-openapi-parser = { workspace = true }
33
+ jentic-openapi-traverse = { workspace = true }
34
+ jentic-openapi-transformer-redocly = { workspace = true }
35
+
36
+
37
+ [build-system]
38
+ requires = ["uv_build~=0.8.15"]
39
+ build-backend = "uv_build"
40
+
41
+ [project.entry-points."jentic.apitools.openapi.transformer.bundler.backends"]
42
+ default = "jentic.apitools.openapi.transformer.bundler.backends.default:DefaultBundlerBackend"
@@ -0,0 +1,48 @@
1
+ from abc import ABC, abstractmethod
2
+ from collections.abc import Sequence
3
+ from typing import Any
4
+
5
+
6
+ __all__ = ["BaseBundlerBackend"]
7
+
8
+
9
+ class BaseBundlerBackend(ABC):
10
+ """
11
+ Base interface that all bundler backends must implement.
12
+
13
+ Bundler backends are responsible for taking OpenAPI documents and transforming
14
+ them through various operations like bundling, reference resolution, component
15
+ extraction, etc.
16
+ """
17
+
18
+ @abstractmethod
19
+ def bundle(self, document: str | dict, *, base_url: str | None = None) -> Any:
20
+ """
21
+ Bundle an OpenAPI document.
22
+
23
+ Args:
24
+ document: The OpenAPI document to bundle. Can be a string (JSON/YAML)
25
+ or a dict representation.
26
+ base_url: Optional base URI for resolving relative references.
27
+
28
+ Returns:
29
+ The bundled OpenAPI document. Type conversion is handled by the main bundler class.
30
+
31
+ Raises:
32
+ Exception: If bundling fails for any reason.
33
+ """
34
+ ...
35
+
36
+ @staticmethod
37
+ @abstractmethod
38
+ def accepts() -> Sequence[str]:
39
+ """
40
+ Return a sequence of input formats this backend can handle.
41
+
42
+ Returns:
43
+ Sequence of supported input formats. Common values:
44
+ - "dict": Accepts dictionary/object representation
45
+ - "text": Accepts string (JSON/YAML) representation
46
+ - "uri": Accepts URI/file path references
47
+ """
48
+ ...
@@ -0,0 +1,38 @@
1
+ from collections.abc import Sequence
2
+ from typing import Literal
3
+
4
+ from jentic.apitools.openapi.transformer.bundler.backends.base import BaseBundlerBackend
5
+
6
+
7
+ __all__ = ["DefaultBundlerBackend"]
8
+
9
+
10
+ class DefaultBundlerBackend(BaseBundlerBackend):
11
+ """
12
+ Default bundler backend that performs basic pass-through bundling.
13
+
14
+ This is a placeholder implementation that returns the document unchanged.
15
+ In a production implementation, this would perform actual bundling operations
16
+ like reference resolution, component extraction, etc.
17
+ """
18
+
19
+ def bundle(self, document: str | dict, *, base_url: str | None = None) -> dict:
20
+ """
21
+ Bundle an OpenAPI document using the default backend.
22
+
23
+ Currently, performs no actual bundling - just validates the input
24
+ and returns it unchanged.
25
+ """
26
+ if not isinstance(document, dict):
27
+ raise TypeError(f"Default bundler expects dict input, got {type(document).__name__}")
28
+ return document
29
+
30
+ @staticmethod
31
+ def accepts() -> Sequence[Literal["dict"]]:
32
+ """Return supported input formats.
33
+
34
+ Returns:
35
+ Sequence of supported document format identifiers:
36
+ - "dict": Python dictionary containing OpenAPI Document data
37
+ """
38
+ return ["dict"]
@@ -0,0 +1,4 @@
1
+ from .bundler import OpenAPIBundler
2
+
3
+
4
+ __all__ = ["OpenAPIBundler"]
@@ -0,0 +1,211 @@
1
+ import importlib.metadata
2
+ import json
3
+ import logging
4
+ import warnings
5
+ from typing import Any, Mapping, Sequence, Type, TypeVar, cast, overload
6
+
7
+ from jentic.apitools.openapi.parser.core import OpenAPIParser
8
+ from jentic.apitools.openapi.transformer.bundler.backends.base import BaseBundlerBackend
9
+
10
+
11
+ __all__ = ["OpenAPIBundler"]
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ # Cache entry points at module level for performance
17
+ try:
18
+ _BUNDLER_BACKENDS = {
19
+ ep.name: ep
20
+ for ep in importlib.metadata.entry_points(
21
+ group="jentic.apitools.openapi.transformer.bundler.backends"
22
+ )
23
+ }
24
+ except Exception as e:
25
+ warnings.warn(f"Failed to load bundler backend entry points: {e}", RuntimeWarning)
26
+ _BUNDLER_BACKENDS = {}
27
+
28
+ T = TypeVar("T")
29
+
30
+
31
+ class OpenAPIBundler:
32
+ """
33
+ Provides a bundler for OpenAPI specifications using customizable backends.
34
+
35
+ This class is designed to facilitate the bundling of OpenAPI documents.
36
+ It supports one backend at a time and can be extended through backends.
37
+
38
+ Attributes:
39
+ backend: Backend used by the parser implementing the BaseBundlerBackend interface.
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ backend: str | BaseBundlerBackend | Type[BaseBundlerBackend] | None = None,
45
+ parser: OpenAPIParser | None = None,
46
+ ):
47
+ self.parser = parser if parser else OpenAPIParser()
48
+ backend = backend if backend else "default"
49
+
50
+ if isinstance(backend, str):
51
+ if backend in _BUNDLER_BACKENDS:
52
+ backend_class = _BUNDLER_BACKENDS[backend].load() # loads the class
53
+ self.backend = backend_class()
54
+ else:
55
+ raise ValueError(f"No bundler backend named '{backend}' found")
56
+ elif isinstance(backend, BaseBundlerBackend):
57
+ self.backend = backend
58
+ elif isinstance(backend, type) and issubclass(backend, BaseBundlerBackend):
59
+ # if a class (not instance) is passed
60
+ self.backend = backend()
61
+ else:
62
+ raise TypeError("Invalid backend type: must be name or backend class/instance")
63
+
64
+ @overload
65
+ def bundle(
66
+ self,
67
+ document: str | dict,
68
+ base_url: str | None = None,
69
+ *,
70
+ return_type: type[str],
71
+ strict: bool = False,
72
+ ) -> str: ...
73
+
74
+ @overload
75
+ def bundle(
76
+ self,
77
+ document: str | dict,
78
+ base_url: str | None = None,
79
+ *,
80
+ return_type: type[dict[str, Any]],
81
+ strict: bool = False,
82
+ ) -> dict[str, Any]: ...
83
+
84
+ @overload
85
+ def bundle(
86
+ self,
87
+ document: str | dict,
88
+ base_url: str | None = None,
89
+ *,
90
+ return_type: type[T],
91
+ strict: bool = False,
92
+ ) -> T: ...
93
+
94
+ def bundle(
95
+ self,
96
+ document: str | dict,
97
+ base_url: str | None = None,
98
+ *,
99
+ return_type: type[T] | None = None,
100
+ strict: bool = False,
101
+ ) -> Any:
102
+ raw = self._bundle(document, base_url)
103
+
104
+ if return_type is None:
105
+ return self._to_plain(raw)
106
+
107
+ # Handle conversion to a string type
108
+ if return_type is str and not isinstance(raw, str):
109
+ if isinstance(raw, (dict, list)):
110
+ return cast(T, json.dumps(raw))
111
+ else:
112
+ return cast(T, str(raw))
113
+
114
+ # Handle conversion from string to dict type
115
+ if return_type is dict and isinstance(raw, str):
116
+ try:
117
+ return cast(T, json.loads(raw))
118
+ except json.JSONDecodeError:
119
+ if strict:
120
+ raise ValueError(f"Cannot parse string as JSON: {raw}")
121
+ return cast(T, raw)
122
+
123
+ if strict:
124
+ if not isinstance(raw, return_type):
125
+ raise TypeError(
126
+ f"Expected {getattr(return_type, '__name__', return_type)}, "
127
+ f"got {type(raw).__name__}"
128
+ )
129
+
130
+ return cast(T, raw)
131
+
132
+ def _bundle(self, document: str | dict, base_url: str | None = None) -> Any:
133
+ text = document
134
+ data = None
135
+ result = None
136
+
137
+ if isinstance(document, str):
138
+ is_uri = self.parser.is_uri_like(document)
139
+ is_text = not is_uri
140
+
141
+ if is_text:
142
+ data = self.parser.parse(document)
143
+
144
+ if is_uri and self.has_non_uri_backend():
145
+ text = self.parser.load_uri(document)
146
+ if not data or data is None:
147
+ data = self.parser.parse(text)
148
+ else:
149
+ is_uri = False
150
+
151
+ data = text if not data or data is None else data
152
+
153
+ backend_document = None
154
+ if is_uri and "uri" in self.backend.accepts():
155
+ backend_document = document
156
+ elif is_uri and "text" in self.backend.accepts():
157
+ backend_document = text
158
+ elif is_uri and "dict" in self.backend.accepts():
159
+ backend_document = data
160
+ elif not is_uri and "text" in self.backend.accepts():
161
+ backend_document = text
162
+ elif not is_uri and "dict" in self.backend.accepts():
163
+ backend_document = data
164
+
165
+ if backend_document is not None:
166
+ try:
167
+ result = self.backend.bundle(backend_document)
168
+ except Exception:
169
+ # TODO(fracensco@jentic.com): Add to parser/validation chain result
170
+ logger.exception("Error bundling document")
171
+ raise
172
+
173
+ if result is None:
174
+ raise ValueError("No valid document found")
175
+ return result
176
+
177
+ def has_non_uri_backend(self) -> bool:
178
+ """Check if any backend accepts 'text' or 'dict' but not 'uri'."""
179
+ accepted = self.backend.accepts()
180
+ return ("text" in accepted or "dict" in accepted) and "uri" not in accepted
181
+
182
+ def _to_plain(self, value: Any) -> Any:
183
+ # Mapping
184
+ if isinstance(value, Mapping):
185
+ return {k: self._to_plain(v) for k, v in value.items()}
186
+
187
+ # Sequence but NOT str/bytes
188
+ if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
189
+ return [self._to_plain(x) for x in value]
190
+
191
+ # Scalar
192
+ return value
193
+
194
+ @staticmethod
195
+ def list_backends() -> list[str]:
196
+ """
197
+ List all available bundler backends registered via entry points.
198
+
199
+ This static method discovers and returns the names of all bundler backends
200
+ that have been registered in the 'jentic.apitools.openapi.transformer.bundler.backends'
201
+ entry point group.
202
+
203
+ Returns:
204
+ List of backend names that can be used when initializing OpenAPIBundler.
205
+
206
+ Example:
207
+ >>> backends = OpenAPIBundler.list_backends()
208
+ >>> print(backends)
209
+ ['default', 'redocly']
210
+ """
211
+ return list(_BUNDLER_BACKENDS.keys())
@@ -0,0 +1,4 @@
1
+ from .normalize import normalize
2
+
3
+
4
+ __all__ = ["normalize"]
@@ -0,0 +1,12 @@
1
+ from jentic.apitools.openapi.parser.core import OpenAPIParser
2
+
3
+
4
+ def normalize(document: str) -> dict:
5
+ """
6
+ Parse and perform a trivial 'normalization' to prove the flow works.
7
+ Later: real bundling, $ref deref, component hoisting, etc.
8
+ """
9
+ parse_result = dict(OpenAPIParser().parse(document))
10
+ parse_result.setdefault("x-jentic", {})["transformed"] = True
11
+
12
+ return parse_result
@@ -0,0 +1,218 @@
1
+ from typing import Any, Iterator, List, MutableMapping, Tuple, cast
2
+ from urllib.parse import urljoin
3
+
4
+ from jentic.apitools.openapi.common.uri import (
5
+ is_absolute_uri,
6
+ is_fragment_only_uri,
7
+ is_http_https_url,
8
+ is_scheme_relative_uri,
9
+ )
10
+ from jentic.apitools.openapi.traverse.json import JSONPath, traverse
11
+
12
+
13
+ # TODO(vladimir@jentic.com): this needs to be refactored when we have OpenAPI datamodel available
14
+
15
+ __all__ = [
16
+ "find_relative_urls",
17
+ "find_absolute_http_urls",
18
+ "RewriteOptions",
19
+ "rewrite_urls_inplace",
20
+ "iter_url_fields",
21
+ "count_references",
22
+ ]
23
+
24
+
25
+ def count_references(root: Any) -> Tuple[int, int, int, int]:
26
+ """
27
+ Counts the number of references in a given data structure based on their type.
28
+
29
+ This function iterates through the provided structure to analyze and classify
30
+ different kinds of references. The classification includes relative references,
31
+ absolute HTTP/HTTPS references, local references, and the total number of
32
+ references.
33
+
34
+ Args:
35
+ root: Any
36
+ The root data structure containing references to be analyzed.
37
+
38
+ Returns:
39
+ Tuple[int, int, int, int]: A tuple containing the following counts:
40
+ - Total references count
41
+ - Local references count
42
+ - Relative references count
43
+ - Absolute HTTP/HTTPS references count
44
+ """
45
+ relative_refs_count = 0
46
+ absolute_http_refs_count = 0
47
+ total_refs_count = 0
48
+ local_refs_count = 0
49
+
50
+ for path, _parent, key, value in iter_url_fields(root):
51
+ assert isinstance(key, str)
52
+ total_refs_count += 1
53
+ if key == "$ref" and is_fragment_only_uri(value):
54
+ local_refs_count += 1
55
+ continue
56
+ if _is_relative_like(value):
57
+ relative_refs_count += 1
58
+ elif not _is_relative_like(value) and is_http_https_url(value):
59
+ absolute_http_refs_count += 1
60
+ return total_refs_count, local_refs_count, relative_refs_count, absolute_http_refs_count
61
+
62
+
63
+ def find_relative_urls(root: Any) -> List[Tuple[JSONPath, str, str]]:
64
+ """
65
+ Return a list of (json_path, key, value) for any URL-like field
66
+ (including $ref) whose value is relative (e.g., 'schemas/a.yaml', '../b', '/c')
67
+ and not a pure fragment '#/...' .
68
+ """
69
+ out: List[Tuple[JSONPath, str, str]] = []
70
+ for path, _parent, key, value in iter_url_fields(root):
71
+ assert isinstance(key, str)
72
+ if key == "$ref" and is_fragment_only_uri(value):
73
+ continue
74
+ if _is_relative_like(value):
75
+ new_path = cast(JSONPath, (*path, key))
76
+ out.append((new_path, key, value))
77
+ return out
78
+
79
+
80
+ def find_absolute_http_urls(root: Any) -> List[Tuple[JSONPath, str, str]]:
81
+ """
82
+ Return a list of (json_path, key, value) for any URL-like field
83
+ (including $ref) whose value is absolute and http
84
+ """
85
+ out: List[Tuple[JSONPath, str, str]] = []
86
+ for path, _parent, key, value in iter_url_fields(root):
87
+ assert isinstance(key, str)
88
+ if key == "$ref" and is_fragment_only_uri(value):
89
+ continue
90
+ if not _is_relative_like(value) and is_http_https_url(value):
91
+ new_path = cast(JSONPath, (*path, key))
92
+ out.append((new_path, key, value))
93
+ return out
94
+
95
+
96
+ class RewriteOptions:
97
+ """
98
+ Options for rewrite_urls_inplace.
99
+ - base_url: New base for *relative* refs/URLs.
100
+ - original_base_url: If provided together with include_absolute_urls=True, we'll
101
+ retarget absolute URLs that begin with original_base_url to base_url.
102
+ - include_absolute_urls: If True (and original_base_url given), retarget absolute URLs too.
103
+ """
104
+
105
+ __slots__ = ("base_url", "original_base_url", "include_absolute_urls")
106
+
107
+ def __init__(
108
+ self,
109
+ base_url: str,
110
+ original_base_url: str | None = None,
111
+ include_absolute_urls: bool = False,
112
+ ) -> None:
113
+ self.base_url = base_url
114
+ self.original_base_url = original_base_url
115
+ self.include_absolute_urls = include_absolute_urls
116
+
117
+
118
+ def rewrite_urls_inplace(root: Any, opts: RewriteOptions) -> int:
119
+ """
120
+ Rewrite $ref and other URL-bearing fields in-place.
121
+ Rules:
122
+ - Relative values (except fragment-only) are absolutized against opts.base_url.
123
+ - If opts.include_absolute_urls and opts.original_base_url are set,
124
+ then any absolute URL beginning with original_base_url gets retargeted
125
+ to opts.base_url (prefix replacement).
126
+ Returns the number of fields changed.
127
+ """
128
+ changed = 0
129
+ for _path, parent, key, value in iter_url_fields(root):
130
+ # value is str by iter_url_fields contract
131
+ if key == "$ref" and is_fragment_only_uri(value):
132
+ continue # keep pure fragments
133
+
134
+ new_value = value
135
+ if _is_relative_like(value):
136
+ new_value = _absolutize(value, opts.base_url)
137
+ elif opts.include_absolute_urls and opts.original_base_url and is_absolute_uri(value):
138
+ new_value = _retarget_absolute(value, opts.original_base_url, opts.base_url)
139
+
140
+ if new_value != value:
141
+ parent[key] = new_value # parent is a mapping; key is str
142
+ changed += 1
143
+
144
+ return changed
145
+
146
+
147
+ def iter_url_fields(root: Any) -> Iterator[Tuple[JSONPath, MutableMapping[str, Any], str, str]]:
148
+ """
149
+ Iterate over all places that likely carry URL/URI/Reference strings,
150
+ including $ref and common OpenAPI URL-bearing keys.
151
+ """
152
+ for node in traverse(root):
153
+ if (
154
+ isinstance(node.parent, MutableMapping)
155
+ and isinstance(node.segment, str)
156
+ and isinstance(node.value, str)
157
+ and node.segment in _URL_KEYS_EXPLICIT
158
+ ):
159
+ yield node.path, node.parent, node.segment, node.value
160
+
161
+
162
+ # Keys that *by spec* or convention carry URL/URI references (OpenAPI 3.0/3.1).
163
+ _URL_KEYS_EXPLICIT: frozenset[str] = frozenset(
164
+ {
165
+ # JSON Reference
166
+ "$ref",
167
+ # JSON Schema / examples / links
168
+ "externalValue",
169
+ "operationRef",
170
+ # Info/Contact/License
171
+ "termsOfService",
172
+ "url", # Contact.url, License.url, ExternalDocs.url, Server.url, etc.
173
+ # OAuth/OpenID
174
+ "authorizationUrl",
175
+ "tokenUrl",
176
+ "refreshUrl",
177
+ "openIdConnectUrl",
178
+ # Server Variable namespace can influence URLs, but we avoid touching variables.*.default
179
+ # Add more as needed (e.g., "namespace" in XML Object).
180
+ }
181
+ )
182
+
183
+
184
+ def _looks_like_uri(s: str) -> bool:
185
+ # Heuristic: treat strings with ':' before any slash as potentially absolute
186
+ # but we also want to catch relative paths like './x', '../x', 'a/b', '/a'
187
+ # We'll consider *any* non-empty string that isn't pure fragment as a URI candidate,
188
+ # and then rely on absolute/relative checks above.
189
+ return isinstance(s, str) and s != "" and not s.isspace()
190
+
191
+
192
+ def _has_prefix(url: str, base: str) -> bool:
193
+ # Normalize both and compare prefix; use straightforward string prefix
194
+ # because urljoin/urlparse can recompose differently. Assumes base ends
195
+ # at a directory or resource boundary that you control.
196
+ return url.startswith(base)
197
+
198
+
199
+ def _retarget_absolute(url: str, original_base_url: str, new_base_url: str) -> str:
200
+ """If url starts with original_base_url, replace with new_base_url."""
201
+ if _has_prefix(url, original_base_url):
202
+ return new_base_url + url[len(original_base_url) :]
203
+ return url
204
+
205
+
206
+ def _absolutize(url: str, base_url: str) -> str:
207
+ """Make a relative URL absolute against base_url."""
208
+ return urljoin(base_url, url)
209
+
210
+
211
+ def _is_relative_like(s: str) -> bool:
212
+ """Relative (incl. root-relative '/x') and not fragment-only or scheme-relative."""
213
+ if not _looks_like_uri(s):
214
+ return False
215
+ if is_fragment_only_uri(s) or is_scheme_relative_uri(s) or is_absolute_uri(s):
216
+ return False
217
+ # At this point treat anything else as relative: './x', '../x', 'x', 'x/y', '/x'
218
+ return True