initial commit
This commit is contained in:
@@ -0,0 +1 @@
|
||||
node_modules
|
||||
@@ -0,0 +1 @@
|
||||
* @elyukai
|
||||
@@ -0,0 +1,378 @@
|
||||
Copyright (C) 2022-present Lukas Obermann
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0.
|
||||
|
||||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
|
||||
1. Definitions
|
||||
--------------
|
||||
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
means Source Code Form to which the initial Contributor has attached
|
||||
the notice in Exhibit A, the Executable Form of such Source Code
|
||||
Form, and Modifications of such Source Code Form, in each case
|
||||
including portions thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
|
||||
(b) that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the
|
||||
terms of a Secondary License.
|
||||
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. "Larger Work"
|
||||
means a work that combines Covered Software with other material, in
|
||||
a separate file or files, that is not Covered Software.
|
||||
|
||||
1.8. "License"
|
||||
means this document.
|
||||
|
||||
1.9. "Licensable"
|
||||
means having the right to grant, to the maximum extent possible,
|
||||
whether at the time of the initial grant or subsequently, any and
|
||||
all of the rights conveyed by this License.
|
||||
|
||||
1.10. "Modifications"
|
||||
means any of the following:
|
||||
|
||||
(a) any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered
|
||||
Software; or
|
||||
|
||||
(b) any new file in Source Code Form that contains any Covered
|
||||
Software.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the
|
||||
License, by the making, using, selling, offering for sale, having
|
||||
made, import, or transfer of either its Contributions or its
|
||||
Contributor Version.
|
||||
|
||||
1.12. "Secondary License"
|
||||
means either the GNU General Public License, Version 2.0, the GNU
|
||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||
Public License, Version 3.0, or any later versions of those
|
||||
licenses.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that
|
||||
controls, is controlled by, or is under common control with You. For
|
||||
purposes of this definition, "control" means (a) the power, direct
|
||||
or indirect, to cause the direction or management of such entity,
|
||||
whether by contract or otherwise, or (b) ownership of more than
|
||||
fifty percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
|
||||
2. License Grants and Conditions
|
||||
--------------------------------
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
(a) under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||
for sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
(a) for any code that a Contributor has removed from Covered Software;
|
||||
or
|
||||
|
||||
(b) for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights
|
||||
to grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
(a) such Covered Software must also be made available in Source Code
|
||||
Form, as described in Section 3.1, and You must inform recipients of
|
||||
the Executable Form how they can obtain a copy of such Source Code
|
||||
Form by reasonable means in a timely manner, at a charge no more
|
||||
than the cost of distribution to the recipient; and
|
||||
|
||||
(b) You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter
|
||||
the recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty,
|
||||
or limitations of liability) contained within the Source Code Form of
|
||||
the Covered Software, except that You may alter any license notices to
|
||||
the extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
---------------------------------------------------
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this
|
||||
License with respect to some or all of the Covered Software due to
|
||||
statute, judicial order, or regulation then You must: (a) comply with
|
||||
the terms of this License to the maximum extent possible; and (b)
|
||||
describe the limitations and the code they affect. Such description must
|
||||
be placed in a text file included with all distributions of the Covered
|
||||
Software under this License. Except to the extent prohibited by statute
|
||||
or regulation, such description must be sufficiently detailed for a
|
||||
recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
--------------
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically
|
||||
if You fail to comply with any of its terms. However, if You become
|
||||
compliant, then the rights granted under this License from a particular
|
||||
Contributor are reinstated (a) provisionally, unless and until such
|
||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||
ongoing basis, if such Contributor fails to notify You of the
|
||||
non-compliance by some reasonable means prior to 60 days after You have
|
||||
come back into compliance. Moreover, Your grants from a particular
|
||||
Contributor are reinstated on an ongoing basis if such Contributor
|
||||
notifies You of the non-compliance by some reasonable means, this is the
|
||||
first time You have received notice of non-compliance with this License
|
||||
from such Contributor, and You become compliant prior to 30 days after
|
||||
Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||
end user license agreements (excluding distributors and resellers) which
|
||||
have been validly granted by You or Your distributors under this License
|
||||
prior to termination shall survive termination.
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 6. Disclaimer of Warranty *
|
||||
* ------------------------- *
|
||||
* *
|
||||
* Covered Software is provided under this License on an "as is" *
|
||||
* basis, without warranty of any kind, either expressed, implied, or *
|
||||
* statutory, including, without limitation, warranties that the *
|
||||
* Covered Software is free of defects, merchantable, fit for a *
|
||||
* particular purpose or non-infringing. The entire risk as to the *
|
||||
* quality and performance of the Covered Software is with You. *
|
||||
* Should any Covered Software prove defective in any respect, You *
|
||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||
* essential part of this License. No use of any Covered Software is *
|
||||
* authorized under this License except under this disclaimer. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 7. Limitation of Liability *
|
||||
* -------------------------- *
|
||||
* *
|
||||
* Under no circumstances and under no legal theory, whether tort *
|
||||
* (including negligence), contract, or otherwise, shall any *
|
||||
* Contributor, or anyone who distributes Covered Software as *
|
||||
* permitted above, be liable to You for any direct, indirect, *
|
||||
* special, incidental, or consequential damages of any character *
|
||||
* including, without limitation, damages for lost profits, loss of *
|
||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||
* and all other commercial damages or losses, even if such party *
|
||||
* shall have been informed of the possibility of such damages. This *
|
||||
* limitation of liability shall not apply to liability for death or *
|
||||
* personal injury resulting from such party's negligence to the *
|
||||
* extent applicable law prohibits such limitation. Some *
|
||||
* jurisdictions do not allow the exclusion or limitation of *
|
||||
* incidental or consequential damages, so this exclusion and *
|
||||
* limitation may not apply to You. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
|
||||
Any litigation relating to this License may be brought only in the
|
||||
courts of a jurisdiction where the defendant maintains its principal
|
||||
place of business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions.
|
||||
Nothing in this Section shall prevent a party's ability to bring
|
||||
cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides
|
||||
that the language of a contract shall be construed against the drafter
|
||||
shall not be used to construe this License against a Contributor.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular
|
||||
file, then You may include the notice in a location (such as a LICENSE
|
||||
file in a relevant directory) where a recipient would be likely to look
|
||||
for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
---------------------------------------------------------
|
||||
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||
defined by the Mozilla Public License, v. 2.0.
|
||||
@@ -0,0 +1,104 @@
|
||||
# Optolith TypeScript to JSON Schema and Markdown
|
||||
|
||||
This tool provides an opinionated solution for generating **both JSON Schemas and corresponding Markdown documentation** from a set of TypeScript files. The tool does not support all types possible in TypeScript, only those that are needed in Optolith and that can be represented in a JSON Schema as well.
|
||||
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
node -r ts-node/register/transpile-only src/main.ts --tsdir "src/entity" --jsondir "schema" --mddir "docs"
|
||||
```
|
||||
|
||||
The tool takes all TypeScript files from the source directory `tsdir` and outputs a JSON Schema to `jsondir` and a Markdown file to `mddir` for each file. All three options can point to the same folder. It does not do any cleanup, it only overwrites existing files. Types that are referenced from other files are also referenced this way in JSON Schema and Markdown, so that the output is a mirror of the TypeScript files without any duplicate definitions in both JSON Schema and Markdown. Not that all types must be present in the specified directory, otherwise references/links in JSON schema and Markdown will not work.
|
||||
|
||||
Types that are not supported are represented as an `UNKNOWN` type (or variant such as `UNKNOWN LITERAL`) in JSON schema. If structures are too deeply nested for Markdown representation, the nested types will be output as formatted JSON schema. The script usually **does not throw** if it encounters anything it cannot represent, but instead tries to represent it in an obvious way without needing to throw.
|
||||
|
||||
### Main type
|
||||
|
||||
A module comment may indicate the main type of the module, which can be used by directly importing the JSON Schema without the need to specify the definition inside. The type is referenced to by its name.
|
||||
|
||||
Example:
|
||||
|
||||
```ts
|
||||
/**
|
||||
* @main Attribute
|
||||
*/
|
||||
```
|
||||
|
||||
### Supported types
|
||||
|
||||
Types may have constraints, which are annotated as JSDoc tags. They may have an associated value.
|
||||
|
||||
#### Descriptive tags
|
||||
|
||||
Each type supports descriptive tags used in both output formats.
|
||||
|
||||
##### `@title`
|
||||
|
||||
Not only used for JSON Schema, it is also used for headings in Markdown.
|
||||
|
||||
##### Description
|
||||
|
||||
The JSDoc comment itself is used as the value `description` in JSON Schema and also precedes any details in Markdown
|
||||
|
||||
#### String
|
||||
|
||||
##### Supported tags
|
||||
|
||||
- `@minLength` — `integer`
|
||||
- `@maxLength` — `integer`
|
||||
|
||||
#### Number
|
||||
|
||||
##### Supported tags
|
||||
|
||||
- `@integer` If this tag is present, the number is output as an integer and other tags related to the value are also interpreted as integers.
|
||||
- `@minimum` — `integer/number`
|
||||
- `@maximum` — `integer/number`
|
||||
|
||||
#### Array
|
||||
|
||||
##### Supported tags
|
||||
|
||||
- `@minItems` — `integer`
|
||||
- `@maxItems` — `integer`
|
||||
- `@uniqueItems`
|
||||
|
||||
#### Object
|
||||
|
||||
An object with strict properties cannot have indexed properties at the same time.
|
||||
|
||||
##### Supported tags
|
||||
|
||||
None.
|
||||
|
||||
#### Dictionary
|
||||
|
||||
An object with indexed properties cannot have strict properties at the same time.
|
||||
|
||||
##### Supported tags
|
||||
|
||||
This is used for indexed properties.
|
||||
|
||||
- `@minProperties`
|
||||
|
||||
##### Pattern Dictionary
|
||||
|
||||
Pattern properties are annotated using `@patternProperties`. The value of this annotation is the pattern that should be used for the indexed properties. It is annotated on the indexed property definition, not the object itself.
|
||||
|
||||
Example:
|
||||
|
||||
```ts
|
||||
/**
|
||||
* @minProperties 1
|
||||
*/
|
||||
type IndexedObject = {
|
||||
/**
|
||||
* @patternProperties ^KEY_[1-9]$
|
||||
*/
|
||||
[key: string]: number
|
||||
}
|
||||
```
|
||||
|
||||
#### Literals
|
||||
|
||||
Strings, numbers and boolean values are supported.
|
||||
Generated
+276
@@ -0,0 +1,276 @@
|
||||
{
|
||||
"name": "optolith-tsjsonschemamd",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"version": "1.0.0",
|
||||
"license": "MPL-2.0",
|
||||
"dependencies": {
|
||||
"ts-node": "^10.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^17.0.18",
|
||||
"typescript": "^4.5.5"
|
||||
}
|
||||
},
|
||||
"node_modules/@cspotcode/source-map-consumer": {
|
||||
"version": "0.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-consumer/-/source-map-consumer-0.8.0.tgz",
|
||||
"integrity": "sha512-41qniHzTU8yAGbCp04ohlmSrZf8bkf/iJsl3V0dRGsQN/5GFfx+LbCSsCpp2gqrqjTVg/K6O8ycoV35JIwAzAg==",
|
||||
"engines": {
|
||||
"node": ">= 12"
|
||||
}
|
||||
},
|
||||
"node_modules/@cspotcode/source-map-support": {
|
||||
"version": "0.7.0",
|
||||
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.7.0.tgz",
|
||||
"integrity": "sha512-X4xqRHqN8ACt2aHVe51OxeA2HjbcL4MqFqXkrmQszJ1NOUuUu5u6Vqx/0lZSVNku7velL5FC/s5uEAj1lsBMhA==",
|
||||
"dependencies": {
|
||||
"@cspotcode/source-map-consumer": "0.8.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@tsconfig/node10": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.8.tgz",
|
||||
"integrity": "sha512-6XFfSQmMgq0CFLY1MslA/CPUfhIL919M1rMsa5lP2P097N2Wd1sSX0tx1u4olM16fLNhtHZpRhedZJphNJqmZg=="
|
||||
},
|
||||
"node_modules/@tsconfig/node12": {
|
||||
"version": "1.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.9.tgz",
|
||||
"integrity": "sha512-/yBMcem+fbvhSREH+s14YJi18sp7J9jpuhYByADT2rypfajMZZN4WQ6zBGgBKp53NKmqI36wFYDb3yaMPurITw=="
|
||||
},
|
||||
"node_modules/@tsconfig/node14": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.1.tgz",
|
||||
"integrity": "sha512-509r2+yARFfHHE7T6Puu2jjkoycftovhXRqW328PDXTVGKihlb1P8Z9mMZH04ebyajfRY7dedfGynlrFHJUQCg=="
|
||||
},
|
||||
"node_modules/@tsconfig/node16": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.2.tgz",
|
||||
"integrity": "sha512-eZxlbI8GZscaGS7kkc/trHTT5xgrjH3/1n2JDwusC9iahPKWMRvRjJSAN5mCXviuTGQ/lHnhvv8Q1YTpnfz9gA=="
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "17.0.18",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.18.tgz",
|
||||
"integrity": "sha512-eKj4f/BsN/qcculZiRSujogjvp5O/k4lOW5m35NopjZM/QwLOR075a8pJW5hD+Rtdm2DaCVPENS6KtSQnUD6BA=="
|
||||
},
|
||||
"node_modules/acorn": {
|
||||
"version": "8.7.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.0.tgz",
|
||||
"integrity": "sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ==",
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/acorn-walk": {
|
||||
"version": "8.2.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz",
|
||||
"integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==",
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/arg": {
|
||||
"version": "4.1.3",
|
||||
"resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz",
|
||||
"integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA=="
|
||||
},
|
||||
"node_modules/create-require": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz",
|
||||
"integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ=="
|
||||
},
|
||||
"node_modules/diff": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz",
|
||||
"integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==",
|
||||
"engines": {
|
||||
"node": ">=0.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/make-error": {
|
||||
"version": "1.3.6",
|
||||
"resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
|
||||
"integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw=="
|
||||
},
|
||||
"node_modules/ts-node": {
|
||||
"version": "10.5.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.5.0.tgz",
|
||||
"integrity": "sha512-6kEJKwVxAJ35W4akuiysfKwKmjkbYxwQMTBaAxo9KKAx/Yd26mPUyhGz3ji+EsJoAgrLqVsYHNuuYwQe22lbtw==",
|
||||
"dependencies": {
|
||||
"@cspotcode/source-map-support": "0.7.0",
|
||||
"@tsconfig/node10": "^1.0.7",
|
||||
"@tsconfig/node12": "^1.0.7",
|
||||
"@tsconfig/node14": "^1.0.0",
|
||||
"@tsconfig/node16": "^1.0.2",
|
||||
"acorn": "^8.4.1",
|
||||
"acorn-walk": "^8.1.1",
|
||||
"arg": "^4.1.0",
|
||||
"create-require": "^1.1.0",
|
||||
"diff": "^4.0.1",
|
||||
"make-error": "^1.1.1",
|
||||
"v8-compile-cache-lib": "^3.0.0",
|
||||
"yn": "3.1.1"
|
||||
},
|
||||
"bin": {
|
||||
"ts-node": "dist/bin.js",
|
||||
"ts-node-cwd": "dist/bin-cwd.js",
|
||||
"ts-node-script": "dist/bin-script.js",
|
||||
"ts-node-transpile-only": "dist/bin-transpile.js",
|
||||
"ts-script": "dist/bin-script-deprecated.js"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@swc/core": ">=1.2.50",
|
||||
"@swc/wasm": ">=1.2.50",
|
||||
"@types/node": "*",
|
||||
"typescript": ">=2.7"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@swc/core": {
|
||||
"optional": true
|
||||
},
|
||||
"@swc/wasm": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "4.5.5",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.5.tgz",
|
||||
"integrity": "sha512-TCTIul70LyWe6IJWT8QSYeA54WQe8EjQFU4wY52Fasj5UKx88LNYKCgBEHcOMOrFF1rKGbD8v/xcNWVUq9SymA==",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/v8-compile-cache-lib": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.0.tgz",
|
||||
"integrity": "sha512-mpSYqfsFvASnSn5qMiwrr4VKfumbPyONLCOPmsR3A6pTY/r0+tSaVbgPWSAIuzbk3lCTa+FForeTiO+wBQGkjA=="
|
||||
},
|
||||
"node_modules/yn": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",
|
||||
"integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@cspotcode/source-map-consumer": {
|
||||
"version": "0.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-consumer/-/source-map-consumer-0.8.0.tgz",
|
||||
"integrity": "sha512-41qniHzTU8yAGbCp04ohlmSrZf8bkf/iJsl3V0dRGsQN/5GFfx+LbCSsCpp2gqrqjTVg/K6O8ycoV35JIwAzAg=="
|
||||
},
|
||||
"@cspotcode/source-map-support": {
|
||||
"version": "0.7.0",
|
||||
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.7.0.tgz",
|
||||
"integrity": "sha512-X4xqRHqN8ACt2aHVe51OxeA2HjbcL4MqFqXkrmQszJ1NOUuUu5u6Vqx/0lZSVNku7velL5FC/s5uEAj1lsBMhA==",
|
||||
"requires": {
|
||||
"@cspotcode/source-map-consumer": "0.8.0"
|
||||
}
|
||||
},
|
||||
"@tsconfig/node10": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.8.tgz",
|
||||
"integrity": "sha512-6XFfSQmMgq0CFLY1MslA/CPUfhIL919M1rMsa5lP2P097N2Wd1sSX0tx1u4olM16fLNhtHZpRhedZJphNJqmZg=="
|
||||
},
|
||||
"@tsconfig/node12": {
|
||||
"version": "1.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.9.tgz",
|
||||
"integrity": "sha512-/yBMcem+fbvhSREH+s14YJi18sp7J9jpuhYByADT2rypfajMZZN4WQ6zBGgBKp53NKmqI36wFYDb3yaMPurITw=="
|
||||
},
|
||||
"@tsconfig/node14": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.1.tgz",
|
||||
"integrity": "sha512-509r2+yARFfHHE7T6Puu2jjkoycftovhXRqW328PDXTVGKihlb1P8Z9mMZH04ebyajfRY7dedfGynlrFHJUQCg=="
|
||||
},
|
||||
"@tsconfig/node16": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.2.tgz",
|
||||
"integrity": "sha512-eZxlbI8GZscaGS7kkc/trHTT5xgrjH3/1n2JDwusC9iahPKWMRvRjJSAN5mCXviuTGQ/lHnhvv8Q1YTpnfz9gA=="
|
||||
},
|
||||
"@types/node": {
|
||||
"version": "17.0.18",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.18.tgz",
|
||||
"integrity": "sha512-eKj4f/BsN/qcculZiRSujogjvp5O/k4lOW5m35NopjZM/QwLOR075a8pJW5hD+Rtdm2DaCVPENS6KtSQnUD6BA=="
|
||||
},
|
||||
"acorn": {
|
||||
"version": "8.7.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.0.tgz",
|
||||
"integrity": "sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ=="
|
||||
},
|
||||
"acorn-walk": {
|
||||
"version": "8.2.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz",
|
||||
"integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA=="
|
||||
},
|
||||
"arg": {
|
||||
"version": "4.1.3",
|
||||
"resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz",
|
||||
"integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA=="
|
||||
},
|
||||
"create-require": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz",
|
||||
"integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ=="
|
||||
},
|
||||
"diff": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz",
|
||||
"integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A=="
|
||||
},
|
||||
"make-error": {
|
||||
"version": "1.3.6",
|
||||
"resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
|
||||
"integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw=="
|
||||
},
|
||||
"ts-node": {
|
||||
"version": "10.5.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.5.0.tgz",
|
||||
"integrity": "sha512-6kEJKwVxAJ35W4akuiysfKwKmjkbYxwQMTBaAxo9KKAx/Yd26mPUyhGz3ji+EsJoAgrLqVsYHNuuYwQe22lbtw==",
|
||||
"requires": {
|
||||
"@cspotcode/source-map-support": "0.7.0",
|
||||
"@tsconfig/node10": "^1.0.7",
|
||||
"@tsconfig/node12": "^1.0.7",
|
||||
"@tsconfig/node14": "^1.0.0",
|
||||
"@tsconfig/node16": "^1.0.2",
|
||||
"acorn": "^8.4.1",
|
||||
"acorn-walk": "^8.1.1",
|
||||
"arg": "^4.1.0",
|
||||
"create-require": "^1.1.0",
|
||||
"diff": "^4.0.1",
|
||||
"make-error": "^1.1.1",
|
||||
"v8-compile-cache-lib": "^3.0.0",
|
||||
"yn": "3.1.1"
|
||||
}
|
||||
},
|
||||
"typescript": {
|
||||
"version": "4.5.5",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.5.tgz",
|
||||
"integrity": "sha512-TCTIul70LyWe6IJWT8QSYeA54WQe8EjQFU4wY52Fasj5UKx88LNYKCgBEHcOMOrFF1rKGbD8v/xcNWVUq9SymA=="
|
||||
},
|
||||
"v8-compile-cache-lib": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.0.tgz",
|
||||
"integrity": "sha512-mpSYqfsFvASnSn5qMiwrr4VKfumbPyONLCOPmsR3A6pTY/r0+tSaVbgPWSAIuzbk3lCTa+FForeTiO+wBQGkjA=="
|
||||
},
|
||||
"yn": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",
|
||||
"integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q=="
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "optolith-tsjsonschemamd",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "main.ts",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"author": "Lukas Obermann",
|
||||
"license": "MPL-2.0",
|
||||
"devDependencies": {
|
||||
"@types/node": "^17.0.18",
|
||||
"typescript": "^4.5.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"ts-node": "^10.5.0"
|
||||
}
|
||||
}
|
||||
+967
@@ -0,0 +1,967 @@
|
||||
import { Dirent, mkdirSync, readdirSync, writeFileSync } from "fs"
|
||||
import { basename, extname, join, sep } from "path"
|
||||
import * as ts from "typescript"
|
||||
|
||||
namespace JsonSchema {
|
||||
export type ConstraintKey = "minimum" | "maximum" | "minProperties" | "maxProperties" | "minLength" | "maxLength" | "format" | "minItems" | "maxItems" | "uniqueItems"
|
||||
|
||||
export type ConstraintValueType = "integer" | "numeric" | "boolean"
|
||||
|
||||
export type ValueType = "object" | "number" | "string" | "array"
|
||||
|
||||
/**
|
||||
* Descriptive annotations of the JSON type definition
|
||||
*/
|
||||
export interface Annotated {
|
||||
title?: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
export interface ObjectBase extends Annotated {
|
||||
type: "object"
|
||||
}
|
||||
|
||||
export interface StrictObject extends ObjectBase {
|
||||
properties: {
|
||||
[key: string]: Definition
|
||||
}
|
||||
required: string[]
|
||||
additionalProperties: false
|
||||
}
|
||||
|
||||
export interface PatternDictionary extends ObjectBase {
|
||||
patternProperties: {
|
||||
[pattern: string]: Definition
|
||||
}
|
||||
minProperties?: number
|
||||
additionalProperties: false
|
||||
}
|
||||
|
||||
export interface Dictionary extends ObjectBase {
|
||||
minProperties?: number
|
||||
additionalProperties: Definition
|
||||
}
|
||||
|
||||
export interface Array extends Annotated {
|
||||
type: "array"
|
||||
items: Definition
|
||||
minItems?: number
|
||||
maxItems?: number
|
||||
uniqueItems?: boolean
|
||||
}
|
||||
|
||||
export interface Number extends Annotated {
|
||||
type: "number" | "integer"
|
||||
minimum?: number
|
||||
maximum?: number
|
||||
}
|
||||
|
||||
export interface String extends Annotated {
|
||||
type: "string"
|
||||
minLength?: number
|
||||
maxLength?: number
|
||||
}
|
||||
|
||||
export interface Boolean extends Annotated {
|
||||
type: "boolean"
|
||||
}
|
||||
|
||||
export interface Union extends Annotated {
|
||||
oneOf: Definition[]
|
||||
}
|
||||
|
||||
export interface Constant extends Annotated {
|
||||
const: string | number | boolean
|
||||
}
|
||||
|
||||
export interface Reference extends Annotated {
|
||||
$ref: string
|
||||
}
|
||||
|
||||
export type Simple =
|
||||
| Number
|
||||
| String
|
||||
| Boolean
|
||||
| Constant
|
||||
| Reference
|
||||
|
||||
export type NonStrictObject =
|
||||
| Dictionary
|
||||
| PatternDictionary
|
||||
| Array
|
||||
| Number
|
||||
| String
|
||||
| Boolean
|
||||
| Reference
|
||||
| Union
|
||||
| Constant
|
||||
|
||||
export type Definition =
|
||||
| StrictObject
|
||||
| Dictionary
|
||||
| PatternDictionary
|
||||
| Array
|
||||
| Number
|
||||
| String
|
||||
| Boolean
|
||||
| Reference
|
||||
| Union
|
||||
| Constant
|
||||
|
||||
export interface Base extends Annotated {
|
||||
$schema: string
|
||||
$id: string
|
||||
$ref?: string
|
||||
definitions: {
|
||||
[id: string]: Definition
|
||||
}
|
||||
}
|
||||
|
||||
export const isStrictObject = (x: Definition): x is StrictObject =>
|
||||
(x as { type: any }).type === "object"
|
||||
&& x.hasOwnProperty("properties")
|
||||
|
||||
export const isDictionary = (x: Definition): x is Dictionary =>
|
||||
(x as { type: any }).type === "object"
|
||||
&& !x.hasOwnProperty("properties")
|
||||
&& !x.hasOwnProperty("patternProperties")
|
||||
|
||||
export const isPatternDictionary = (x: Definition): x is PatternDictionary =>
|
||||
(x as { type: any }).type === "object"
|
||||
&& x.hasOwnProperty("patternProperties")
|
||||
|
||||
export const isArray = (x: Definition): x is Array =>
|
||||
(x as { type: any }).type === "array"
|
||||
|
||||
export const isNumber = (x: Definition): x is Number =>
|
||||
(x as { type: any }).type === "number"
|
||||
|| (x as { type: any }).type === "integer"
|
||||
|
||||
export const isString = (x: Definition): x is String =>
|
||||
(x as { type: any }).type === "string"
|
||||
|
||||
export const isBoolean = (x: Definition): x is Boolean =>
|
||||
(x as { type: any }).type === "boolean"
|
||||
|
||||
export const isUnion = (x: Definition): x is Union =>
|
||||
x.hasOwnProperty("oneOf")
|
||||
|
||||
export const isConstant = (x: Definition): x is Constant =>
|
||||
x.hasOwnProperty("const")
|
||||
|
||||
export const isReference = (x: Definition): x is Reference =>
|
||||
x.hasOwnProperty("$ref")
|
||||
|
||||
export const isSimple = (x: Definition): x is Simple =>
|
||||
isNumber(x) || isString(x) || isBoolean(x) || isConstant(x) || isReference(x)
|
||||
|
||||
export const constraintsByValueType: { [K in ConstraintKey]?: ConstraintValueType } = {
|
||||
minimum: "numeric",
|
||||
maximum: "numeric",
|
||||
minProperties: "integer",
|
||||
maxProperties: "integer",
|
||||
minLength: "integer",
|
||||
maxLength: "integer",
|
||||
minItems: "integer",
|
||||
maxItems: "integer",
|
||||
uniqueItems: "boolean",
|
||||
}
|
||||
|
||||
export const constraintsByJsonSchemaType: { [K in ValueType]: ConstraintKey[] } = {
|
||||
number: ["minimum", "maximum"],
|
||||
string: ["minLength", "maxLength", "format"],
|
||||
object: ["minProperties", "maxProperties"],
|
||||
array: ["minItems", "maxItems", "uniqueItems"],
|
||||
}
|
||||
|
||||
export const hasKeyword = (jsDoc: ts.JSDoc | undefined, tagName: string) =>
|
||||
jsDoc?.tags?.some(tag => tag.tagName.escapedText === tagName)
|
||||
|
||||
export const keywordValue = (jsDoc: ts.JSDoc | undefined, tagName: string) =>
|
||||
ts.getTextOfJSDocComment(jsDoc?.tags?.find(tag => tag.tagName.escapedText === tagName)?.comment)
|
||||
|
||||
export const parseKeywordValue = (
|
||||
keyword: ConstraintKey,
|
||||
value: string,
|
||||
parseNumeric: (value: string) => number = Number.parseInt
|
||||
) => {
|
||||
switch (constraintsByValueType[keyword]) {
|
||||
case "integer": return Number.parseInt(value)
|
||||
case "boolean": return value === "true" || value === ""
|
||||
case "numeric": return parseNumeric(value ?? "")
|
||||
default: return value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace JSDoc {
|
||||
export const ofNode = (node: ts.Node) => node.getChildren().filter(ts.isJSDoc).slice(-1)[0]
|
||||
|
||||
export const toAnnotations = (jsDoc: ts.JSDoc | undefined) => ({
|
||||
title: JsonSchema.keywordValue(jsDoc, "title"),
|
||||
description: ts.getTextOfJSDocComment(jsDoc?.comment)
|
||||
?.replace(/\r\n(?:\r\n)+/g, "\n\n")
|
||||
.replace(/\r\n/g, " "),
|
||||
})
|
||||
|
||||
const tagToKeywordValuePair = (
|
||||
type: JsonSchema.ValueType,
|
||||
tag: ts.JSDocTag,
|
||||
parseNumeric: (value: string) => number = Number.parseInt
|
||||
) => {
|
||||
const keyword = tag.tagName.escapedText.toString() as JsonSchema.ConstraintKey
|
||||
const value = tag.comment?.toString() ?? ""
|
||||
|
||||
if (JsonSchema.constraintsByJsonSchemaType[type].includes(keyword)) {
|
||||
return [ keyword, JsonSchema.parseKeywordValue(keyword, value, parseNumeric) ]
|
||||
}
|
||||
}
|
||||
|
||||
export const toConstraints = (
|
||||
jsDoc: ts.JSDoc | undefined,
|
||||
type: JsonSchema.ValueType,
|
||||
parseNumeric: (value: string) => number = Number.parseInt
|
||||
) => Object.fromEntries(
|
||||
jsDoc?.tags?.flatMap(tag => {
|
||||
const keywordValuePair = tagToKeywordValuePair(type, tag, parseNumeric)
|
||||
|
||||
return keywordValuePair ? [keywordValuePair] : []
|
||||
}) ?? []
|
||||
)
|
||||
}
|
||||
|
||||
namespace TypeScriptToJsonSchema {
|
||||
const propertyNameToString = (propertyName: ts.PropertyName) =>
|
||||
ts.isComputedPropertyName(propertyName)
|
||||
? propertyName.expression.getText()
|
||||
: propertyName.text
|
||||
|
||||
const toJsonSchemaObject = (
|
||||
node: ts.InterfaceDeclaration | ts.TypeLiteralNode,
|
||||
jsDoc: ts.JSDoc | undefined
|
||||
): JsonSchema.Definition => {
|
||||
const firstMember = node.members[0]
|
||||
|
||||
if (node.members.length === 1 && firstMember && ts.isIndexSignatureDeclaration(firstMember)) {
|
||||
const jsDocIndex = JSDoc.ofNode(firstMember)
|
||||
|
||||
const propertyPattern = jsDocIndex?.tags?.find(tag => tag.tagName.escapedText === "patternProperties")
|
||||
|
||||
const value = toJsonSchemaType(firstMember.type)
|
||||
|
||||
if (propertyPattern !== undefined) {
|
||||
return {
|
||||
...JSDoc.toAnnotations(jsDoc),
|
||||
type: "object",
|
||||
patternProperties: {
|
||||
[propertyPattern.comment?.toString() ?? ""]: value
|
||||
},
|
||||
...JSDoc.toConstraints(jsDoc, "object"),
|
||||
additionalProperties: false
|
||||
}
|
||||
}
|
||||
else {
|
||||
return {
|
||||
...JSDoc.toAnnotations(jsDoc),
|
||||
type: "object",
|
||||
additionalProperties: value,
|
||||
...JSDoc.toConstraints(jsDoc, "object")
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (node.members.every(ts.isPropertySignature)) {
|
||||
const properties = (node.members as readonly ts.PropertySignature[]).map(
|
||||
member => {
|
||||
return {
|
||||
name: propertyNameToString(member.name),
|
||||
required: member.questionToken === undefined,
|
||||
value: toJsonSchemaType(member.type!)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
...JSDoc.toAnnotations(jsDoc),
|
||||
type: "object",
|
||||
properties: Object.fromEntries(properties.map(({ name, value }) => [name, value])),
|
||||
required: properties.filter(prop => prop.required).map(({ name }) => name),
|
||||
additionalProperties: false
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw new Error("Mixing index signatures and concrete properties is currently unsupported");
|
||||
}
|
||||
}
|
||||
|
||||
const toJsonSchemaPrimitive = (node: ts.Node): JsonSchema.Definition => {
|
||||
const jsDoc = JSDoc.ofNode(node.parent)
|
||||
|
||||
switch (node.kind) {
|
||||
case ts.SyntaxKind.NumberKeyword: {
|
||||
const isInteger = jsDoc?.tags?.some(tag => tag.tagName.escapedText === "integer")
|
||||
|
||||
const parseNumeric = isInteger ? Number.parseInt : Number.parseFloat
|
||||
|
||||
return {
|
||||
...JSDoc.toAnnotations(jsDoc),
|
||||
type: isInteger ? "integer" : "number",
|
||||
...JSDoc.toConstraints(jsDoc, "number", parseNumeric)
|
||||
}
|
||||
}
|
||||
|
||||
case ts.SyntaxKind.StringKeyword: {
|
||||
return {
|
||||
...JSDoc.toAnnotations(jsDoc),
|
||||
type: "string",
|
||||
...JSDoc.toConstraints(jsDoc, "string")
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
// @ts-expect-error
|
||||
return { type: "UNKNOWN TOKEN" }
|
||||
}
|
||||
}
|
||||
|
||||
const toJsonSchemaArray = (node: ts.ArrayTypeNode): JsonSchema.Definition => {
|
||||
const jsDoc = JSDoc.ofNode(node.parent)
|
||||
|
||||
return {
|
||||
...JSDoc.toAnnotations(jsDoc),
|
||||
type: "array",
|
||||
items: toJsonSchemaType(node.elementType),
|
||||
...JSDoc.toConstraints(jsDoc, "array")
|
||||
}
|
||||
}
|
||||
|
||||
const toJsonSchemaLiteral = (node: ts.LiteralTypeNode): JsonSchema.Definition => {
|
||||
const jsDoc = JSDoc.ofNode(node.parent)
|
||||
|
||||
if (ts.isStringLiteral(node.literal)) {
|
||||
return {
|
||||
...JSDoc.toAnnotations(jsDoc),
|
||||
const: node.literal.text
|
||||
}
|
||||
}
|
||||
else {
|
||||
// @ts-expect-error
|
||||
return { type: "UNKNOWN LITERAL TYPE" }
|
||||
}
|
||||
}
|
||||
|
||||
const toJsonSchemaUnion = (node: ts.UnionTypeNode): JsonSchema.Definition => {
|
||||
const jsDoc = JSDoc.ofNode(node.parent)
|
||||
|
||||
return {
|
||||
...JSDoc.toAnnotations(jsDoc),
|
||||
oneOf: node.types.map(toJsonSchemaType)
|
||||
}
|
||||
}
|
||||
|
||||
const toJsonSchemaReference = (node: ts.TypeReferenceNode): JsonSchema.Definition => {
|
||||
const jsDoc = JSDoc.ofNode(node.parent)
|
||||
|
||||
const name = ts.isIdentifier(node.typeName)
|
||||
? node.typeName.escapedText.toString()
|
||||
: node.typeName.right.escapedText.toString()
|
||||
|
||||
// const refSymbol = checker.getSymbolAtLocation(node.typeName)
|
||||
|
||||
// const type = refSymbol && checker.getTypeOfSymbolAtLocation(refSymbol, node)
|
||||
|
||||
// const type = checker.getTypeAtLocation(node.typeName)
|
||||
|
||||
// const symbol = type.getSymbol()
|
||||
|
||||
// const aliasedSymbol = symbol && checker.alias(symbol)
|
||||
|
||||
// const sourceFiles = symbol
|
||||
// ?.declarations
|
||||
// ?.map(decl => decl.getSourceFile())
|
||||
// ?? []
|
||||
|
||||
const currentSourceFile = node.getSourceFile()
|
||||
|
||||
const importNodes = currentSourceFile.statements.filter(ts.isImportDeclaration)
|
||||
|
||||
const matchingImportNode = importNodes.find(importNode => {
|
||||
const namedBindings = importNode.importClause?.namedBindings
|
||||
|
||||
if (namedBindings && ts.isNamedImports(namedBindings)) {
|
||||
return namedBindings.elements.some(namedBinding => namedBinding.name.escapedText === name)
|
||||
}
|
||||
else {
|
||||
return false
|
||||
}
|
||||
})
|
||||
|
||||
const externalRelativeFilePath = matchingImportNode?.moduleSpecifier.getText().replace(/^["'](.+)["']$/, "$1")
|
||||
|
||||
// const externalAbsoluteFilePath = externalRelativeFilePath !== undefined
|
||||
// ? resolve(currentSourceFile.fileName, externalRelativeFilePath).split(sep).join("/")
|
||||
// : undefined
|
||||
|
||||
const externalFile = externalRelativeFilePath !== undefined
|
||||
? `${externalRelativeFilePath}.schema.json`
|
||||
: ""
|
||||
|
||||
return {
|
||||
...JSDoc.toAnnotations(jsDoc),
|
||||
$ref: `${externalFile}#/definitions/${name}`
|
||||
}
|
||||
}
|
||||
|
||||
const toJsonSchemaType = (node: ts.Node): JsonSchema.Definition => {
|
||||
if (ts.isTypeAliasDeclaration(node)) {
|
||||
return toJsonSchemaType(node.type)
|
||||
}
|
||||
else if (ts.isInterfaceDeclaration(node)) {
|
||||
return toJsonSchemaObject(node, JSDoc.ofNode(node))
|
||||
}
|
||||
else if (ts.isTypeLiteralNode(node)) {
|
||||
return toJsonSchemaObject(node, JSDoc.ofNode(node.parent))
|
||||
}
|
||||
else if (ts.isToken(node)) {
|
||||
return toJsonSchemaPrimitive(node)
|
||||
}
|
||||
else if (ts.isUnionTypeNode(node)) {
|
||||
return toJsonSchemaUnion(node)
|
||||
}
|
||||
else if (ts.isTypeReferenceNode(node)) {
|
||||
return toJsonSchemaReference(node)
|
||||
}
|
||||
else if (ts.isArrayTypeNode(node)) {
|
||||
return toJsonSchemaArray(node)
|
||||
}
|
||||
else if (ts.isLiteralTypeNode(node)) {
|
||||
return toJsonSchemaLiteral(node)
|
||||
}
|
||||
else {
|
||||
console.log(node)
|
||||
// @ts-expect-error
|
||||
return { type: "UNKNOWN" }
|
||||
}
|
||||
}
|
||||
|
||||
const getModuleJsDoc = (file: ts.SourceFile) => {
|
||||
const firstNode = file.statements[0]
|
||||
|
||||
if (firstNode) {
|
||||
if (ts.isImportDeclaration(firstNode)) {
|
||||
return JSDoc.ofNode(firstNode)
|
||||
}
|
||||
else {
|
||||
const jsDocs = firstNode.getChildren().filter(ts.isJSDoc)
|
||||
|
||||
return jsDocs.length > 1 ? jsDocs[0] : undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const getDefinitionName = (statement: ts.Node) => {
|
||||
if (ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement)) {
|
||||
return statement.name.escapedText.toString()
|
||||
}
|
||||
else {
|
||||
throw new Error("No reference name for node available");
|
||||
}
|
||||
}
|
||||
|
||||
export const convertFile = (file: ts.SourceFile, schemaFileName: string): JsonSchema.Base => {
|
||||
const jsDoc = getModuleJsDoc(file)
|
||||
|
||||
const definitions = Object.fromEntries(
|
||||
file
|
||||
.statements
|
||||
.filter(x => ts.isInterfaceDeclaration(x) || ts.isTypeAliasDeclaration(x))
|
||||
.map(statement => [
|
||||
getDefinitionName(statement),
|
||||
toJsonSchemaType(statement)
|
||||
])
|
||||
)
|
||||
|
||||
const mainType = ts.getTextOfJSDocComment(jsDoc?.tags?.find(tag => tag.tagName.escapedText === "main")?.comment)
|
||||
|
||||
return {
|
||||
$schema: "http://json-schema.org/draft-07/schema",
|
||||
$id: schemaFileName,
|
||||
$ref: mainType ? `#/definitions/${mainType}` : mainType,
|
||||
definitions
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace JsonSchemaToMarkdown {
|
||||
const refToParts = (ref: string) => {
|
||||
const groups = /^(?:(?<external>.+)\.schema\.json)?#\/definitions\/(?<id>\w+)$/.exec(ref)?.groups
|
||||
|
||||
if (groups && groups.id) {
|
||||
return {
|
||||
external: groups.external,
|
||||
id: groups.id
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw new Error(`Json Schema $ref "${ref}" has no id`);
|
||||
}
|
||||
}
|
||||
|
||||
const resolveDefinition = (schema: JsonSchema.Base, ref: string): JsonSchema.Definition | undefined => {
|
||||
const resolvedRef = refToParts(ref)
|
||||
|
||||
if (resolvedRef.external !== undefined) {
|
||||
return undefined
|
||||
}
|
||||
else {
|
||||
const definition = schema.definitions[resolvedRef.id]
|
||||
|
||||
if (definition) {
|
||||
if (JsonSchema.isReference(definition)) {
|
||||
return resolveDefinition(schema, definition.$ref)
|
||||
}
|
||||
else {
|
||||
return definition
|
||||
}
|
||||
}
|
||||
else {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const h = (level: number, text: string, anchor?: string) => {
|
||||
const safeLevel = level < 1 ? 1 : level > 6 ? 6 : level
|
||||
const anchorElement = anchor === undefined ? "" : ` <a name="${anchor}"></a>`
|
||||
|
||||
return `${"#".repeat(safeLevel)}${anchorElement} ${text}`
|
||||
}
|
||||
|
||||
const a = (text: string, href: string) => `<a href="${href}">${text}</a>`
|
||||
|
||||
const docHeader = (schema: JsonSchema.Base, ref: JsonSchema.Annotated | undefined) => {
|
||||
const title = ref?.title ?? schema.title ?? "[TITLE MISSING]"
|
||||
const description = ref?.description ?? schema.description
|
||||
|
||||
return headerWithDescription(h(1, title), description)
|
||||
}
|
||||
|
||||
const definitionHeader = (id: string, node: JsonSchema.Annotated) => {
|
||||
return headerWithDescription(h(3, node.title ?? id, id), node.description)
|
||||
}
|
||||
|
||||
const headerWithDescription = (title: string, description: string | undefined) => {
|
||||
if (description === undefined) {
|
||||
return title
|
||||
}
|
||||
|
||||
return `${title}\n\n${description}`
|
||||
}
|
||||
|
||||
namespace LabelledList {
|
||||
type KeyConfig<T extends object, K extends keyof T> = false | {
|
||||
label: string,
|
||||
transform?: (value: T[K] extends undefined ? never : T[K]) => string | number | boolean
|
||||
}
|
||||
|
||||
export type Config<T extends object> = {
|
||||
[K in keyof T]-?: KeyConfig<T, K>
|
||||
}
|
||||
|
||||
export type AdditionalConfig = {
|
||||
indent?: number
|
||||
prepend?: { [label: string]: string }
|
||||
append?: { [label: string]: string }
|
||||
}
|
||||
|
||||
export const line = (label: string, value: string | number | boolean, indent = 0) =>
|
||||
`${" ".repeat(indent)}- **${label}:** ${value}`
|
||||
|
||||
export const create = <T extends object>(
|
||||
obj: T,
|
||||
config: Config<T>,
|
||||
{ indent = 0, prepend = {}, append = {} }: AdditionalConfig = {}
|
||||
) => {
|
||||
return [
|
||||
...Object.entries(prepend)
|
||||
.map(([label, value]) => line(label, value, indent)),
|
||||
...Object.entries(obj)
|
||||
.flatMap(([key, value]) => {
|
||||
const keyConfig = (config as { [key: string]: KeyConfig<T, keyof T> })[key]
|
||||
|
||||
if (keyConfig && value !== undefined) {
|
||||
const transformedValue = keyConfig.transform
|
||||
? keyConfig.transform(value as T[keyof T] extends undefined ? never : T[keyof T])
|
||||
: value
|
||||
|
||||
return [line(keyConfig.label, transformedValue, indent)]
|
||||
}
|
||||
else {
|
||||
return []
|
||||
}
|
||||
}),
|
||||
...Object.entries(append)
|
||||
.map(([label, value]) => line(label, value, indent))
|
||||
]
|
||||
.join("\n")
|
||||
}
|
||||
}
|
||||
|
||||
const simpleBody = (
|
||||
node: JsonSchema.Simple
|
||||
): string => {
|
||||
if (JsonSchema.isNumber(node)) {
|
||||
return LabelledList.create(node, {
|
||||
title: false,
|
||||
description: false,
|
||||
type: { label: "Type", transform: value => value === "integer" ? "Integer" : "Number" },
|
||||
minimum: { label: "Minimum", transform: value => `\`${value}\`` },
|
||||
maximum: { label: "Maximum", transform: value => `\`${value}\`` },
|
||||
})
|
||||
}
|
||||
else if (JsonSchema.isString(node)) {
|
||||
return LabelledList.create(node, {
|
||||
title: false,
|
||||
description: false,
|
||||
type: { label: "Type", transform: () => "String" },
|
||||
minLength: { label: "Minimum Length", transform: value => `\`${value}\`` },
|
||||
maxLength: { label: "Maximum Length", transform: value => `\`${value}\`` },
|
||||
})
|
||||
}
|
||||
else if (JsonSchema.isBoolean(node)) {
|
||||
return LabelledList.create(node, {
|
||||
title: false,
|
||||
description: false,
|
||||
type: { label: "Type", transform: () => "Boolean" },
|
||||
})
|
||||
}
|
||||
else if (JsonSchema.isConstant(node)) {
|
||||
return LabelledList.create(node, {
|
||||
title: false,
|
||||
description: false,
|
||||
const: { label: "Constant", transform: value => `\`${JSON.stringify(value)}\`` },
|
||||
})
|
||||
}
|
||||
else if (JsonSchema.isReference(node)) {
|
||||
return LabelledList.create(node, {
|
||||
title: false,
|
||||
description: false,
|
||||
$ref: {
|
||||
label: "Type",
|
||||
transform: ref => {
|
||||
const { id, external } = refToParts(ref)
|
||||
|
||||
return a(id, `${external ? `${external}.md` : ""}#${id}`)
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
else {
|
||||
throw new Error(`${JSON.stringify(node)} is not primitive`)
|
||||
}
|
||||
}
|
||||
|
||||
type ResultCollection = {
|
||||
paragraphs: string[]
|
||||
openDefinitions: {
|
||||
propertyPath: string
|
||||
definition: JsonSchema.Definition
|
||||
}[]
|
||||
}
|
||||
|
||||
const arrayBody = (
|
||||
node: JsonSchema.Array,
|
||||
headingLevel: number,
|
||||
propertyPath: string
|
||||
): string[] => {
|
||||
return [
|
||||
LabelledList.create(node, {
|
||||
title: false,
|
||||
description: false,
|
||||
type: { label: "Type", transform: () => "List" },
|
||||
items: false,
|
||||
uniqueItems: { label: "Unique Items", transform: value => `\`${value}\`` },
|
||||
minItems: { label: "Minimum Items", transform: value => `\`${value}\`` },
|
||||
maxItems: { label: "Maximum Items", transform: value => `\`${value}\`` },
|
||||
}),
|
||||
h(headingLevel + 1, "Items"),
|
||||
JsonSchema.isSimple(node.items) ? simpleBody(node.items) : printJson(node.items)
|
||||
]
|
||||
}
|
||||
|
||||
const unionBody = (
|
||||
node: JsonSchema.Union,
|
||||
headingLevel: number,
|
||||
propertyPath: string
|
||||
): string[] => {
|
||||
const cases = node.oneOf
|
||||
.flatMap((childNode, index): string[] => {
|
||||
if (JsonSchema.isReference(childNode)) {
|
||||
const { id } = refToParts(childNode.$ref)
|
||||
|
||||
return [
|
||||
headerWithDescription(
|
||||
h(headingLevel + 1, `Case: ${childNode.title ?? id}`),
|
||||
childNode.description
|
||||
),
|
||||
simpleBody(childNode)
|
||||
]
|
||||
}
|
||||
else if (JsonSchema.isSimple(childNode)) {
|
||||
return [
|
||||
headerWithDescription(
|
||||
h(headingLevel + 1, `Case: ${childNode.title ?? index.toFixed(0)}`),
|
||||
childNode.description
|
||||
),
|
||||
simpleBody(childNode)
|
||||
]
|
||||
}
|
||||
else {
|
||||
const id = (() => {
|
||||
if (JsonSchema.isStrictObject(childNode)) {
|
||||
const tagProperty = childNode.properties["tag"]
|
||||
return tagProperty && JsonSchema.isConstant(tagProperty)
|
||||
? tagProperty.const.toString()
|
||||
: index.toFixed(0)
|
||||
}
|
||||
else {
|
||||
return index.toFixed(0)
|
||||
}
|
||||
})()
|
||||
|
||||
const casePropertyPath = `${propertyPath}\`${index}`
|
||||
|
||||
return [
|
||||
headerWithDescription(
|
||||
h(headingLevel + 1, `Case: ${childNode.title ?? id}`),
|
||||
childNode.description
|
||||
),
|
||||
...definitionBody(childNode, headingLevel + 1, casePropertyPath)
|
||||
]
|
||||
}
|
||||
})
|
||||
|
||||
return [
|
||||
LabelledList.create(node, {
|
||||
title: false,
|
||||
description: false,
|
||||
oneOf: { label: "Type", transform: () => "Union"}
|
||||
}),
|
||||
...cases
|
||||
]
|
||||
}
|
||||
|
||||
const dictionaryBody = (
|
||||
node: JsonSchema.Dictionary,
|
||||
headingLevel: number,
|
||||
propertyPath: string
|
||||
): string[] => {
|
||||
return [
|
||||
LabelledList.create(node, {
|
||||
title: false,
|
||||
description: false,
|
||||
type: { label: "Type", transform: () => "Dictionary" },
|
||||
additionalProperties: false,
|
||||
minProperties: { label: "Minimum Properties", transform: value => `\`${value}\`` },
|
||||
}),
|
||||
h(headingLevel + 1, "Values"),
|
||||
JsonSchema.isSimple(node.additionalProperties) ? simpleBody(node.additionalProperties) : printJson(node.additionalProperties)
|
||||
]
|
||||
}
|
||||
|
||||
const patternDictionaryBody = (
|
||||
node: JsonSchema.PatternDictionary,
|
||||
headingLevel: number,
|
||||
propertyPath: string
|
||||
): string[] => {
|
||||
return [
|
||||
LabelledList.create(node, {
|
||||
title: false,
|
||||
description: false,
|
||||
type: { label: "Type", transform: () => "Dictionary" },
|
||||
patternProperties: { label: "Patterns", transform: value => Object.keys(value).map(pattern => `\`${pattern}\``).join(", ") },
|
||||
minProperties: { label: "Minimum Properties", transform: value => `\`${value}\`` },
|
||||
additionalProperties: false,
|
||||
}),
|
||||
...Object.entries(node.patternProperties).flatMap(([pattern, propertyNode]) => {
|
||||
return [
|
||||
h(headingLevel + 1, `Values matching \`${pattern}\``),
|
||||
JsonSchema.isSimple(propertyNode) ? simpleBody(propertyNode) : printJson(propertyNode)
|
||||
]
|
||||
})
|
||||
]
|
||||
}
|
||||
|
||||
const nonStrictObject = (node: JsonSchema.NonStrictObject, headingLevel: number, propertyPath: string): string[] => {
|
||||
if (JsonSchema.isSimple(node)) {
|
||||
return [simpleBody(node)]
|
||||
}
|
||||
else if (JsonSchema.isArray(node)) {
|
||||
return arrayBody(node, headingLevel, propertyPath)
|
||||
}
|
||||
else if (JsonSchema.isUnion(node)) {
|
||||
return unionBody(node, headingLevel, propertyPath)
|
||||
}
|
||||
else if (JsonSchema.isDictionary(node)) {
|
||||
return dictionaryBody(node, headingLevel, propertyPath)
|
||||
}
|
||||
else if (JsonSchema.isPatternDictionary(node)) {
|
||||
return patternDictionaryBody(node, headingLevel, propertyPath)
|
||||
}
|
||||
else {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
const strictObjectBody = (
|
||||
node: JsonSchema.StrictObject,
|
||||
headingLevel: number,
|
||||
propertyPath: string
|
||||
): string[] => {
|
||||
const propertiesOverview = Object.entries(node.properties)
|
||||
.map(([key, propertyNode]) => {
|
||||
const propertyPropertyPath = `${propertyPath}/${key}`
|
||||
const title = `\`${key}${node.required.includes(key) ? "" : "?"}\``
|
||||
|
||||
return [
|
||||
title,
|
||||
propertyNode.description ?? "",
|
||||
a("See details", `#${propertyPropertyPath}`)
|
||||
].join(" | ")
|
||||
})
|
||||
.join("\n")
|
||||
|
||||
const properties = Object.entries(node.properties)
|
||||
.flatMap(([key, propertyNode]): string[] => {
|
||||
const propertyPropertyPath = `${propertyPath}/${key}`
|
||||
const title = h(headingLevel + 1, `\`${key}${node.required.includes(key) ? "" : "?"}\``, propertyPropertyPath)
|
||||
|
||||
if (JsonSchema.isStrictObject(propertyNode)) {
|
||||
return [
|
||||
headerWithDescription( title, propertyNode.description ),
|
||||
printJson(propertyNode)
|
||||
]
|
||||
}
|
||||
else {
|
||||
return [
|
||||
headerWithDescription( title, propertyNode.description ),
|
||||
...nonStrictObject(propertyNode, headingLevel + 1, propertyPropertyPath)
|
||||
]
|
||||
}
|
||||
})
|
||||
|
||||
return [
|
||||
LabelledList.create(node, {
|
||||
title: false,
|
||||
description: false,
|
||||
type: { label: "Type", transform: () => "Object" },
|
||||
properties: false,
|
||||
required: false,
|
||||
additionalProperties: false,
|
||||
}),
|
||||
`Key | Description | Details\n:-- | :-- | :--\n${propertiesOverview}`,
|
||||
...properties
|
||||
]
|
||||
}
|
||||
|
||||
const printJson = (json: any) => `\`\`\`json\n${JSON.stringify(json, undefined, 2)}\n\`\`\``
|
||||
|
||||
const definitionBody = (node: JsonSchema.Definition, headingLevel: number, propertyPath: string): string[] => {
|
||||
if (JsonSchema.isStrictObject(node)) {
|
||||
return strictObjectBody(node, headingLevel, propertyPath)
|
||||
}
|
||||
else {
|
||||
return nonStrictObject(node, headingLevel, propertyPath)
|
||||
}
|
||||
}
|
||||
|
||||
const definitionToMarkdown = (id: string, node: JsonSchema.Definition, headingLevel: number) => {
|
||||
const header = definitionHeader(id, node)
|
||||
const body = definitionBody(node, headingLevel, id)
|
||||
|
||||
return [
|
||||
header,
|
||||
...body
|
||||
]
|
||||
}
|
||||
|
||||
export const convertSchema = (schema: JsonSchema.Base) => {
|
||||
const ref = schema.$ref !== undefined ? resolveDefinition(schema, schema.$ref) : undefined
|
||||
|
||||
const definitions = Object.entries(schema.definitions)
|
||||
.flatMap(([id, definition], i, arr) =>
|
||||
arr.length > i + 1
|
||||
? [
|
||||
...definitionToMarkdown(id, definition, 3),
|
||||
"---"
|
||||
]
|
||||
: definitionToMarkdown(id, definition, 3)
|
||||
)
|
||||
|
||||
return [
|
||||
docHeader(schema, ref),
|
||||
h(2, "Definitions"),
|
||||
...definitions
|
||||
].join("\n\n")
|
||||
}
|
||||
}
|
||||
|
||||
const getOptionValue = (name: string) => {
|
||||
const index = process.argv.indexOf(name)
|
||||
|
||||
if (index > -1) {
|
||||
return process.argv[index + 1]
|
||||
}
|
||||
}
|
||||
|
||||
const tsDir = getOptionValue("--tsdir")
|
||||
const jsonSchemaDir = getOptionValue("--jsondir")
|
||||
const mdDir = getOptionValue("--mddir")
|
||||
|
||||
if (!tsDir || !jsonSchemaDir || !mdDir) {
|
||||
console.log(`\
|
||||
Usage:
|
||||
|
||||
node -r ts-node/register/transpile-only createSchema.ts --tsdir "src/entity" --jsondir "json" --mddir "docs"`)
|
||||
}
|
||||
else {
|
||||
const rootPaths = tsDir.split(/[\/\\]/)
|
||||
|
||||
const dirEntryToFilePath = (dirEntry: Dirent) =>
|
||||
[...__dirname.split(sep), ...rootPaths, dirEntry.name].join("/")
|
||||
|
||||
const tsFiles = readdirSync(join(...rootPaths), { withFileTypes: true })
|
||||
.flatMap(dirEntry => {
|
||||
if (dirEntry.isFile() && extname(dirEntry.name) === ".ts") {
|
||||
return [dirEntryToFilePath(dirEntry)]
|
||||
}
|
||||
else {
|
||||
return []
|
||||
}
|
||||
})
|
||||
|
||||
const program = ts.createProgram(tsFiles, { strict: true })
|
||||
|
||||
// KEEP, SIDE EFFECT: it fills the parent references of nodes
|
||||
program.getTypeChecker()
|
||||
|
||||
const jsonSchemaRoot = jsonSchemaDir.split(/[\/\\]/)
|
||||
const markdownRoot = mdDir.split(/[\/\\]/)
|
||||
|
||||
mkdirSync(join(...jsonSchemaRoot), { recursive: true })
|
||||
mkdirSync(join(...markdownRoot), { recursive: true })
|
||||
|
||||
program
|
||||
.getSourceFiles()
|
||||
.filter(file => tsFiles.includes(file.fileName))
|
||||
// .filter(file => file.fileName.includes("State.ts"))
|
||||
.forEach(file => {
|
||||
const schemaFilePath = [...jsonSchemaRoot, `${basename(file.fileName, ".ts")}.schema.json`]
|
||||
const markdownFilePath = [...markdownRoot, `${basename(file.fileName, ".ts")}.md`]
|
||||
|
||||
const schema = TypeScriptToJsonSchema.convertFile(file, schemaFilePath.join("/"))
|
||||
const docs = JsonSchemaToMarkdown.convertSchema(schema)
|
||||
|
||||
writeFileSync(join(...schemaFilePath), JSON.stringify(schema, undefined, 2))
|
||||
writeFileSync(join(...markdownFilePath), docs)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"include": [
|
||||
"src/**/*"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"strict": true,
|
||||
"lib": ["ESNext"],
|
||||
"module": "CommonJS",
|
||||
"moduleResolution": "Node",
|
||||
"target": "ESNext",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user