├── .github
├── FUNDING.yml
└── workflows
│ └── test.yml
├── .gitignore
├── API.md
├── FUNDING.yml
├── LICENSE
├── README.md
├── VERSION
├── deps.edn
├── dev
├── deps.edn
└── test_runner.clj
├── src
└── s_exp
│ ├── pact.clj
│ └── pact
│ └── impl.clj
└── test
└── s_exp
└── pact_test.clj
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: mpenet
2 |
3 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Test
2 |
3 | on:
4 | push:
5 | paths:
6 | - src/**
7 | - test/**
8 | - deps.edn
9 |
10 | jobs:
11 |
12 | test:
13 |
14 | runs-on: ubuntu-latest
15 |
16 | container:
17 | image: clojure:openjdk-17-tools-deps-slim-bullseye
18 | volumes:
19 | - ${{ github.workspace }}:${{ github.workspace }}
20 | env:
21 | ARTIFACTS_USERNAME: ${{ secrets.ARTIFACTS_USERNAME }}
22 | ARTIFACTS_PASSWORD: ${{ secrets.ARTIFACTS_PASSWORD }}
23 |
24 | steps:
25 | - name: Check out Git repository
26 | uses: actions/checkout@v3
27 |
28 | # - name: Cache mvn/git deps
29 | # uses: actions/cache@v3
30 | # id: cache-deps
31 | # with:
32 | # path: |
33 | # /root/.m2
34 | # /root/.gitlibs
35 | # key: ${{ runner.os }}-${{ hashFiles('**/deps.edn') }}
36 |
37 | - name: Test
38 | id: test
39 | run: clj -X:test
40 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | .cpcache
3 | **/.clj-kondo/.cache
4 | **/.lsp
5 | **/.DS_Store
--------------------------------------------------------------------------------
/API.md:
--------------------------------------------------------------------------------
1 | # Table of contents
2 | - [`s-exp.pact`](#s-exp.pact)
3 | - [`assoc-meta`](#s-exp.pact/assoc-meta) - Assoc k
->x
on metadata for spec
.
4 | - [`default-opts`](#s-exp.pact/default-opts)
5 | - [`find-description`](#s-exp.pact/find-description) - Find first description
value in spec hierarchy for spec.
6 | - [`find-format`](#s-exp.pact/find-format) - Find first format
value in spec hierarchy for spec.
7 | - [`find-id`](#s-exp.pact/find-id) - Find first $id
value in spec hierarchy for spec.
8 | - [`find-pattern`](#s-exp.pact/find-pattern) - Find first pattern
value in spec hierarchy for spec.
9 | - [`find-schema`](#s-exp.pact/find-schema) - Find first schema
value in spec hierarchy for spec.
10 | - [`find-title`](#s-exp.pact/find-title) - Find first title
value in spec hierarchy for spec.
11 | - [`json-schema`](#s-exp.pact/json-schema) - Generate json-schema for spec
.
12 | - [`meta`](#s-exp.pact/meta) - Returns spec
metadata.
13 | - [`register-form!`](#s-exp.pact/register-form!) - Registers a form
for generation.
14 | - [`register-ident!`](#s-exp.pact/register-ident!) - Registers an ident
for generation.
15 | - [`register-pred!`](#s-exp.pact/register-pred!) - Sets conformer
and schema-fn
for predicate parser.
16 | - [`registry`](#s-exp.pact/registry) - Returns registry.
17 | - [`registry-ref`](#s-exp.pact/registry-ref)
18 | - [`vary-meta`](#s-exp.pact/vary-meta) - Like clojure.core/vary-meta but on spec
k` metadata.
19 | - [`with-description`](#s-exp.pact/with-description) - Add description
to spec.
20 | - [`with-format`](#s-exp.pact/with-format) - Add format
to spec.
21 | - [`with-id`](#s-exp.pact/with-id) - Adds $id to spec.
22 | - [`with-meta`](#s-exp.pact/with-meta) - Sets metadata for spec
.
23 | - [`with-pattern`](#s-exp.pact/with-pattern) - Add pattern
to spec.
24 | - [`with-title`](#s-exp.pact/with-title) - Add title
to spec.
25 |
26 | -----
27 | # s-exp.pact
28 |
29 |
30 |
31 |
32 |
33 |
34 | ## `assoc-meta`
35 | ``` clojure
36 |
37 | (assoc-meta spec k x)
38 | ```
39 |
40 | Assoc `k`->`x` on metadata for `spec`
41 |
Source
42 |
43 | ## `default-opts`
44 |
45 |
46 |
47 | Source
48 |
49 | ## `find-description`
50 |
51 |
52 |
53 |
54 | Find first `description` value in spec hierarchy for spec
55 | Source
56 |
57 | ## `find-format`
58 |
59 |
60 |
61 |
62 | Find first `format` value in spec hierarchy for spec
63 | Source
64 |
65 | ## `find-id`
66 |
67 |
68 |
69 |
70 | Find first `$id` value in spec hierarchy for spec
71 | Source
72 |
73 | ## `find-pattern`
74 |
75 |
76 |
77 |
78 | Find first `pattern` value in spec hierarchy for spec
79 | Source
80 |
81 | ## `find-schema`
82 |
83 |
84 |
85 |
86 | Find first `schema` value in spec hierarchy for spec
87 | Source
88 |
89 | ## `find-title`
90 |
91 |
92 |
93 |
94 | Find first `title` value in spec hierarchy for spec
95 | Source
96 |
97 | ## `json-schema`
98 | ``` clojure
99 |
100 | (json-schema k & {:as opts, :keys [property-key-fn strict gen-only-first-and-arg unknown-spec-default]})
101 | ```
102 |
103 | Generate json-schema for `spec`.
104 | `opts` support:
105 |
106 | * `property-key-fn` - function that will convert the spec keys to json-schema
107 | keys - defaults to `name`
108 |
109 | * `strict` - whether to throw or not upon encountering unknown values for
110 | conversion - defaults to `true`
111 |
112 | * `gen-only-first-and-arg` - whether to only attempt generate the first
113 | predicate of `s/and` - defaults to `false`
114 |
115 | * `unknown-spec-default` - value to be used for unknown values for conversion
116 | - defaults to `nil`
117 | Source
118 |
119 | ## `meta`
120 | ``` clojure
121 |
122 | (meta spec)
123 | ```
124 |
125 | Returns `spec` metadata
126 | Source
127 |
128 | ## `register-form!`
129 | ``` clojure
130 |
131 | (register-form! form f)
132 | ```
133 |
134 | Registers a `form` for generation. Upon encountering that form (by matching its
135 | against first element or sequential symbolic spec values), [`json-schema`](#s-exp.pact/json-schema) will
136 | then call `f` against its arguments for generation
137 | Source
138 |
139 | ## `register-ident!`
140 | ``` clojure
141 |
142 | (register-ident! ident x)
143 | ```
144 |
145 | Registers an `ident` for generation. Upon encountering a qualified
146 | symbol/keyword matching an `ident` in the registry it will return `x` as
147 | generated value
148 | Source
149 |
150 | ## `register-pred!`
151 | ``` clojure
152 |
153 | (register-pred! k schema-fn _opts)
154 | (register-pred! k schema-fn)
155 | ```
156 |
157 | Sets `conformer` and `schema-fn` for predicate parser.
158 | If a conformer matches, the bindings we get from the s/conform result will be
159 | passed to `schema-fn` in order to generate an appropriate json-schema value
160 | for the predicate.
161 | Source
162 |
163 | ## `registry`
164 | ``` clojure
165 |
166 | (registry)
167 | (registry k)
168 | ```
169 |
170 | Returns registry
171 | Source
172 |
173 | ## `registry-ref`
174 |
175 |
176 |
177 | Source
178 |
179 | ## `vary-meta`
180 | ``` clojure
181 |
182 | (vary-meta k f & args)
183 | ```
184 |
185 | Like `clojure.core/vary-meta but on spec `k` metadata
186 | Source
187 |
188 | ## `with-description`
189 | ``` clojure
190 |
191 | (with-description k description)
192 | ```
193 |
194 | Add `description` to spec
195 | Source
196 |
197 | ## `with-format`
198 | ``` clojure
199 |
200 | (with-format k fmt)
201 | ```
202 |
203 | Add `format` to spec.
204 | See https://json-schema.org/understanding-json-schema/reference/string#built-in-formats
205 | Source
206 |
207 | ## `with-id`
208 | ``` clojure
209 |
210 | (with-id spec id)
211 | ```
212 |
213 | Adds $id to spec
214 | Source
215 |
216 | ## `with-meta`
217 | ``` clojure
218 |
219 | (with-meta spec x)
220 | ```
221 |
222 | Sets metadata for `spec`
223 | Source
224 |
225 | ## `with-pattern`
226 | ``` clojure
227 |
228 | (with-pattern k p)
229 | ```
230 |
231 | Add `pattern` to spec
232 | Source
233 |
234 | ## `with-title`
235 | ``` clojure
236 |
237 | (with-title k title)
238 | ```
239 |
240 | Add `title` to spec
241 | Source
242 |
--------------------------------------------------------------------------------
/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: mpenet
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (“AGREEMENT”). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT’S ACCEPTANCE OF THIS AGREEMENT.
2 |
3 | 1. DEFINITIONS
4 |
5 | “Contribution” means:
6 |
7 | a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
8 |
9 | b) in the case of each subsequent Contributor:
10 |
11 | i) changes to the Program, and
12 |
13 | ii) additions to the Program;
14 |
15 | where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution ‘originates’ from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor’s behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.
16 |
17 | “Contributor” means any person or entity that distributes the Program.
18 |
19 | “Licensed Patents ” mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
20 |
21 | “Program” means the Contributions distributed in accordance with this Agreement.
22 |
23 | “Recipient” means anyone who receives the Program under this Agreement, including all Contributors.
24 |
25 | 2. GRANT OF RIGHTS
26 |
27 | a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.
28 |
29 | b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
30 |
31 | c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient’s responsibility to acquire that license before distributing the Program.
32 |
33 | d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
34 |
35 | 3. REQUIREMENTS
36 |
37 | A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
38 |
39 | a) it complies with the terms and conditions of this Agreement; and
40 |
41 | b) its license agreement:
42 |
43 | i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
44 |
45 | ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
46 |
47 | iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
48 |
49 | iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.
50 |
51 | When the Program is made available in source code form:
52 |
53 | a) it must be made available under this Agreement; and
54 |
55 | b) a copy of this Agreement must be included with each copy of the Program.
56 |
57 | Contributors may not remove or alter any copyright notices contained within the Program.
58 |
59 | Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.
60 |
61 | 4. COMMERCIAL DISTRIBUTION
62 |
63 | Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor (“Commercial Contributor”) hereby agrees to defend and indemnify every other Contributor (“Indemnified Contributor”) against any losses, damages and costs (collectively “Losses”) arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
64 |
65 | For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor’s responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
66 |
67 | 5. NO WARRANTY
68 |
69 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
70 |
71 | 6. DISCLAIMER OF LIABILITY
72 |
73 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
74 |
75 | 7. GENERAL
76 |
77 | If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
78 |
79 | If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient’s patent(s), then such Recipient’s rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
80 |
81 | All Recipient’s rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient’s rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient’s obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
82 |
83 | Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
84 |
85 | This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # pact
2 |
3 |
4 |
5 | Tiny library allowing you to generate json-schema from clojure specs.
6 |
7 | # Rationale
8 |
9 | Specs allow us to define contracts, why not re-using these to **generate
10 | json-schema**. Spec forms are just "data", should be easy right?
11 |
12 | Well, there are a few challenges:
13 | * specs can be defined as arbitrary predicates
14 | * specs can also be aliases to other specs
15 | * specs can be the result of composition of other specs via s/and s/merge
16 | s/multi-spec etc
17 | * specs can be *parameterized* (kind of, think `s/coll-of`, `s/int-in` & co)
18 | * specs have no metadata, that makes adding features json-schema supports but
19 | spec doesn't a bit complicated
20 |
21 | How `pact` attempts to handle these:
22 |
23 | * **Spec forms/composition of specs**: schemas can be inferred for all
24 | clojure.spec forms (s/and & co). In the cases where we cannot infer the schema
25 | we provide ways for you to specify what to generate.
26 |
27 | * **Spec alias chains**: we ensure that alias chains are understood and walk them
28 | up trying to find the first spec key that will allow json-schema
29 | generation. For instance if you have a spec ::foo that is an alias to ::bar
30 | that is itself an alias to ::baz that is a `string?`, trying to generate
31 | json-schema for ::foo will check them in order until it finds enough
32 | information to do so (from ::baz definition).
33 |
34 | * **Metadata**: we have a few helpers that allow you to specify/override
35 | `title`, `description`, `format`, `pattern`, `$id` on top of existing specs,
36 | that will later show up in the json-schema for these. They also understand
37 | spec aliases and pick up the first walking back the spec alias chain.
38 |
39 | * **Register new generators**, either globally or on per-call basis.
40 |
41 | * **Arbitrary predicates**: Predicate forms parsing is done using spec , with
42 | conform. We destructure predicate forms via conform, so that you grab any
43 | value from them (anything in the body of the function really) in order to then
44 | generate the appropriate openapi data via a supplied function that take these
45 | bindings as argument. `pact` comes with a number of useful predicate parsers
46 | that allow to generate correct schemas for common cases (numercic
47 | comparaisons, length bounds and so on). This is really an escape hatch,
48 | generally you don't have to go that far and can get by registering generators
49 | for `idents` or `forms` (more on this later).
50 |
51 | By default pact is **strict**, it will throw at generation time if it cannot
52 | infer the json-schema for a spec, but it will allow you to specify the missing
53 | bits.
54 |
55 | It can also function in non strict mode where unknowns generate whatever you
56 | specify by default, or just skip what it can't infer in some cases.
57 |
58 | You can also tune the interpretation of some forms to be less strict, for
59 | instance having only the first component of a `s/and` to be taken into account
60 | and a few others like this. But by default we try to cover the full spec.
61 |
62 | We **do not** provide an openapi generator, if you want to generate openapi
63 | using `pact` it's very easy to do so, there's no need for an extra lib layer to
64 | do so. That also gives you more control over the way you manage $refs, paths and
65 | other openapi details.
66 |
67 | ## Examples
68 |
69 | ```clojure
70 |
71 | (require '[s-exp.pact :as p])
72 | (require '[clojure.spec.alpha :as s])
73 |
74 | ;; simple specs
75 | (p/json-schema `(s/and number? int?))
76 | => {:allOf [{:type "number"} {:type "integer" :format "int64"}]}
77 |
78 | (p/json-schema `(s/or number? int?))
79 | => {:anyOf [{:type "number"} {:type "integer" :format "int64"}]}
80 |
81 | (p/json-schema `(s/coll-of string? :max-count 3))
82 | => {:type "array", :items {:type "string"} :maxItems 3}
83 |
84 | (s/def ::foo string?)
85 | (s/def ::bar keyword?)
86 | (s/def ::baz int?)
87 |
88 | ;; maps
89 | (s/def ::thing (s/keys :req-un [::foo ::bar] :opt-un [::baz]))
90 | (p/json-schema ::thing)
91 | => {:type "object",
92 | :properties
93 | {"foo" {:type "string"},
94 | "bar" {:type "string"},
95 | "baz" {:type "integer", :format "int64"}},
96 | :required ["foo" "bar"]}
97 |
98 | ;; merged maps
99 | (p/json-schema `(s/merge (s/keys :req-un [::foo]) (s/keys :req-un [::bar]) (s/keys :opt-un [::baz])))
100 | => {:allOf
101 | [{:type "object",
102 | :properties {"foo" {:type "string"}},
103 | :required ["foo"]}
104 | {:type "object",
105 | :properties {"bar" {:type "string"}},
106 | :required ["bar"]}
107 | {:type "object",
108 | :properties {"baz" {:type "integer", :format "int64"}}}]}
109 |
110 |
111 | ;; multi-specs
112 | (s/def ::tag #{:a :b :c :d})
113 | (s/def ::example-key keyword?)
114 | (s/def ::different-key keyword?)
115 | (defmulti tagmm :tag)
116 | (defmethod tagmm :a [_] (s/keys :req-un [::tag ::example-key]))
117 | (defmethod tagmm :default [_] (s/keys :req-un [::tag ::different-key]))
118 | (s/def ::ms (s/multi-spec tagmm :tag))
119 |
120 | (p/json-schema ::ms)
121 | => {:anyOf
122 | [{:type "object",
123 | :properties {"tag" {:enum #{:c :b :d :a}}, "different-key" {:type "string"}},
124 | :required ["tag" "different-key"]}
125 | {:type "object",
126 | :properties {"tag" {:enum #{:c :b :d :a}}, "example-key" {:type "string"}},
127 | :required ["tag" "example-key"]}]}
128 |
129 | ;; arbitrary predicates
130 |
131 | (s/def ::p (s/and number? (fn [x] (>= x 10))))
132 | (p/json-schema ::p)
133 | => {:allOf [{:type "number"} {:minimum 10, :type "number"}]}
134 |
135 |
136 | ;; metadata
137 |
138 | (-> (s/def ::animal string?)
139 | (p/with-description "An animal")
140 | (p/with-title "Animal")
141 | (p/with-pattern "[a-zA-Z]")
142 | (p/json-schema))
143 |
144 | => {:type "string", :title "Animal", :description "An animal", :pattern "[a-zA-Z]"}
145 |
146 | ;; overriding output, we make string? return something different
147 | (p/json-schema ::animal {:idents {`string? {:type "string" :foo "bar"}}})
148 | =>
149 | {:type "string",
150 | :foo "bar",
151 | :title "Animal",
152 | :description "An animal",
153 | :pattern "[a-zA-Z]"}
154 |
155 | ;; also works for parameterized forms
156 | (p/json-schema `(s/coll-of any?) {:forms {`s/coll-of (fn [_coll-of-arg _opts] {:foo :bar})}})
157 | => {:foo :bar}
158 |
159 | ;; it understands alias chains
160 | (s/def ::foo string?)
161 | (s/def ::bar ::foo)
162 | (s/def ::baz ::bar)
163 | (p/json-schema ::baz)
164 | => {:type "string"}
165 |
166 | ;; also inherits all properties from chains
167 | (p/with-pattern ::bar "[a-zA-Z]")
168 | (p/json-schema ::baz)
169 | {:type "string", :pattern "[a-zA-Z]"}
170 |
171 | ;; and allow overrides at any level
172 | (with-pattern ::baz "[a-z]")
173 | (p/json-schema ::baz)
174 | => {:type "string", :pattern "[a-z]"}
175 | ```
176 |
177 | ## Extensions
178 |
179 | You can extend the way pact generates schemas via `json-schema` options or by registering schema generators
180 |
181 | * `s-exp.pact/register-ident!`: registers a new generator for an `ident` (spec key or symbol)
182 |
183 | ```clj
184 | (register-ident! `int? {:type "integer" :format "int64"})
185 | ```
186 |
187 | * `s-exp.pact/register-form!`: registers a generator for a `form`, ex: `coll-of`
188 | parameterized spec forms (think, `int-in`, `nilable`, `coll-of` and so on)
189 | ex: how nilable is implemented
190 |
191 | ```clj
192 | (p/register-form!
193 | `s/nilable
194 | (fn [[form] opts]
195 | {:anyOf [{:type "null"}
196 | (json-schema* form opts)]}))
197 | ```
198 |
199 | * `s-exp.pact/register-pred!`: allows to set predicate conformer & schema
200 | generator for **arbitrary predicates** found in spec forms, ex: `(s/and string? (fn [s] (str/includes? s something)))`
201 |
202 | It takes 2 arguments a spec key, that would be used to potentially conform
203 | (pattern match) a spec form onto bindings to use for a json-schema, and a
204 | function that will receive these arguments and return json-schema data
205 | matching the form.
206 |
207 | There are also matching options you can pass to the `json-schema` function to
208 | have overrides be applied per call (without being registered globally):
209 |
210 | * `:idents` - map of idents -> values
211 | * `:forms` - map of forms -> function of form args+opts
212 | * `:preds` - map of pred conformer spec key -> generator
213 | function which will take the conformed values and options
214 |
215 | ## API
216 |
217 | see [API.md](API.md)
218 |
219 | ## Tests
220 |
221 | `clj -X:test`
222 |
223 | # Installation
224 |
225 | [](https://clojars.org/com.s-exp/pact)
226 |
227 | ## License
228 |
229 | Copyright © 2024 Max Penet
230 |
231 | Distributed under the Eclipse Public License version 1.0.
232 |
--------------------------------------------------------------------------------
/VERSION:
--------------------------------------------------------------------------------
1 | 1.0.9-SNAPSHOT
--------------------------------------------------------------------------------
/deps.edn:
--------------------------------------------------------------------------------
1 | {:exoscale.project/lib com.s-exp/pact
2 | :exoscale.project/version-file "VERSION"
3 | :exoscale.project/deploy? true
4 | :slipset.deps-deploy/exec-args {:installer :remote
5 | :sign-releases? false
6 | :repository "clojars"}
7 | :exoscale.project/pom-data
8 | [[:licenses
9 | [:license
10 | [:name "Eclipse Public License version 1.0"]
11 | [:url "https://opensource.org/license/epl-1-0/"]
12 | [:distribution "repo"]]]]
13 |
14 | :deps {org.clojure/clojure {:mvn/version "1.12.0-alpha5"}
15 | exoscale/ex {:mvn/version "0.4.1"}}
16 |
17 | :aliases
18 | {:project {:deps {io.github.exoscale/tools.project {:git/sha "99e6b7aaccd9b97079341625c807b9fa0352e36d"}}
19 | :ns-default exoscale.tools.project
20 | :jvm-opts ["-Dclojure.main.report=stderr"]}
21 | :test
22 | {:extra-deps {sks/test-runner {:local/root "dev"}
23 | org.clojure/test.check {:mvn/version "1.1.1"}}
24 | :jvm-opts ["-Dclojure.main.report=stderr"]
25 |
26 | :exec-fn test-runner/run
27 | :extra-paths ["test"]}
28 |
29 | :quickdoc
30 | {:deps {org.babashka/cli {:mvn/version "0.4.36"}
31 | io.github.borkdude/quickdoc
32 | {:deps/root "jvm"
33 | :git/sha "7c8bef54eda28367193ec433af01bb940114f012"}}
34 | :exec-fn quickdoc.api/quickdoc
35 | :exec-args {:github/repo "https://github.com/mpenet/pact"
36 | :git/branch "master"
37 | :source-paths ["src/s_exp/pact.clj"]}}}}
38 |
--------------------------------------------------------------------------------
/dev/deps.edn:
--------------------------------------------------------------------------------
1 | {:paths ["."]
2 | :deps {eftest/eftest {:mvn/version "0.6.0"}
3 | org.clojure/test.check {:mvn/version "1.1.1"}}}
4 |
--------------------------------------------------------------------------------
/dev/test_runner.clj:
--------------------------------------------------------------------------------
1 | (ns test-runner
2 | (:gen-class)
3 | (:require [clojure.test]
4 | eftest.report.pretty
5 | [eftest.runner :as ef]))
6 |
7 | (def default-options
8 | {:dir "test"
9 | :selector (constantly true)
10 | :capture-output? false
11 | :fail-fast? false
12 | :multithread? false
13 | :add-x-spec false
14 | :reporters [eftest.report.pretty/report]})
15 |
16 | (defn sort-vars
17 | [vars]
18 | (sort-by (fn [var]
19 | (let [{:keys [ns line]} (meta var)]
20 | [(str ns) line]))
21 | vars))
22 |
23 | (defn- ret->exit-code
24 | [{:as _ret :keys [error fail]}]
25 | (System/exit
26 | (cond
27 | (and (pos? fail) (pos? error)) 30
28 | (pos? fail) 20
29 | (pos? error) 10
30 | :else 0)))
31 |
32 | (defn combined-reporter
33 | "Combines the reporters by running first one directly,
34 | and others with clojure.test/*report-counters* bound to nil."
35 | [[report & rst]]
36 | (fn [m]
37 | (report m)
38 | (doseq [report rst]
39 | (binding [clojure.test/*report-counters* nil]
40 | (report m)))))
41 |
42 | (defn find-tests
43 | [{:keys [selector dir]}]
44 | (->> (ef/find-tests dir)
45 | (filter #(-> % meta selector))
46 | sort-vars))
47 |
48 | (defn setup-options
49 | [opts]
50 | (let [{:as opts :keys [reporters]} (merge default-options opts)]
51 | (cond-> opts
52 | (seq reporters)
53 | (assoc :report (combined-reporter reporters)))))
54 |
55 | (defn run
56 | [options]
57 | (let [options (setup-options options)]
58 | (-> (find-tests options)
59 | (ef/run-tests options)
60 | ret->exit-code)))
61 |
62 | (defn run-unit
63 | [options]
64 | (run (assoc options
65 | :selector
66 | (complement :integration))))
67 |
68 | (defn run-integation
69 | [options]
70 | (run (assoc options :selector :integration)))
71 |
--------------------------------------------------------------------------------
/src/s_exp/pact.clj:
--------------------------------------------------------------------------------
1 | (ns s-exp.pact
2 | (:refer-clojure :exclude [derive vary-meta meta with-meta])
3 | (:require
4 | [clojure.spec.alpha :as s]
5 | [exoscale.ex :as ex]
6 | [s-exp.pact.impl :as impl]))
7 |
8 | (s/def :s-exp.pact/options
9 | (s/keys :opt-un [:s-exp.pact.option/property-key-fn
10 | :s-exp.pact.option/gen-only-first-and-arg
11 | :s-exp.pact.option/strict
12 | :s-exp.pact.option/unknown-spec-default]))
13 |
14 | (s/def :s-exp.pact.option/property-key-fn ifn?)
15 | (s/def :s-exp.pact.option/gen-only-first-and-arg boolean?)
16 | (s/def :s-exp.pact.option/strict boolean?)
17 | (s/def :s-exp.pact.option/unknown-spec-default any?)
18 |
19 | (def default-opts
20 | {:property-key-fn name
21 | :gen-only-first-and-arg false
22 | :strict true ; will throw on unknown conversion
23 | :unknown-spec-default nil})
24 |
25 | (defonce registry-ref
26 | (atom #:s-exp.pact.json-schema{:meta {}
27 | :idents {}
28 | :forms {}
29 | :preds {}}))
30 |
31 | (s/def :s-exp.pact.json-schema/schema map?)
32 | (s/def :s-exp.pact.json-schema/forms (s/map-of symbol? ifn?))
33 | (s/def :s-exp.pact.json-schema/idents (s/map-of qualified-ident? :s-exp.pact.json-schema/schema))
34 | (s/def :s-exp.pact.json-schema/preds (s/map-of qualified-keyword? ifn?))
35 |
36 | (defn registry
37 | "Returns registry"
38 | ([]
39 | @registry-ref)
40 | ([k]
41 | (get (registry) k)))
42 |
43 | (defn register-form!
44 | "Registers a `form` for generation. Upon encountering that form (by matching its
45 | against first element or sequential symbolic spec values), `json-schema` will
46 | then call `f` against its arguments for generation. Returns form passed as argument"
47 | [form f]
48 | (swap! registry-ref update :s-exp.pact.json-schema/forms
49 | assoc form f)
50 | form)
51 |
52 | (defn register-ident!
53 | "Registers an `ident` for generation. Upon encountering a qualified
54 | symbol/keyword matching an `ident` in the registry it will return `x` as
55 | generated value. Returns the `ident` passed as argument"
56 | [ident x]
57 | (swap! registry-ref update :s-exp.pact.json-schema/idents
58 | assoc ident x)
59 | ident)
60 |
61 | (def find-id
62 | "Find first `id` value in spec hierarchy for spec"
63 | (impl/find-key :id))
64 |
65 | (def find-title
66 | "Find first `title` value in spec hierarchy for spec"
67 | (impl/find-key :title))
68 |
69 | (def find-description
70 | "Find first `description` value in spec hierarchy for spec"
71 | (impl/find-key :description))
72 |
73 | (def find-format
74 | "Find first `format` value in spec hierarchy for spec"
75 | (impl/find-key :format))
76 |
77 | (def find-pattern
78 | "Find first `pattern` value in spec hierarchy for spec"
79 | (impl/find-key :pattern))
80 |
81 | (def find-schema
82 | "Find first `schema` value in spec hierarchy for spec"
83 | impl/find-schema)
84 |
85 | (defn vary-meta
86 | "Like `clojure.core/vary-meta but on spec `k` metadata"
87 | [k f & args]
88 | (swap! registry-ref
89 | update-in
90 | [:s-exp.pact.json-schema/meta k]
91 | #(apply f % args))
92 | k)
93 |
94 | (defn with-meta
95 | "Sets metadata for `spec` "
96 | [spec x]
97 | (vary-meta spec (constantly x)))
98 |
99 | (defn meta
100 | "Returns `spec` metadata"
101 | [spec]
102 | (get-in @registry-ref [:s-exp.pact.json-schema/meta spec]))
103 |
104 | (defn assoc-meta
105 | "Assoc `k`->`x` on metadata for `spec` "
106 | [spec k x]
107 | (vary-meta spec assoc k x))
108 |
109 | (defn with-id
110 | "Adds $id to spec"
111 | [spec id]
112 | (assoc-meta spec :id id))
113 |
114 | (defn with-title
115 | "Add `title` to spec"
116 | [k title]
117 | (assoc-meta k :title title))
118 |
119 | (defn with-description
120 | "Add `description` to spec"
121 | [k description]
122 | (assoc-meta k :description description))
123 |
124 | (defn with-format
125 | "Add `format` to spec.
126 | See https://json-schema.org/understanding-json-schema/reference/string#built-in-formats"
127 | [k fmt]
128 | (assoc-meta k :format fmt))
129 |
130 | (defn with-pattern
131 | "Add `pattern` to spec"
132 | [k p]
133 | (assoc-meta k :pattern p))
134 |
135 | (defn json-schema
136 | "Generate json-schema for `spec`.
137 | `opts` support:
138 |
139 | * `property-key-fn` - function that will convert the spec keys to json-schema
140 | keys - defaults to `name`
141 |
142 | * `strict` - whether to throw or not upon encountering unknown values for
143 | conversion - defaults to `true`
144 |
145 | * `gen-only-first-and-arg` - whether to only attempt generate the first
146 | predicate of `s/and` - defaults to `false`
147 |
148 | * `unknown-spec-default` - value to be used for unknown values for conversion
149 | - defaults to `nil`"
150 | [k & {:as opts
151 | :keys [property-key-fn strict gen-only-first-and-arg
152 | unknown-spec-default add-x-spec]}]
153 | (let [opts (into default-opts opts)
154 | spec-chain (impl/spec-chain k)
155 | registry-val (registry)
156 | ret (or (find-schema registry-val
157 | spec-chain
158 | opts)
159 | (when (:strict opts)
160 | (throw (ex-info "Unknown val to json-schema generator"
161 | {:exoscale.ex/type :s-exp.pact/unknown-val
162 | :spec k})))
163 | (:unknown-spec-default opts))
164 | desc (find-description registry-val spec-chain)
165 | fmt (find-format registry-val spec-chain)
166 | pattern (find-pattern registry-val spec-chain)
167 | id (find-id registry-val spec-chain)
168 | title (find-title registry-val spec-chain)]
169 | (cond-> ret
170 | (and (:add-x-spec opts) (qualified-keyword? k))
171 | (assoc :x-spec (format "%s/%s" (namespace k) (name k)))
172 | id
173 | (assoc :id id)
174 | title
175 | (assoc :title title)
176 | desc
177 | (assoc :description desc)
178 | fmt
179 | (assoc :format fmt)
180 | pattern
181 | (assoc :pattern pattern))))
182 |
183 | (ex/derive :s-exp.pact/unknown-val :exoscale.ex/invalid)
184 |
185 | ;; idents
186 |
187 | (register-ident! `nil? {:type "null"})
188 | (register-ident! `string? (impl/string-schema))
189 | (register-ident! `keyword? (impl/string-schema))
190 | (register-ident! `qualified-keyword? (impl/string-schema))
191 | (register-ident! `simple-keyword? (impl/string-schema))
192 | (register-ident! `ident? (impl/string-schema))
193 | (register-ident! `qualified-ident? (impl/string-schema))
194 | (register-ident! `simple-ident? (impl/string-schema))
195 | (register-ident! `symbol? (impl/string-schema))
196 | (register-ident! `qualified-symbol? (impl/string-schema))
197 | (register-ident! `simple-symbol? (impl/string-schema))
198 | (register-ident! `uuid? (impl/string-schema :format "uuid"))
199 | (register-ident! `uri? (impl/string-schema :format "uri"))
200 | (register-ident! `boolean? {:type "boolean"})
201 | (register-ident! `true? {:const true})
202 | (register-ident! `false? {:const false})
203 | (register-ident! `inst? (impl/string-schema :format "date-time"))
204 | (register-ident! `any? (impl/object-schema))
205 | (register-ident! `some? (impl/object-schema))
206 | (register-ident! `map? (impl/object-schema))
207 | (register-ident! `number? (impl/number-schema))
208 | (register-ident! `int? (impl/int-schema :format "int64"))
209 | (register-ident! `pos? (impl/int-schema :format "int64" :minimum 0))
210 | (register-ident! `integer? (impl/int-schema :format "int64"))
211 | (register-ident! `nat-int? (impl/int-schema :format "int64" :minimum 0))
212 | (register-ident! `pos-int? (impl/int-schema :format "int64" :minimum 1))
213 | (register-ident! `neg-int? (impl/int-schema :format "int64" :maximum -1))
214 | (register-ident! `neg? (impl/int-schema :format "int64" :maximum -1))
215 | (register-ident! `float? (impl/number-schema :format "float"))
216 | (register-ident! `double? (impl/number-schema :format "double"))
217 | (register-ident! `decimal? (impl/number-schema :format "double"))
218 | (register-ident! `rational? (impl/number-schema :format "double"))
219 | (register-ident! `zero? {:const 0})
220 | (register-ident! `coll? (impl/array-schema))
221 | (register-ident! `empty? (impl/array-schema :maxItems 0 :minItems 0))
222 | (register-ident! `vector? (impl/array-schema))
223 | (register-ident! `list? (impl/array-schema))
224 | (register-ident! `set? (impl/array-schema :uniqueItems true))
225 | (register-ident! `sequential? (impl/array-schema))
226 |
227 | ;;; forms
228 |
229 | (defn- every-form-gen*
230 | [[spec & {:as spec-opts :keys [max-count min-count length kind]}] opts]
231 | (let [distinct (or (:distinct spec-opts) (= kind `set?))]
232 | (cond-> (impl/array-schema :items (json-schema spec opts))
233 | length
234 | (assoc :minItems length
235 | :maxItems length)
236 | max-count
237 | (assoc :maxItems max-count)
238 | min-count
239 | (assoc :minItems min-count)
240 | distinct
241 | (assoc :uniqueItems true))))
242 |
243 | (register-form! `s/every every-form-gen*)
244 | (register-form! `s/coll-of every-form-gen*)
245 |
246 | (register-form! `s/cat
247 | (fn [pairs opts]
248 | (impl/array-schema
249 | :items
250 | {:anyOf
251 | (map (fn [[_k spec]]
252 | (json-schema spec opts))
253 | (partition-all 2 pairs))})))
254 |
255 | (register-form! `s/*
256 | (fn [spec opts]
257 | (impl/array-schema
258 | :items (map (fn [spec] (json-schema spec opts)) spec))))
259 |
260 | (register-form! `s/+
261 | (fn [more opts]
262 | (impl/array-schema
263 | :items (map (fn [spec] (json-schema spec opts)) more)
264 | :minItems 1)))
265 |
266 | (register-form! `s/?
267 | (fn [more opts]
268 | (impl/array-schema
269 | :items (map (fn [spec] (json-schema spec opts)) more)
270 | :minItems 0)))
271 |
272 | (register-form!
273 | `s/map-of
274 | (fn [[_ val-spec] opts]
275 | {:type "object"
276 | :patternProperties {".*" (json-schema val-spec opts)}}))
277 |
278 | (register-form!
279 | `s/tuple
280 | (fn [[_ & specs] opts]
281 | (impl/array-schema
282 | :items (map (fn [spec] (json-schema spec opts))
283 | specs))))
284 |
285 | (defn- parse-s-keys
286 | [form]
287 | (-> (apply hash-map form)
288 | (update-vals #(->> %
289 | flatten
290 | ;; hackish, but will do for now
291 | (remove #{`or `and})
292 | (distinct)))))
293 |
294 | (defn- keys->properties [pk {:as opts :keys [property-key-fn]}]
295 | (let [specs (eduction
296 | (mapcat (comp val))
297 | (select-keys pk
298 | [:req-un :req :opt :opt-un]))]
299 | (into {}
300 | (map (fn [k]
301 | [(property-key-fn k) (json-schema k opts)]))
302 | specs)))
303 |
304 | (register-form!
305 | `s/keys
306 | (fn [form {:as opts :keys [property-key-fn]}]
307 | (let [keys' (parse-s-keys form)
308 | req-keys (not-empty
309 | (select-keys keys'
310 | [:req-un :req]))]
311 | (cond-> {:type "object"
312 | :properties (keys->properties keys' opts)}
313 | req-keys
314 | (assoc :required (into []
315 | (comp (mapcat val)
316 | (map property-key-fn))
317 | (select-keys keys'
318 | [:req-un :req])))))))
319 |
320 | (register-form!
321 | `s/nilable
322 | (fn [[form] opts]
323 | {:anyOf [{:type "null"}
324 | (json-schema form opts)]}))
325 |
326 | (register-form!
327 | `s/multi-spec
328 | (fn [[mm tag-key] opts]
329 | (let [f (resolve mm)]
330 | {:anyOf (into []
331 | (comp
332 | (map (fn extract-spec [[dispatch-val _spec]]
333 | (impl/spec-root (s/form (f {tag-key dispatch-val})))))
334 | (map (fn get-json-schema [k]
335 | (json-schema k opts))))
336 | (methods @f))})))
337 |
338 | (register-form!
339 | `enum-of
340 | (fn [values _opts]
341 | {:enum values}))
342 |
343 | (register-form!
344 | `s/int-in
345 | (fn [[min max] _opts]
346 | {:type "integer"
347 | :minimum min
348 | :maximum (dec max)}))
349 |
350 | (register-form!
351 | `s/and
352 | (fn [[& forms] {:as opts :keys [gen-only-first-and-arg]}]
353 | {:allOf (into []
354 | (keep #(json-schema % opts))
355 | (if gen-only-first-and-arg
356 | [(first forms)]
357 | forms))}))
358 |
359 | (register-form!
360 | `s/merge
361 | (fn [[& forms] opts]
362 | {:allOf (into []
363 | (map #(json-schema % opts))
364 | forms)}))
365 |
366 | (defn- or-schema
367 | [[& forms] opts]
368 | {:anyOf (into []
369 | (comp
370 | (partition-all 2)
371 | (map #(json-schema (second %) opts)))
372 | forms)})
373 |
374 | (register-form! `s/or or-schema)
375 | (register-form! `s/alt or-schema)
376 |
377 | ;;
378 |
379 | (defn register-pred!
380 | "Sets `conformer` and `schema-fn` for predicate parser.
381 | If a conformer matches, the bindings we get from the s/conform result will be
382 | passed to `schema-fn` in order to generate an appropriate json-schema value
383 | for the predicate."
384 | ([k schema-fn _opts]
385 | (swap! registry-ref
386 | (fn [registry-val]
387 | (assoc-in registry-val
388 | [:s-exp.pact.json-schema/preds k]
389 | schema-fn)))
390 | k)
391 | ([k schema-fn]
392 | (register-pred! k schema-fn default-opts)))
393 |
394 | (defn- parse-fn
395 | [args fn-body opts]
396 | (or (impl/pred-conformer fn-body opts)
397 | (if (:strict opts)
398 | (throw (ex-info "Unknown predicate to json-schema generator"
399 | {:exoscale.ex/type :s-exp.pact/unknown-pred
400 | :args args
401 | :body fn-body}))
402 | (json-schema (:unknown-spec-default opts) opts))))
403 |
404 | (ex/derive :s-exp.pact/unknown-pred :exoscale.ex/invalid)
405 |
406 | (register-form!
407 | `clojure.core/fn
408 | (fn [[args form] opts]
409 | (parse-fn args form opts)))
410 |
411 | ;;; preds
412 |
413 | (register-pred! (s/def :s-exp.pact.json-schema.pred/num-compare
414 | (s/or :count-1
415 | (s/cat :op #{'= '< '> '<= '>= 'not=}
416 | :_ simple-symbol?
417 | :x any?)
418 | :count-2 (s/cat :op #{'= '< '> '<= '>= 'not=}
419 | :x any?
420 | :_ simple-symbol?)))
421 | (fn [[t {:keys [op x]}] _opts]
422 |
423 | (case [t op]
424 | ([:count-1 >=] [:count-2 <=]) {:minimum x :type "number"}
425 | ([:count-1 <=] [:count-2 >=]) {:maximum x :type "number"}
426 | ([:count-1 >] [:count-2 <]) {:minimum (inc x) :type "number"}
427 | ([:count-1 <] [:count-2 >]) {:maximum (dec x) :type "number"}
428 | ([:count-1 =] [:count-2 =]) {:const x}
429 | ([:count-1 not=] [:count-2 not=]) {:not {:const x}})))
430 |
431 | (s/def ::count+arg (s/spec (s/cat :_ #{'count} :sym simple-symbol?)))
432 |
433 | (register-pred! (s/def :s-exp-pact.json-schema.pred/count-compare
434 | (s/or :count-1
435 | (s/cat :op #{'<= '< '> '>= '= 'not=}
436 | :_cnt ::count+arg
437 | :x number?)
438 |
439 | :count-2
440 | (s/cat :op #{'<= '< '> '>= '= 'not=}
441 | :x number?
442 | :_cnt ::count+arg)))
443 | (fn [[t {:keys [op x]}] _opts]
444 |
445 | (assoc (case [t op]
446 | ([:count-1 =] [:count-2 =]) {:const x}
447 | ([:count-1 not=] [:count-2 not=]) {:not {:const x}}
448 | ([:count-1 <=] [:count-2 >=]) {:maxItems x}
449 | ([:count-1 >=] [:count-2 <=]) {:minItems x}
450 | ([:count-1 <] [:count-2 >]) {:maxItems (dec x)}
451 | ([:count-1 >] [:count-2 <]) {:minItems (inc x)})
452 | :type "array")))
453 |
454 | (register-pred! (s/def :s-exp.pact.json-schema.pred/int-in-range?
455 | (s/cat :op #{'clojure.spec.alpha/int-in-range?}
456 | :minimum int?
457 | :maximum int?
458 | :_ any?))
459 | (fn [{:keys [minimum maximum]} _opts]
460 | {:type "integer" :minimum minimum :maximum maximum}))
461 |
--------------------------------------------------------------------------------
/src/s_exp/pact/impl.clj:
--------------------------------------------------------------------------------
1 | (ns s-exp.pact.impl
2 | (:refer-clojure :exclude [derive vary-meta meta])
3 | (:require
4 | [clojure.spec.alpha :as s]
5 | [clojure.walk :as walk]))
6 |
7 | ;;; reg
8 |
9 | (defn registry-meta
10 | "Returns metadata registry or metadata for spec `k`"
11 | ([registry-val] (get registry-val :s-exp.pact.json-schema/meta))
12 | ([registry-val k]
13 | (get (registry-meta registry-val) k)))
14 |
15 | (defn registry-form
16 | "Returns registry form function for key `k`"
17 | [registry-val k]
18 | (get-in registry-val [:s-exp.pact.json-schema/forms k]))
19 |
20 | (defn registry-ident
21 | "Returns registry ident value for key `k`"
22 | [registry-val k]
23 | (get-in registry-val [:s-exp.pact.json-schema/idents k]))
24 |
25 | (defn find-schema
26 | "Find first schema generator in spec hierarchy"
27 | [registry-val spec-chain {:as opts :keys [idents forms preds]}]
28 | (let [registry-val
29 | (-> registry-val
30 | (update :s-exp.pact.json-schema/forms merge forms)
31 | (update :s-exp.pact.json-schema/idents merge idents)
32 | (update :s-exp.pact.json-schema/preds merge preds))
33 | opts (merge opts registry-val)
34 | cnil (constantly nil)]
35 | (reduce (fn find-schema* [_ x]
36 | (when-let [schema (cond
37 | (set? x)
38 | ((or (registry-form registry-val 's-exp.pact/enum-of)
39 | cnil)
40 | x opts)
41 |
42 | (sequential? x)
43 | ((or (registry-form registry-val (first x))
44 | cnil)
45 | (rest x) opts)
46 |
47 | (qualified-ident? x)
48 | (registry-ident registry-val x))]
49 | (reduced schema)))
50 | nil
51 | spec-chain)))
52 |
53 | (defn find-key
54 | "Find first `prop` value in spec hierarchy for spec"
55 | [prop]
56 | (fn [registry-val spec-chain]
57 | (let [m (registry-meta registry-val)]
58 | (reduce (fn find-key* [_ k]
59 | (when (qualified-keyword? k)
60 | (when-let [val (get-in m [k prop])]
61 | (reduced val))))
62 | nil
63 | spec-chain))))
64 |
65 | ;;; Preds
66 |
67 | (defn strip-core
68 | [sym]
69 | (cond-> sym
70 | (= (namespace sym) "clojure.core")
71 | (-> name symbol)))
72 |
73 | (defn abbrev [form]
74 | (cond->> form
75 | (seq? form)
76 | (walk/postwalk (fn [form]
77 | (let [qs? (qualified-symbol? form)]
78 | (cond
79 | ;; just treat */% as %
80 | (and qs? (= "%" (name form)))
81 | (symbol "%")
82 |
83 | ;; it's could be a core symbol, in that case remove ns
84 | qs?
85 | (strip-core form)
86 |
87 | (and (seq? form)
88 | (contains? #{'fn 'fn*} (first form)))
89 | (last form)
90 | :else form))))))
91 |
92 | (defn pred-conformer
93 | [pred {:as opts :s-exp.pact.json-schema/keys [preds]}]
94 | (reduce (fn match-conformer [_ [k f]]
95 | (let [match (s/conform k (abbrev pred))]
96 | (when-not (= :clojure.spec.alpha/invalid match)
97 | (reduced (f match opts)))))
98 | nil
99 | preds))
100 |
101 | ;;; Spec inspection
102 |
103 | (defn accept-keyword [x]
104 | (when (qualified-keyword? x)
105 | x))
106 |
107 | (defn accept-symbol [x]
108 | (when (qualified-symbol? x)
109 | x))
110 |
111 | (defn accept-set [x]
112 | (when (set? x)
113 | x))
114 |
115 | (defn accept-symbol-call [spec]
116 | (when (and (seq? spec)
117 | (symbol? (first spec)))
118 | spec))
119 |
120 | (defn spec-form
121 | "Return the spec form or nil."
122 | [spec]
123 | (some-> spec s/get-spec s/form))
124 |
125 | (defn spec-root
126 | "Determine the main spec root from a spec form."
127 | [spec]
128 | (let [spec-def (or (spec-form spec)
129 | (accept-symbol spec)
130 | (accept-symbol-call spec)
131 | (accept-set spec))]
132 | (cond-> spec-def
133 | (qualified-keyword? spec-def)
134 | recur)))
135 |
136 | (defn parent-spec
137 | "Look up for the parent coercer using the spec hierarchy."
138 | [k]
139 | (or (accept-keyword (s/get-spec k))
140 | (accept-keyword (spec-form k))))
141 |
142 | (defn spec-chain
143 | "Determine the main spec root from a spec form."
144 | [spec]
145 | (loop [spec spec
146 | ret (cond-> [spec])]
147 | (let [p (or (parent-spec spec)
148 | (spec-form spec))]
149 | (if p
150 | (recur p (conj ret p))
151 | ret))))
152 |
153 | ;;; schemas impls
154 |
155 | (defn string-schema
156 | ([] (string-schema {}))
157 | ([& {:as opts}]
158 | (merge {:type "string"} opts)))
159 |
160 | (defn array-schema
161 | ([] {:type "array"})
162 | ([& {:as opts}]
163 | (merge (array-schema) opts)))
164 |
165 | (defn int-schema
166 | ([] {:type "integer"})
167 | ([& {:as opts}]
168 | (merge (int-schema) opts)))
169 |
170 | (defn object-schema
171 | ([] {:type "object"})
172 | ([& {:as opts}]
173 | (merge (object-schema) opts)))
174 |
175 | (defn number-schema
176 | ([] {:type "number"})
177 | ([& {:as opts}]
178 | (merge (number-schema) opts)))
179 |
--------------------------------------------------------------------------------
/test/s_exp/pact_test.clj:
--------------------------------------------------------------------------------
1 | (ns s-exp.pact-test
2 | (:require [clojure.spec.alpha :as s]
3 | [clojure.test :as test :refer [is deftest are]]
4 | [exoscale.ex.test]
5 | [s-exp.pact :as p]
6 | [s-exp.pact.impl :as impl]))
7 |
8 | (s/check-asserts true)
9 | (set-validator! p/registry-ref
10 | (fn [x]
11 | (s/assert (s/keys) x)))
12 |
13 | (deftest test-simple-preds
14 | (are [spec schema] (= schema (p/json-schema spec))
15 | `string? {:type "string"}
16 | `keyword? {:type "string"}
17 | `number? {:type "number"}
18 | `int? {:type "integer" :format "int64"}
19 | `integer? {:type "integer" :format "int64"}
20 | `pos-int? {:type "integer" :format "int64" :minimum 1}
21 | `nat-int? {:type "integer" :format "int64" :minimum 0}
22 | `neg-int? {:type "integer" :format "int64" :maximum -1}
23 | `float? {:type "number" :format "float"}
24 | `double? {:type "number" :format "double"}
25 | `boolean? {:type "boolean"}
26 | `inst? {:type "string" :format "date-time"}
27 | `any? {:type "object"}
28 | `coll? {:type "array"}
29 | `list? {:type "array"}
30 | `sequential? {:type "array"}
31 | `vector? {:type "array"}
32 | `map? {:type "object"}
33 | `uuid? {:type "string" :format "uuid"}
34 | `nil? {:type "null"}))
35 |
36 | (deftest test-composites
37 | (are [spec schema] (= schema (p/json-schema spec))
38 | #{:a :b} {:enum #{:a :b}}
39 | `(s/and number? int?) {:allOf [{:type "number"} {:type "integer" :format "int64"}]}
40 | `(s/or :num number? :int int?) {:anyOf [{:type "number"} {:type "integer" :format "int64"}]}
41 | `(s/alt :num number? :int int?) {:anyOf [{:type "number"} {:type "integer" :format "int64"}]}
42 | `(s/coll-of string?) {:type "array", :items {:type "string"}}
43 | `(s/coll-of string? :max-count 3) {:type "array", :items {:type "string"} :maxItems 3}
44 | `(s/every string?) {:type "array", :items {:type "string"}}
45 | `(s/every string? :max-count 3) {:type "array", :items {:type "string"} :maxItems 3}
46 | `(s/map-of any? string?) {:type "object", :patternProperties {".*" {:type "string"}}}
47 | `(s/map-of int? string?) {:type "object", :patternProperties {".*" {:type "string"}}}
48 | `(s/cat :foo (s/* string?)) {:type "array" :items {:anyOf [{:items [{:type "string"}], :type "array"}]}}
49 | `(s/int-in 0 3) {:type "integer", :minimum 0, :maximum 2}
50 | `(s/nilable string?) {:anyOf [{:type "null"} {:type "string"}]}))
51 |
52 | (s/def ::foo string?)
53 | (s/def ::bar keyword?)
54 | (s/def ::baz int?)
55 |
56 | (deftest test-s-keys
57 | (are [spec schema] (= schema (p/json-schema spec))
58 | `(s/keys :req-un [::foo ::bar] :opt-un [::baz])
59 | {:type "object",
60 | :properties
61 | {"foo" {:type "string"},
62 | "bar" {:type "string"},
63 | "baz" {:type "integer", :format "int64"}},
64 | :required ["foo" "bar"]}
65 |
66 | `(s/keys :req [::foo ::bar] :opt [::baz])
67 | {:type "object",
68 | :properties
69 | {"foo" {:type "string"},
70 | "bar" {:type "string"},
71 | "baz" {:type "integer", :format "int64"}},
72 | :required ["foo" "bar"]}
73 |
74 | `(s/keys :req-un [(or ::foo (and ::bar ::baz))])
75 | {:type "object",
76 | :properties
77 | {"foo" {:type "string"},
78 | "bar" {:type "string"},
79 | "baz" {:type "integer", :format "int64"}},
80 | :required ["foo" "bar" "baz"]}
81 |
82 | `(s/merge (s/keys :req-un [::foo]) (s/keys :req-un [::bar])
83 | (s/keys :opt-un [::baz]))
84 | {:allOf
85 | [{:type "object",
86 | :properties {"foo" {:type "string"}},
87 | :required ["foo"]}
88 | {:type "object",
89 | :properties {"bar" {:type "string"}},
90 | :required ["bar"]}
91 | {:type "object",
92 | :properties {"baz" {:type "integer", :format "int64"}}}]}))
93 |
94 | (s/def ::tag #{:a :b :c :d})
95 | (s/def ::example-key keyword?)
96 | (s/def ::different-key keyword?)
97 | (defmulti tagmm :tag)
98 | (defmethod tagmm :a [_] (s/keys :req-un [::tag ::example-key]))
99 | (defmethod tagmm :default [_] (s/keys :req-un [::tag ::different-key]))
100 | (s/def ::ms (s/multi-spec tagmm :tag))
101 |
102 | (deftest test-s-multi-spec
103 | (are [spec schema] (= schema (p/json-schema spec))
104 | ::ms {:anyOf
105 | [{:type "object",
106 | :properties
107 | {"tag" {:enum #{:c :b :d :a}}, "different-key" {:type "string"}},
108 | :required ["tag" "different-key"]}
109 | {:type "object",
110 | :properties
111 | {"tag" {:enum #{:c :b :d :a}}, "example-key" {:type "string"}},
112 | :required ["tag" "example-key"]}]}))
113 |
114 | (deftest test-predicates-math
115 | (s/def ::f1 (s/and number? (fn [x] (>= x 10))))
116 | (s/def ::f1' (s/and number? #(>= % 10)))
117 | (s/def ::f2 (s/and number? (fn [x] (> x 10))))
118 | (s/def ::f3 (s/and number? (fn [x] (<= x 10))))
119 | (s/def ::f4 (s/and number? (fn [x] (< x 10))))
120 | (s/def ::f5 (s/and number? (fn [x] (= 10 x))))
121 | (s/def ::f6 (s/and number? (fn [x] (not= 10 x))))
122 |
123 | (s/def ::f7 (s/and number? (fn [x] (>= 10 x))))
124 | (s/def ::f8 (s/and number? (fn [x] (> 10 x))))
125 | (s/def ::f9 (s/and number? (fn [x] (<= 10 x))))
126 | (s/def ::f10 (s/and number? (fn [x] (< 10 x))))
127 | (s/def ::f11 (s/and number? (fn [x] (= x 10))))
128 | (s/def ::f12 (s/and number? (fn [x] (not= x 10))))
129 | (are [spec schema] (= schema (p/json-schema spec))
130 | ::f1 {:allOf [{:type "number"} {:minimum 10, :type "number"}]}
131 | ::f1' {:allOf [{:type "number"} {:minimum 10, :type "number"}]}
132 | ::f2 {:allOf [{:type "number"} {:minimum 11, :type "number"}]}
133 | ::f3 {:allOf [{:type "number"} {:maximum 10, :type "number"}]}
134 | ::f4 {:allOf [{:type "number"} {:maximum 9, :type "number"}]}
135 | ::f5 {:allOf [{:type "number"} {:const 10}]}
136 | ::f6 {:allOf [{:type "number"} {:not {:const 10}}]}
137 | ::f7 {:allOf [{:type "number"} {:maximum 10, :type "number"}]}
138 | ::f8 {:allOf [{:type "number"} {:maximum 9, :type "number"}]}
139 | ::f9 {:allOf [{:type "number"} {:minimum 10, :type "number"}]}
140 | ::f10 {:allOf [{:type "number"} {:minimum 11, :type "number"}]}
141 | ::f11 {:allOf [{:type "number"} {:const 10}]}
142 | ::f12 {:allOf [{:type "number"} {:not {:const 10}}]}))
143 |
144 | (deftest pred-strictness
145 | (s/def ::unknown-pred (s/and string? (fn [x] :stuff)))
146 | (is (thrown-ex-info-type? :s-exp.pact/unknown-pred (p/json-schema ::unknown-pred)))
147 | (is (= {:allOf [{:type "string"}]} (p/json-schema ::unknown-pred {:strict false}))))
148 |
149 | (defmacro string-of [& _])
150 |
151 | (deftest form-strictness
152 | (s/def ::unknown-form (s/and string? (string-of string?)))
153 | (is (thrown-ex-info-type? :s-exp.pact/unknown-val (p/json-schema ::unknown-form)))
154 | (is (= {:allOf [{:type "string"}]} (p/json-schema ::unknown-form {:strict false}))))
155 |
156 | (deftest ident-strictness
157 | (s/def ::unknown-ident (s/and ::xxx ::yyy))
158 | (is (thrown-ex-info-type? :s-exp.pact/unknown-val (p/json-schema ::unknown-ident)))
159 | (is (= {:allOf []} (p/json-schema ::unknown-ident {:strict false})))
160 | (is (= {:allOf [{:type "object"} {:type "object"}]}
161 | (p/json-schema ::unknown-ident {:strict false
162 | :unknown-spec-default {:type "object"}}))))
163 |
164 | (deftest s-and-first-arg
165 | (s/def ::s-and-first (s/and string? (string-of string?)))
166 | (is (= {:allOf [{:type "string"}]}
167 | (p/json-schema ::s-and-first {:gen-only-first-and-arg true}))))
168 |
169 | (deftest meta-test
170 | (let [title "test"
171 | pattern "pattern"]
172 | (-> (s/def ::meta-test string?)
173 | (p/with-title title)
174 | (p/with-id "id")
175 | (p/with-pattern pattern)
176 | (p/with-description "description")
177 | (p/with-format "format"))
178 | (s/def ::meta-test2 ::meta-test)
179 | (s/def ::meta-test3 ::meta-test2)
180 |
181 | (is (= (p/find-title (p/registry) (impl/spec-chain ::meta-test))
182 | title))
183 | (is (= (p/find-title (p/registry) (impl/spec-chain ::meta-test2))
184 | title))
185 | (is (= (p/find-title (p/registry) (impl/spec-chain ::meta-test3))
186 | title))
187 | (is (= (p/find-pattern (p/registry) (impl/spec-chain ::meta-test3))
188 | pattern))
189 |
190 | (let [schema {:extra "yolo"}]
191 | (is (= (:extra schema)
192 | (:extra (p/json-schema ::meta-test
193 | {:idents {::meta-test schema}}))))
194 | (is (= (:extra schema)
195 | (:extra (p/json-schema ::meta-test2
196 | {:idents {::meta-test schema}}))))
197 | (is (= {:stuff 1} (p/json-schema `(s/coll-of string?)
198 | {:forms {`s/coll-of (fn [_ _] {:stuff 1})}})))
199 |
200 | (is (= {:stuff 1}
201 | (p/json-schema `(s/coll-of string?)
202 | {:forms {`s/coll-of (fn [_ _] {:stuff 1})}})
203 | (p/json-schema `(s/coll-of string?)
204 | :forms {`s/coll-of (fn [_ _] {:stuff 1})}))))))
205 |
--------------------------------------------------------------------------------