@power-plant/schema 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +221 -1
  2. package/dist/codegen.cjs +1 -77
  3. package/dist/codegen.mjs +1 -78
  4. package/dist/{constants-Cx9_Shfk.d.cts → constants-u7ovYS9e.d.cts} +3 -4
  5. package/dist/constants-u7ovYS9e.d.cts.map +1 -0
  6. package/dist/{constants-Cx9_Shfk.d.mts → constants-u7ovYS9e.d.mts} +3 -4
  7. package/dist/constants-u7ovYS9e.d.mts.map +1 -0
  8. package/dist/constants.cjs +1 -1
  9. package/dist/constants.d.cts +2 -2
  10. package/dist/constants.d.mts +2 -2
  11. package/dist/constants.mjs +1 -1
  12. package/dist/extract.cjs +1 -1
  13. package/dist/extract.d.cts +22 -9
  14. package/dist/extract.d.cts.map +1 -1
  15. package/dist/extract.d.mts +22 -9
  16. package/dist/extract.mjs +2 -1
  17. package/dist/extract.mjs.map +1 -0
  18. package/dist/helpers.cjs +1 -1
  19. package/dist/helpers.d.cts +14 -3
  20. package/dist/helpers.d.cts.map +1 -1
  21. package/dist/helpers.d.mts +14 -3
  22. package/dist/helpers.mjs +1 -2
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.d.cts +7 -10
  25. package/dist/index.d.cts.map +1 -1
  26. package/dist/index.d.mts +7 -10
  27. package/dist/index.mjs +1 -1
  28. package/dist/metadata-CsY3HrP2.cjs +77 -0
  29. package/dist/metadata-DIEpQjbq.mjs +78 -0
  30. package/dist/metadata-DIEpQjbq.mjs.map +1 -0
  31. package/dist/metadata.cjs +1 -1
  32. package/dist/metadata.d.cts +65 -2
  33. package/dist/metadata.d.cts.map +1 -1
  34. package/dist/metadata.d.mts +65 -2
  35. package/dist/metadata.mjs +1 -2
  36. package/dist/type-checks.cjs +1 -1
  37. package/dist/type-checks.d.cts +10 -3
  38. package/dist/type-checks.d.cts.map +1 -1
  39. package/dist/type-checks.d.mts +10 -3
  40. package/dist/type-checks.mjs +1 -1
  41. package/dist/types.d.cts +206 -37
  42. package/dist/types.d.cts.map +1 -1
  43. package/dist/types.d.mts +206 -37
  44. package/package.json +19 -64
  45. package/dist/bundle.cjs +0 -1
  46. package/dist/bundle.d.cts +0 -18
  47. package/dist/bundle.d.cts.map +0 -1
  48. package/dist/bundle.d.mts +0 -18
  49. package/dist/bundle.d.mts.map +0 -1
  50. package/dist/bundle.mjs +0 -2
  51. package/dist/bundle.mjs.map +0 -1
  52. package/dist/codegen.mjs.map +0 -1
  53. package/dist/constants-Cx9_Shfk.d.cts.map +0 -1
  54. package/dist/constants-Cx9_Shfk.d.mts.map +0 -1
  55. package/dist/helpers.mjs.map +0 -1
  56. package/dist/metadata.mjs.map +0 -1
  57. package/dist/persistence-B9pzElsC.mjs +0 -2
  58. package/dist/persistence-B9pzElsC.mjs.map +0 -1
  59. package/dist/persistence-CLni2zCP.cjs +0 -1
  60. package/dist/persistence.cjs +0 -1
  61. package/dist/persistence.d.cts +0 -58
  62. package/dist/persistence.d.cts.map +0 -1
  63. package/dist/persistence.d.mts +0 -58
  64. package/dist/persistence.d.mts.map +0 -1
  65. package/dist/persistence.mjs +0 -1
  66. package/dist/resolve.cjs +0 -1
  67. package/dist/resolve.d.cts +0 -45
  68. package/dist/resolve.d.cts.map +0 -1
  69. package/dist/resolve.d.mts +0 -45
  70. package/dist/resolve.d.mts.map +0 -1
  71. package/dist/resolve.mjs +0 -2
  72. package/dist/resolve.mjs.map +0 -1
package/README.md CHANGED
@@ -1,10 +1,65 @@
1
1
  <!-- START header -->
2
+ <!-- prettier-ignore-start -->
3
+ <!-- markdownlint-disable -->
4
+
5
+
6
+ <div align="center">
7
+ <picture>
8
+ <source media="(prefers-color-scheme: dark)" srcset="https://public.storm-cdn.com/power-plant/media/banner-1280x640-dark.gif">
9
+ <source media="(prefers-color-scheme: light)" srcset="https://public.storm-cdn.com/power-plant/media/banner-1280x640-light.gif">
10
+ <img src="https://public.storm-cdn.com/power-plant/media/banner-1280x640-dark.gif" width="100%" alt="Storm Software" />
11
+ </picture>
12
+ </div>
13
+ <br />
14
+
15
+ <div align="center">
16
+ <b>
17
+ <a href="https://stormsoftware.com" target="_blank">Website</a> •
18
+ <a href="https://github.com/storm-software/power-plant" target="_blank">GitHub</a> •
19
+ <a href="https://discord.gg/MQ6YVzakM5">Discord</a> • <a href="https://docs.stormsoftware.com/projects/power-plant/" target="_blank">Docs</a> • <a href="https://stormsoftware.com/contact" target="_blank">Contact</a> •
20
+ <a href="https://github.com/storm-software/power-plant/issues/new?assignees=&labels=bug&template=bug-report.yml&title=Bug Report%3A+">Report a Bug</a>
21
+ </b>
22
+ </div>
23
+
24
+ <br />
25
+
26
+ **☢️ Power Plant** is a collection of TypeScript packages and stand-alone developer tools that center on a single, simple concept: **generate anything from a specification**. The goal of Power Plant is to make it easy for developers to generate code, documentation, and other artifacts from a specification, without having to write any boilerplate code themselves.
27
+
28
+ In the background, Power Plant will also gather metadata about the repository and provide it to LLMs and various other tools. **This allows our favorite AI models to understand more than just the source code, but also its context, the reason why it exists, and its intended usage.**
29
+
30
+ The Power Plant monorepo is a collection of packages that are designed to work together, but in many cases can also be used independently.
31
+
32
+ <br />
33
+
34
+ <h3 align="center">💻 Visit <a href="https://stormsoftware.com" target="_blank">stormsoftware.com</a> to stay up to date with this developer</h3><br />
35
+
36
+ [![Version](https://img.shields.io/badge/version-0.0.2-1fb2a6.svg?style=for-the-badge&color=1fb2a6)](https://docs.stormsoftware.com/projects/power-plant)&nbsp;[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg?style=for-the-badge&logo=commitlint&color=1fb2a6)](http://commitizen.github.io/cz-cli/)&nbsp;![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=for-the-badge&color=1fb2a6)&nbsp;![GitHub Workflow Status (with event)](https://img.shields.io/github/actions/workflow/status/storm-software/power-plant/release.yml?style=for-the-badge&logo=github-actions&color=1fb2a6)
37
+
38
+ <!-- prettier-ignore-start -->
39
+ <!-- markdownlint-disable -->
40
+
41
+ > [!IMPORTANT]
42
+ > This repository, and the apps, libraries, and tools contained within, is still in it's initial development phase. As a result, bugs and issues are expected with it's usage. When the main development phase completes, a proper release will be performed, the packages will be available through NPM (and other distributions), and this message will be removed. However, in the meantime, please feel free to report any issues you may come across.
43
+
44
+ <!-- markdownlint-restore -->
45
+ <!-- prettier-ignore-end -->
46
+
47
+ <div align="center">
48
+ <a href="https://github.com/storm-software/power-plant" target="_blank">
49
+ <b>Be sure to ⭐ this repository on GitHub so you can keep up to date on any daily progress!</b>
50
+ </a>
51
+ </div>
52
+
53
+ <br />
54
+
55
+ <!-- markdownlint-restore -->
56
+ <!-- prettier-ignore-end -->
2
57
 
3
58
  <!-- END header -->
4
59
 
5
60
  # Power Plant - Schema
6
61
 
7
- **Power Plant Schema** allows you to generate anything from a spec.
62
+ A Power Plant utility package to help managing schemas.
8
63
 
9
64
  ## Installing
10
65
 
@@ -41,5 +96,170 @@ Run `nx build schema` to build the library.
41
96
  Run `nx test schema` to execute the unit tests via [Vitest](https://vitest.dev/).
42
97
 
43
98
  <!-- START footer -->
99
+ <!-- prettier-ignore-start -->
100
+ <!-- markdownlint-disable -->
101
+
102
+
103
+ ## Storm Workspaces
104
+
105
+ Storm workspaces are built using
106
+ <a href="https://nx.dev/" target="_blank">Nx</a>, a set of extensible dev tools
107
+ for monorepos, which helps you develop like Google, Facebook, and Microsoft.
108
+ Building on top of Nx, the Open System provides a set of tools and patterns that
109
+ help you scale your monorepo to many teams while keeping the codebase
110
+ maintainable.
111
+
112
+ <div align="right">[ <a href="#table-of-contents">Back to top ▲</a> ]</div>
113
+
114
+ ## Roadmap
115
+
116
+ See the [open issues](https://github.com/storm-software/power-plant/issues) for
117
+ a list of proposed features (and known issues).
118
+
119
+ - [Top Feature Requests](https://github.com/storm-software/power-plant/issues?q=label%3Aenhancement+is%3Aopen+sort%3Areactions-%2B1-desc)
120
+ (Add your votes using the 👍 reaction)
121
+ - [Top Bugs](https://github.com/storm-software/power-plant/issues?q=is%3Aissue+is%3Aopen+label%3Abug+sort%3Areactions-%2B1-desc)
122
+ (Add your votes using the 👍 reaction)
123
+ - [Newest Bugs](https://github.com/storm-software/power-plant/issues?q=is%3Aopen+is%3Aissue+label%3Abug)
124
+
125
+ <div align="right">[ <a href="#table-of-contents">Back to top ▲</a> ]</div>
126
+
127
+ ## Support
128
+
129
+ Reach out to the maintainer at one of the following places:
130
+
131
+ - [Contact](https://stormsoftware.com/contact)
132
+ - [GitHub discussions](https://github.com/storm-software/power-plant/discussions)
133
+ - <support@stormsoftware.com>
134
+
135
+ <div align="right">[ <a href="#table-of-contents">Back to top ▲</a> ]</div>
136
+
137
+ ## License
138
+
139
+ This project is licensed under the **Apache License 2.0**. Feel free to edit and
140
+ distribute this template as you like.
141
+
142
+ See [LICENSE](LICENSE) for more information.
143
+
144
+ <div align="right">[ <a href="#table-of-contents">Back to top ▲</a> ]</div>
145
+
146
+ ## Changelog
147
+
148
+ This project adheres to
149
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Every release, along
150
+ with the migration instructions, is documented in the [CHANGELOG](CHANGELOG.md)
151
+ file
152
+
153
+ <div align="right">[ <a href="#table-of-contents">Back to top ▲</a> ]</div>
154
+
155
+ ## Contributing
156
+
157
+ First off, thanks for taking the time to contribute! Contributions are what
158
+ makes the open-source community such an amazing place to learn, inspire, and
159
+ create. Any contributions you make will benefit everybody else and are **greatly
160
+ appreciated**.
161
+
162
+ Please try to create bug reports that are:
163
+
164
+ - _Reproducible._ Include steps to reproduce the problem.
165
+ - _Specific._ Include as much detail as possible: which version, what
166
+ environment, etc.
167
+ - _Unique._ Do not duplicate existing opened issues.
168
+ - _Scoped to a Single Bug._ One bug per report.
169
+
170
+ Please adhere to this project's [code of conduct](.github/CODE_OF_CONDUCT.md).
171
+
172
+ You can use
173
+ [markdownlint-cli](https://github.com/storm-software/power-plant/markdownlint-cli)
174
+ to check for common markdown style inconsistency.
175
+
176
+ <div align="right">[ <a href="#table-of-contents">Back to top ▲</a> ]</div>
177
+
178
+ ## Contributors
179
+
180
+ Thanks goes to these wonderful people
181
+ ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
182
+
183
+ <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
184
+
185
+ <table>
186
+ <tbody>
187
+ <tr>
188
+ <td align="center" valign="top" width="14.28%"><a href="http://www.sullypat.com/"><img src="https://avatars.githubusercontent.com/u/99053093?v=4?s=100" width="100px;" alt="Patrick Sullivan"/><br /><sub><b>Patrick Sullivan</b></sub></a><br /><a href="#design-sullivanpj" title="Design">🎨</a> <a href="https://github.com/storm-software/power-plant/commits?author=sullivanpj" title="Code">💻</a> <a href="#tool-sullivanpj" title="Tools">🔧</a> <a href="https://github.com/storm-software/power-plant/commits?author=sullivanpj" title="Documentation">📖</a> <a href="https://github.com/storm-software/power-plant/commits?author=sullivanpj" title="Tests">⚠️</a></td>
189
+ <td align="center" valign="top" width="14.28%"><a href="https://tylerbenning.com/"><img src="https://avatars.githubusercontent.com/u/7265547?v=4?s=100" width="100px;" alt="Tyler Benning"/><br /><sub><b>Tyler Benning</b></sub></a><br /><a href="#design-tbenning" title="Design">🎨</a></td>
190
+ <td align="center" valign="top" width="14.28%"><a href="http://stormsoftware.com"><img src="https://avatars.githubusercontent.com/u/149802440?v=4?s=100" width="100px;" alt="Stormie"/><br /><sub><b>Stormie</b></sub></a><br /><a href="#maintenance-stormie-bot" title="Maintenance">🚧</a></td>
191
+ </tr>
192
+ </tbody>
193
+ <tfoot>
194
+ <tr>
195
+ <td align="center" size="13px" colspan="7">
196
+ <img src="https://raw.githubusercontent.com/all-contributors/all-contributors-cli/1b8533af435da9854653492b1327a23a4dbd0a10/assets/logo-small.svg" alt="All Contributors">
197
+ <a href="https://all-contributors.js.org/docs/en/bot/usage">Add your contributions</a>
198
+ </img>
199
+ </td>
200
+ </tr>
201
+ </tfoot>
202
+ </table>
203
+
204
+ <!-- ALL-CONTRIBUTORS-LIST:END -->
205
+
206
+ This project follows the
207
+ [all-contributors](https://github.com/all-contributors/all-contributors)
208
+ specification. Contributions of any kind welcome!
209
+
210
+ <div align="right">[ <a href="#table-of-contents">Back to top ▲</a> ]</div>
211
+ <br />
212
+
213
+ <hr />
214
+ <br />
215
+
216
+ <div align="center">
217
+ <picture>
218
+ <source media="(prefers-color-scheme: dark)" srcset="https://public.storm-cdn.com/storm-software/media/banner-1280x320-dark.webp">
219
+ <source media="(prefers-color-scheme: light)" srcset="https://public.storm-cdn.com/storm-software/media/banner-1280x320-light.webp">
220
+ <img src="https://public.storm-cdn.com/storm-software/media/banner-1280x320-dark.webp" width="100%" alt="Storm Software" />
221
+ </picture>
222
+ </div>
223
+ <br />
224
+
225
+ <div align="center">
226
+ <a href="https://stormsoftware.com" target="_blank">Website</a> • <a href="https://stormsoftware.com/contact" target="_blank">Contact</a> • <a href="https://linkedin.com/in/patrick-sullivan-865526b0" target="_blank">LinkedIn</a> • <a href="https://medium.com/@pat.joseph.sullivan" target="_blank">Medium</a> • <a href="https://github.com/storm-software" target="_blank">GitHub</a> • <a href="https://keybase.io/sullivanp" target="_blank">OpenPGP Key</a>
227
+ </div>
228
+
229
+ <div align="center">
230
+ <b>Fingerprint:</b> 1BD2 7192 7770 2549 F4C9 F238 E6AD C420 DA5C 4C2D
231
+ </div>
232
+ <br />
233
+
234
+ Storm Software is an open source software development organization and creator
235
+ of Acidic, StormStack and StormCloud.
236
+
237
+ Our mission is to make software development more accessible. Our ideal future is
238
+ one where anyone can create software without years of prior development
239
+ experience serving as a barrier to entry. We hope to achieve this via LLMs,
240
+ Generative AI, and intuitive, high-level data modeling/programming languages.
241
+
242
+ Join us on [Discord](https://discord.gg/MQ6YVzakM5) to chat with the team,
243
+ receive release notifications, ask questions, and get involved.
244
+
245
+ If this sounds interesting, and you would like to help us in creating the next
246
+ generation of development tools, please reach out on our
247
+ [website](https://stormsoftware.com/contact) or join our
248
+ [Slack channel](https://join.slack.com/t/storm-software/shared_invite/zt-2gsmk04hs-i6yhK_r6urq0dkZYAwq2pA)!
249
+
250
+ <br />
251
+
252
+ <div align="center"><a href="https://stormsoftware.com" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://public.storm-cdn.com/storm-software/icons/circle-dark.webp"><source media="(prefers-color-scheme: light)" srcset="https://public.storm-cdn.com/storm-software/icons/circle-light.webp"><img src="https://public.storm-cdn.com/storm-software/icons/circle-dark.webp" width="200px" alt="Storm Software" /></picture></a></div>
253
+ <br />
254
+ <div align="center"><a href="https://stormsoftware.com" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://public.storm-cdn.com/misc/text/visit-us-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://public.storm-cdn.com/misc/text/visit-us-light.png"><img src="https://public.storm-cdn.com/misc/text/visit-us-dark.png" height="90px" alt="Visit us at stormsoftware.com" /></picture></a></div>
255
+ <br />
256
+
257
+ <div align="right">[ <a href="#table-of-contents">Back to top ▲</a> ]</div>
258
+ <br />
259
+ <br />
260
+
261
+
262
+ <!-- markdownlint-restore -->
263
+ <!-- prettier-ignore-end -->
44
264
 
45
265
  <!-- END footer -->
package/dist/codegen.cjs CHANGED
@@ -1,77 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./type-checks.cjs"),t=require("./metadata.cjs"),n=require("./helpers.cjs");let r=require("@stryke/type-checks"),i=require("@stryke/type-checks/is-set-string"),a=require("@stryke/string-format/list"),o=require("@stryke/convert/to-bool"),s=require("@stryke/string-format/camel-case"),c=require("@stryke/type-checks/is-boolean"),l=require("@stryke/type-checks/is-null"),u=require("@stryke/type-checks/is-number"),d=require("@stryke/type-checks/is-undefined");function f(e,t){return(0,d.isUndefined)(e)?`undefined`:(0,l.isNull)(e)?`null`:t===`boolean`||(0,c.isBoolean)(e)?String((0,o.toBool)(e)):t===`number`||(0,u.isNumber)(e)?Number.parseFloat(String(e)).toLocaleString(void 0,{maximumFractionDigits:20}):t===`integer`?Number.parseInt(String(e)).toLocaleString():t===`string`||t===`object`||t===`array`?JSON.stringify(e):String(e)}function p(r){if(!r)return`unknown`;if(typeof r==`boolean`)return r?`unknown`:`never`;if(e.isJsonSchemaObject(r)&&(0,i.isSetString)(r.name))return r.name;let a=r;if((0,i.isSetString)(a.$ref))return/^#\/(?:definitions|\$defs)\/(.+)$/.exec(a.$ref)?.[1]??a.$ref;if(e.isJsonSchemaLiteral(r)&&!(0,d.isUndefined)(r.const))return JSON.stringify((0,i.isSetString)(r.const)?r.const.replaceAll(/^['"`]|['"`]$/g,``):r.const);let o=t.getPrimarySchemaType(r);if(o)return o===`integer`||o===`number`?`number`:o;if(a.type===`array`&&Array.isArray(a.enum))return a.enum.map(e=>JSON.stringify(e)).join(` | `);if(a.const!==void 0)return JSON.stringify(a.const);if(a.type===`array`||a.items)return`${p(Array.isArray(a.items)?a.items[0]:a.items)}[]`;if(a.type===`object`||a.properties||a.additionalProperties){if(e.isJsonSchema(a.additionalProperties))return`{ [key: string]: ${p(a.additionalProperties)} }`;if(e.isJsonSchemaObject(a)){let e=a.required??[];return`{ ${n.getPropertiesList(a).map(t=>{let r=!e.includes(t.name)||n.isSchemaNullable(t)?`${e.includes(t.name)?``:`?`}${n.isSchemaNullable(t)?` | null`:``}`:``;return`${t.name}${r}: ${p(t)}`}).join(`;
2
- `)} }`}}return a.oneOf||a.anyOf?(a.oneOf??a.anyOf??[]).map(e=>p(e)).join(` | `):a.allOf?`object`:`unknown`}function m(e){return(0,l.isNull)(e)?`null`:(0,c.isBoolean)(e)?`boolean`:(0,r.isInteger)(e)?`integer`:(0,u.isNumber)(e)?`number`:(0,r.isString)(e)?`string`:(0,r.isObject)(e)?`object`:Array.isArray(e)?`array`:void 0}function h(e){return/^#\/(?:definitions|\$defs)\/(.+)$/.exec(e)?.[1]}function g(e){let t=e.replace(/[^\w$]/gu,`_`);return`parse_${/^\d/u.test(t)?`_${t}`:t}`}function _(e){let t=e.type;return Array.isArray(t)?[...t]:t?[t]:[]}function v(e,t){return`${e} + ${JSON.stringify(t)}`}function y(o,c={}){let l=o,u=typeof l==`boolean`?{}:{...l.definitions,...l.$defs},d={};function f(e){let t=d[e]??0;return d[e]=t+1,`${e}${t>0?`${t}`:``}`}function m(e,t,r,a,o=`errors`){if(typeof e==`boolean`)return e?[`${a} = ${t};`]:[`${o}.push({ path: ${r}, failure: "No value is allowed at this location" });`,`${a} = ${t};`];if((0,i.isSetString)(e.$ref)){let n=h(e.$ref);return n&&n in u?[`${a} = ${g(n)}(${t}, ${r}, ${o});`]:[`${a} = ${t};`]}let l=f(e.name?`${(0,s.camelCase)(e.name)}Value`:`value`),d=f(e.name?`${(0,s.camelCase)(e.name)}Path`:`path`),p=[`const ${l} = ${t};`,`const ${d} = ${r};`];return!c.ignoreDefaults&&e.default!==void 0?(p.push(`if (${l} === undefined${e.type===`string`?` || ${l} === ""`:e.type===`number`||e.type===`integer`?` || Number.isNaN(${l})`:``}) {`,` ${a} = ${JSON.stringify(e.default)};`,`} else {`),n.isSchemaNullable(e)?(p.push(` if (${l} === null) {`,` ${a} = null;`,` } else {`),p.push(...y(e,l,d,a,o)),p.push(` }`)):p.push(...y(e,l,d,a,o)),p.push(`}`),p):(p.push(`if (${l} === undefined) {`,` ${o}.push({ path: ${d}, failure: "A value is required" });`,` ${a} = ${l};`,`} else {`),n.isSchemaNullable(e)?(p.push(` if (${l} === null) {`,` ${a} = null;`,` } else {`),p.push(...y(e,l,d,a,o)),p.push(` }`)):p.push(...y(e,l,d,a,o)),p.push(`}`),p)}function y(e,r,i,o,c){let l=[];if(e.const!==void 0){let t=JSON.stringify(e.const);return l.push(`if (${e.type===`string`?r:`JSON.stringify(${r})`} !== ${t}) { ${c}.push({ path: ${i}, failure: "Expected the constant value " + ${t} }); }`,`${o} = ${t};`),l}if(Array.isArray(e.enum)){let t=JSON.stringify(e.enum);return l.push(`if (!${t}.some(allowed => JSON.stringify(allowed) === JSON.stringify(${r}))) { ${c}.push({ path: ${i}, failure: \`Expected one of: ${(0,a.list)(e.enum.map(e=>JSON.stringify(e)),{conjunction:`or`})}, instead received: \${JSON.stringify(${r})}\` }); }`,`${o} = ${r};`),l}if(Array.isArray(e.oneOf)||Array.isArray(e.anyOf)){let t=e.oneOf??e.anyOf??[],n=f(e.name?`${(0,s.camelCase)(e.name)}Matched`:`matched`);l.push(`let ${n} = false;`);for(let a of t){let t=f(e.name?`${(0,s.camelCase)(e.name)}BranchErrors`:`branchErrors`),c=f(e.name?`${(0,s.camelCase)(e.name)}BranchResult`:`branchResult`);l.push(`if (!${n}) {`),l.push(` const ${t}: { path: string; failure: string }[] = [];`,` let ${c};`),l.push(...m(a,r,i,c,t)),l.push(` if (${t}.length === 0) {`,` ${o} = ${c};`,` ${n} = true;`,` }`,`}`)}return l.push(`if (!${n}) {`,` ${c}.push({ path: ${i}, failure: \`The provided value \${JSON.stringify(${r})} does not match the allowed schemas\` });`,` ${o} = ${r};`,`}`),l}if(Array.isArray(e.allOf)){let{allOf:t,...a}=e,s=n.merge(a,...t);return l.push(...m(s,r,i,o,c)),l}let u=_(e);switch(t.getPrimarySchemaType(e)??u.find(e=>e!==`null`)??(e.properties?`object`:e.items?`array`:void 0)){case`object`:l.push(...b(e,r,i,o,c));break;case`array`:l.push(...x(e,r,i,o,c));break;case`string`:l.push(`if (typeof ${r} === "string") {`,` ${o} = ${r};`,`} else if (typeof ${r} === "number" || typeof ${r} === "boolean") {`,` ${o} = String(${r});`,`} else {`,` ${c}.push({ path: ${i}, failure: "Expected a string value" });`,` ${o} = ${r};`,`}`);break;case`integer`:l.push(`if (typeof ${r} === "number" && Number.isInteger(${r})) {`,` ${o} = ${r};`,`} else if (typeof ${r} === "string" && ${r}.trim() !== "" && Number.isInteger(Number(${r}))) {`,` ${o} = Number(${r});`,`} else if (typeof ${r} === "boolean") {`,` ${o} = ${r} ? 1 : 0;`,`} else {`,` ${c}.push({ path: ${i}, failure: "Expected an integer value" });`,` ${o} = ${r};`,`}`);break;case`number`:l.push(`if (typeof ${r} === "number") {`,` ${o} = ${r};`,`} else if (typeof ${r} === "string" && ${r}.trim() !== "" && !Number.isNaN(Number(${r}))) {`,` ${o} = Number(${r});`,`} else if (typeof ${r} === "boolean") {`,` ${o} = ${r} ? 1 : 0;`,`} else {`,` ${c}.push({ path: ${i}, failure: "Expected a number value" });`,` ${o} = ${r};`,`}`);break;case`boolean`:l.push(`if (typeof ${r} === "boolean") {`,` ${o} = ${r};`,`} else if ((typeof ${r} === "string" && (${r}.toLowerCase() === "true" || ${r}.toLowerCase() === "t" || ${r}.toLowerCase() === "yes" || ${r}.toLowerCase() === "y" || (!Number.isNaN(Number.parseInt(${r})) && Number.parseInt(${r}) > 0))) || (typeof ${r} === "number" && ${r} > 0)) {`,` ${o} = true;`,`} else if ((typeof ${r} === "string" && (${r}.toLowerCase() === "false" || ${r}.toLowerCase() === "f" || ${r}.toLowerCase() === "no" || ${r}.toLowerCase() === "n" || (!Number.isNaN(Number.parseInt(${r})) && Number.parseInt(${r}) <= 0))) || (typeof ${r} === "number" && ${r} <= 0)) {`,` ${o} = false;`,`} else {`,` ${c}.push({ path: ${i}, failure: "Expected a boolean value" });`,` ${o} = ${r};`,`}`);break;case`null`:l.push(`if (${r} === null) {`,` ${o} = null;`,`} else {`,` ${c}.push({ path: ${i}, failure: "Expected a null value" });`,` ${o} = ${r};`,`}`);break;case void 0:default:l.push(`${o} = ${r};`);break}return l}function b(t,i,a,o,c){let l=p(t),u=[`if (typeof ${i} !== "object" || ${i} === null || Array.isArray(${i})) {`,` ${c}.push({ path: ${a}, failure: "Expected an object value" });`,` ${o} = ${i};`,`} else {`],d=f(l||t.name?`${(0,s.camelCase)(l||t.name)}Schema`:`schema`);if(u.push(`const ${d} = {} as Record<string, any>`),e.isJsonSchemaObject(t)){let o=new Set;for(let l of n.getPropertiesList(t)){o.add(l.name);let t;(0,r.isSetArray)(l.alias)?(t=`(${l.alias.map(e=>`${i}[${JSON.stringify(e)}]`).join(` ${e.isJsonSchemaString(l)?`||`:`??`} `)} ${e.isJsonSchemaString(l)?`||`:`??`} ${i}[${JSON.stringify(l.name)}])`,l.alias.forEach(e=>o.add(e))):t=`${i}[${JSON.stringify(l.name)}]`;let n=v(a,`.${l.name}`),p=f(l.name?`${(0,s.camelCase)(l.name)}Property`:`property`),h=l.default===void 0?l.required?`${c}.push({ path: ${n}, failure: "Required property is missing" });`:``:`${d}[${JSON.stringify(l.name)}] = ${JSON.stringify(l.default)};`;u.push(` if (${t} !== undefined) {`,` let ${p};`),u.push(...m(l,t,n,p,c)),u.push(`${d}[${JSON.stringify(l.name)}] = ${p};`),h?u.push(`} else { ${h} }`):u.push(`}`)}let p=t.additionalProperties;if(e.isJsonSchema(p)){let e=f(l||t.name?`${(0,s.camelCase)(l||t.name)}AdditionalProperties`:`additionalProperties`);u.push(` for (const key of Object.keys(${i})) {`,` if (${JSON.stringify([...o])}.includes(key)) { continue; }`,` let ${e};`),u.push(...m(p,`${i}[key]`,`${a} + "." + key`,e,c)),u.push(`${d}[key] = ${e};`,`}`)}else p!==!1&&u.push(` for (const key of Object.keys(${i})) {`,` if (${JSON.stringify([...o])}.includes(key)) { continue; }`,` ${d}[key] = ${i}[key];`,`}`)}return u.push(`${o} = ${d};`,`}`),u}function x(e,t,n,r,i){let a=[`if (!Array.isArray(${t})) {`,` ${i}.push({ path: ${n}, failure: "Expected an array value" });`,` ${r} = ${t};`,`} else {`],o=f(e.name?`${(0,s.camelCase)(e.name)}Array`:`array`);a.push(`const ${o}: unknown[] = [];`);let c=e.prefixItems??(Array.isArray(e.items)?e.items:void 0);if(c){let s=Array.isArray(e.items)?void 0:e.items;return a.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),c.forEach((e,t)=>{a.push(` ${t===0?`if`:`else if`} (index === ${t}) {`),a.push(...m(e,`item`,v(n,`[${t}]`),`itemResult`,i)),a.push(`}`)}),s?(a.push(`else {`),a.push(...m(s,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),a.push(`}`)):a.push(`else { itemResult = item; }`),a.push(` ${o}.push(itemResult);`,` }`,` ${r} = ${o};`,`}`),a}let l=e.items??!0;return a.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),a.push(...m(l,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),a.push(` ${o}.push(itemResult);`,` }`,` ${r} = ${o};`,`}`),a}return`/**
3
- * Parser error constructor function.
4
- */
5
- function ParserError(path, failure) {
6
- this.path = path;
7
- this.failure = failure;
8
- this.name = "ParserError";
9
- this.message = path + ": " + failure;
10
- }
11
- ParserError.prototype = Object.create(Error.prototype);
12
- ParserError.prototype.constructor = ParserError;
13
-
14
- /**
15
- * Represents a parser error with path and failure message.
16
- */
17
- export class ParserError extends Error {
18
- constructor(
19
- public path: string,
20
- public failure: string
21
- ) {
22
- super(\`\${path}: \${failure}\`);
23
- this.name = "ParserError";
24
- }
25
- }
26
-
27
- ${Object.entries(u).map(([e,t])=>`function ${g(e)}(inputValue, inputPath, errors) {
28
- let result;
29
- ${m(t,`inputValue`,`inputPath`,`result`,`errors`).join(`
30
- `)}
31
-
32
- return result;
33
- }`).join(`
34
-
35
- `)}
36
-
37
- /**
38
- * Safely parses an input value into the type described by the JSON Schema, returning an array of validation errors when the value cannot be converted into a valid result.
39
- *
40
- * @remarks
41
- * The parser applies default values for missing properties, coerces primitive values to the declared type, and returns an array of validation errors when the value cannot be converted into a valid result.
42
- *
43
- * @param value - The input value to parse.
44
- * @returns The parsed value conforming to the schema or an array of validation errors.
45
- */
46
- export function parseSafe(inputValue) {
47
- const errors = [];
48
-
49
- let result;
50
- ${m(o,`inputValue`,`"$"`,`result`,`errors`).join(`
51
- `)}
52
-
53
- if (errors.length > 0) {
54
- return errors;
55
- }
56
-
57
- return result;
58
- }
59
-
60
- /**
61
- * Parses an input value into the type described by the JSON Schema, throwing an error if the value cannot be converted into a valid result.
62
- *
63
- * @remarks
64
- * The parser applies default values for missing properties, coerces primitive values to the declared type, and throws an error when the value cannot be converted into a valid result.
65
- *
66
- * @param value - The input value to parse.
67
- * @returns The parsed value conforming to the schema.
68
- * @throws {Error} When the input value cannot be parsed into a valid result according to the schema.
69
- */
70
- export function parse(inputValue) {
71
- const result = parseSafe(inputValue);
72
- if (Array.isArray(result) && result.length > 0 && result.every(error => "path" in error && typeof error.path === "string" && error.path && "failure" in error && typeof error.failure === "string" && error.failure)) {
73
- throw new Error(\`The following validation errors occurred while parsing the input value: \\n\${Object.entries(result.reduce((acc, error) => ((acc[error.path] ??= []).push(error.failure), acc), {})).map(([path, failures]) => \`\${path.replace(/^\\$\\./, "") ? \`\${path.replace(/^\\$\\./, "")}: \\n\` : ""}\${failures.map(failure => \` - \${failure}\`).join("\\n")}\`).join("\\n")}\`);
74
- }
75
-
76
- return result;
77
- }`}exports.generateParserCode=y,exports.getJsonSchemaType=m,exports.stringifyType=p,exports.stringifyValue=f;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./metadata-CsY3HrP2.cjs");exports.generateParserCode=e.f,exports.getJsonSchemaType=e.p,exports.stringifyType=e.m,exports.stringifyValue=e.h;
package/dist/codegen.mjs CHANGED
@@ -1,78 +1 @@
1
- import{isJsonSchema as e,isJsonSchemaLiteral as t,isJsonSchemaObject as n,isJsonSchemaString as r}from"./type-checks.mjs";import{getPrimarySchemaType as i}from"./metadata.mjs";import{getPropertiesList as a,isSchemaNullable as o,merge as s}from"./helpers.mjs";import{isInteger as c,isObject as l,isSetArray as u,isString as d}from"@stryke/type-checks";import{isSetString as f}from"@stryke/type-checks/is-set-string";import{list as p}from"@stryke/string-format/list";import{toBool as m}from"@stryke/convert/to-bool";import{camelCase as h}from"@stryke/string-format/camel-case";import{isBoolean as g}from"@stryke/type-checks/is-boolean";import{isNull as _}from"@stryke/type-checks/is-null";import{isNumber as v}from"@stryke/type-checks/is-number";import{isUndefined as y}from"@stryke/type-checks/is-undefined";function b(e,t){return y(e)?`undefined`:_(e)?`null`:t===`boolean`||g(e)?String(m(e)):t===`number`||v(e)?Number.parseFloat(String(e)).toLocaleString(void 0,{maximumFractionDigits:20}):t===`integer`?Number.parseInt(String(e)).toLocaleString():t===`string`||t===`object`||t===`array`?JSON.stringify(e):String(e)}function x(r){if(!r)return`unknown`;if(typeof r==`boolean`)return r?`unknown`:`never`;if(n(r)&&f(r.name))return r.name;let s=r;if(f(s.$ref))return/^#\/(?:definitions|\$defs)\/(.+)$/.exec(s.$ref)?.[1]??s.$ref;if(t(r)&&!y(r.const))return JSON.stringify(f(r.const)?r.const.replaceAll(/^['"`]|['"`]$/g,``):r.const);let c=i(r);if(c)return c===`integer`||c===`number`?`number`:c;if(s.type===`array`&&Array.isArray(s.enum))return s.enum.map(e=>JSON.stringify(e)).join(` | `);if(s.const!==void 0)return JSON.stringify(s.const);if(s.type===`array`||s.items)return`${x(Array.isArray(s.items)?s.items[0]:s.items)}[]`;if(s.type===`object`||s.properties||s.additionalProperties){if(e(s.additionalProperties))return`{ [key: string]: ${x(s.additionalProperties)} }`;if(n(s)){let e=s.required??[];return`{ ${a(s).map(t=>{let n=!e.includes(t.name)||o(t)?`${e.includes(t.name)?``:`?`}${o(t)?` | null`:``}`:``;return`${t.name}${n}: ${x(t)}`}).join(`;
2
- `)} }`}}return s.oneOf||s.anyOf?(s.oneOf??s.anyOf??[]).map(e=>x(e)).join(` | `):s.allOf?`object`:`unknown`}function S(e){return _(e)?`null`:g(e)?`boolean`:c(e)?`integer`:v(e)?`number`:d(e)?`string`:l(e)?`object`:Array.isArray(e)?`array`:void 0}function C(e){return/^#\/(?:definitions|\$defs)\/(.+)$/.exec(e)?.[1]}function w(e){let t=e.replace(/[^\w$]/gu,`_`);return`parse_${/^\d/u.test(t)?`_${t}`:t}`}function T(e){let t=e.type;return Array.isArray(t)?[...t]:t?[t]:[]}function E(e,t){return`${e} + ${JSON.stringify(t)}`}function D(t,c={}){let l=t,d=typeof l==`boolean`?{}:{...l.definitions,...l.$defs},m={};function g(e){let t=m[e]??0;return m[e]=t+1,`${e}${t>0?`${t}`:``}`}function _(e,t,n,r,i=`errors`){if(typeof e==`boolean`)return e?[`${r} = ${t};`]:[`${i}.push({ path: ${n}, failure: "No value is allowed at this location" });`,`${r} = ${t};`];if(f(e.$ref)){let a=C(e.$ref);return a&&a in d?[`${r} = ${w(a)}(${t}, ${n}, ${i});`]:[`${r} = ${t};`]}let a=g(e.name?`${h(e.name)}Value`:`value`),s=g(e.name?`${h(e.name)}Path`:`path`),l=[`const ${a} = ${t};`,`const ${s} = ${n};`];return!c.ignoreDefaults&&e.default!==void 0?(l.push(`if (${a} === undefined${e.type===`string`?` || ${a} === ""`:e.type===`number`||e.type===`integer`?` || Number.isNaN(${a})`:``}) {`,` ${r} = ${JSON.stringify(e.default)};`,`} else {`),o(e)?(l.push(` if (${a} === null) {`,` ${r} = null;`,` } else {`),l.push(...v(e,a,s,r,i)),l.push(` }`)):l.push(...v(e,a,s,r,i)),l.push(`}`),l):(l.push(`if (${a} === undefined) {`,` ${i}.push({ path: ${s}, failure: "A value is required" });`,` ${r} = ${a};`,`} else {`),o(e)?(l.push(` if (${a} === null) {`,` ${r} = null;`,` } else {`),l.push(...v(e,a,s,r,i)),l.push(` }`)):l.push(...v(e,a,s,r,i)),l.push(`}`),l)}function v(e,t,n,r,a){let o=[];if(e.const!==void 0){let i=JSON.stringify(e.const);return o.push(`if (${e.type===`string`?t:`JSON.stringify(${t})`} !== ${i}) { ${a}.push({ path: ${n}, failure: "Expected the constant value " + ${i} }); }`,`${r} = ${i};`),o}if(Array.isArray(e.enum)){let i=JSON.stringify(e.enum);return o.push(`if (!${i}.some(allowed => JSON.stringify(allowed) === JSON.stringify(${t}))) { ${a}.push({ path: ${n}, failure: \`Expected one of: ${p(e.enum.map(e=>JSON.stringify(e)),{conjunction:`or`})}, instead received: \${JSON.stringify(${t})}\` }); }`,`${r} = ${t};`),o}if(Array.isArray(e.oneOf)||Array.isArray(e.anyOf)){let i=e.oneOf??e.anyOf??[],s=g(e.name?`${h(e.name)}Matched`:`matched`);o.push(`let ${s} = false;`);for(let a of i){let i=g(e.name?`${h(e.name)}BranchErrors`:`branchErrors`),c=g(e.name?`${h(e.name)}BranchResult`:`branchResult`);o.push(`if (!${s}) {`),o.push(` const ${i}: { path: string; failure: string }[] = [];`,` let ${c};`),o.push(..._(a,t,n,c,i)),o.push(` if (${i}.length === 0) {`,` ${r} = ${c};`,` ${s} = true;`,` }`,`}`)}return o.push(`if (!${s}) {`,` ${a}.push({ path: ${n}, failure: \`The provided value \${JSON.stringify(${t})} does not match the allowed schemas\` });`,` ${r} = ${t};`,`}`),o}if(Array.isArray(e.allOf)){let{allOf:i,...c}=e,l=s(c,...i);return o.push(..._(l,t,n,r,a)),o}let c=T(e);switch(i(e)??c.find(e=>e!==`null`)??(e.properties?`object`:e.items?`array`:void 0)){case`object`:o.push(...y(e,t,n,r,a));break;case`array`:o.push(...b(e,t,n,r,a));break;case`string`:o.push(`if (typeof ${t} === "string") {`,` ${r} = ${t};`,`} else if (typeof ${t} === "number" || typeof ${t} === "boolean") {`,` ${r} = String(${t});`,`} else {`,` ${a}.push({ path: ${n}, failure: "Expected a string value" });`,` ${r} = ${t};`,`}`);break;case`integer`:o.push(`if (typeof ${t} === "number" && Number.isInteger(${t})) {`,` ${r} = ${t};`,`} else if (typeof ${t} === "string" && ${t}.trim() !== "" && Number.isInteger(Number(${t}))) {`,` ${r} = Number(${t});`,`} else if (typeof ${t} === "boolean") {`,` ${r} = ${t} ? 1 : 0;`,`} else {`,` ${a}.push({ path: ${n}, failure: "Expected an integer value" });`,` ${r} = ${t};`,`}`);break;case`number`:o.push(`if (typeof ${t} === "number") {`,` ${r} = ${t};`,`} else if (typeof ${t} === "string" && ${t}.trim() !== "" && !Number.isNaN(Number(${t}))) {`,` ${r} = Number(${t});`,`} else if (typeof ${t} === "boolean") {`,` ${r} = ${t} ? 1 : 0;`,`} else {`,` ${a}.push({ path: ${n}, failure: "Expected a number value" });`,` ${r} = ${t};`,`}`);break;case`boolean`:o.push(`if (typeof ${t} === "boolean") {`,` ${r} = ${t};`,`} else if ((typeof ${t} === "string" && (${t}.toLowerCase() === "true" || ${t}.toLowerCase() === "t" || ${t}.toLowerCase() === "yes" || ${t}.toLowerCase() === "y" || (!Number.isNaN(Number.parseInt(${t})) && Number.parseInt(${t}) > 0))) || (typeof ${t} === "number" && ${t} > 0)) {`,` ${r} = true;`,`} else if ((typeof ${t} === "string" && (${t}.toLowerCase() === "false" || ${t}.toLowerCase() === "f" || ${t}.toLowerCase() === "no" || ${t}.toLowerCase() === "n" || (!Number.isNaN(Number.parseInt(${t})) && Number.parseInt(${t}) <= 0))) || (typeof ${t} === "number" && ${t} <= 0)) {`,` ${r} = false;`,`} else {`,` ${a}.push({ path: ${n}, failure: "Expected a boolean value" });`,` ${r} = ${t};`,`}`);break;case`null`:o.push(`if (${t} === null) {`,` ${r} = null;`,`} else {`,` ${a}.push({ path: ${n}, failure: "Expected a null value" });`,` ${r} = ${t};`,`}`);break;case void 0:default:o.push(`${r} = ${t};`);break}return o}function y(t,i,o,s,c){let l=x(t),d=[`if (typeof ${i} !== "object" || ${i} === null || Array.isArray(${i})) {`,` ${c}.push({ path: ${o}, failure: "Expected an object value" });`,` ${s} = ${i};`,`} else {`],f=g(l||t.name?`${h(l||t.name)}Schema`:`schema`);if(d.push(`const ${f} = {} as Record<string, any>`),n(t)){let n=new Set;for(let e of a(t)){n.add(e.name);let t;u(e.alias)?(t=`(${e.alias.map(e=>`${i}[${JSON.stringify(e)}]`).join(` ${r(e)?`||`:`??`} `)} ${r(e)?`||`:`??`} ${i}[${JSON.stringify(e.name)}])`,e.alias.forEach(e=>n.add(e))):t=`${i}[${JSON.stringify(e.name)}]`;let a=E(o,`.${e.name}`),s=g(e.name?`${h(e.name)}Property`:`property`),l=e.default===void 0?e.required?`${c}.push({ path: ${a}, failure: "Required property is missing" });`:``:`${f}[${JSON.stringify(e.name)}] = ${JSON.stringify(e.default)};`;d.push(` if (${t} !== undefined) {`,` let ${s};`),d.push(..._(e,t,a,s,c)),d.push(`${f}[${JSON.stringify(e.name)}] = ${s};`),l?d.push(`} else { ${l} }`):d.push(`}`)}let s=t.additionalProperties;if(e(s)){let e=g(l||t.name?`${h(l||t.name)}AdditionalProperties`:`additionalProperties`);d.push(` for (const key of Object.keys(${i})) {`,` if (${JSON.stringify([...n])}.includes(key)) { continue; }`,` let ${e};`),d.push(..._(s,`${i}[key]`,`${o} + "." + key`,e,c)),d.push(`${f}[key] = ${e};`,`}`)}else s!==!1&&d.push(` for (const key of Object.keys(${i})) {`,` if (${JSON.stringify([...n])}.includes(key)) { continue; }`,` ${f}[key] = ${i}[key];`,`}`)}return d.push(`${s} = ${f};`,`}`),d}function b(e,t,n,r,i){let a=[`if (!Array.isArray(${t})) {`,` ${i}.push({ path: ${n}, failure: "Expected an array value" });`,` ${r} = ${t};`,`} else {`],o=g(e.name?`${h(e.name)}Array`:`array`);a.push(`const ${o}: unknown[] = [];`);let s=e.prefixItems??(Array.isArray(e.items)?e.items:void 0);if(s){let c=Array.isArray(e.items)?void 0:e.items;return a.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),s.forEach((e,t)=>{a.push(` ${t===0?`if`:`else if`} (index === ${t}) {`),a.push(..._(e,`item`,E(n,`[${t}]`),`itemResult`,i)),a.push(`}`)}),c?(a.push(`else {`),a.push(..._(c,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),a.push(`}`)):a.push(`else { itemResult = item; }`),a.push(` ${o}.push(itemResult);`,` }`,` ${r} = ${o};`,`}`),a}let c=e.items??!0;return a.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),a.push(..._(c,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),a.push(` ${o}.push(itemResult);`,` }`,` ${r} = ${o};`,`}`),a}return`/**
3
- * Parser error constructor function.
4
- */
5
- function ParserError(path, failure) {
6
- this.path = path;
7
- this.failure = failure;
8
- this.name = "ParserError";
9
- this.message = path + ": " + failure;
10
- }
11
- ParserError.prototype = Object.create(Error.prototype);
12
- ParserError.prototype.constructor = ParserError;
13
-
14
- /**
15
- * Represents a parser error with path and failure message.
16
- */
17
- export class ParserError extends Error {
18
- constructor(
19
- public path: string,
20
- public failure: string
21
- ) {
22
- super(\`\${path}: \${failure}\`);
23
- this.name = "ParserError";
24
- }
25
- }
26
-
27
- ${Object.entries(d).map(([e,t])=>`function ${w(e)}(inputValue, inputPath, errors) {
28
- let result;
29
- ${_(t,`inputValue`,`inputPath`,`result`,`errors`).join(`
30
- `)}
31
-
32
- return result;
33
- }`).join(`
34
-
35
- `)}
36
-
37
- /**
38
- * Safely parses an input value into the type described by the JSON Schema, returning an array of validation errors when the value cannot be converted into a valid result.
39
- *
40
- * @remarks
41
- * The parser applies default values for missing properties, coerces primitive values to the declared type, and returns an array of validation errors when the value cannot be converted into a valid result.
42
- *
43
- * @param value - The input value to parse.
44
- * @returns The parsed value conforming to the schema or an array of validation errors.
45
- */
46
- export function parseSafe(inputValue) {
47
- const errors = [];
48
-
49
- let result;
50
- ${_(t,`inputValue`,`"$"`,`result`,`errors`).join(`
51
- `)}
52
-
53
- if (errors.length > 0) {
54
- return errors;
55
- }
56
-
57
- return result;
58
- }
59
-
60
- /**
61
- * Parses an input value into the type described by the JSON Schema, throwing an error if the value cannot be converted into a valid result.
62
- *
63
- * @remarks
64
- * The parser applies default values for missing properties, coerces primitive values to the declared type, and throws an error when the value cannot be converted into a valid result.
65
- *
66
- * @param value - The input value to parse.
67
- * @returns The parsed value conforming to the schema.
68
- * @throws {Error} When the input value cannot be parsed into a valid result according to the schema.
69
- */
70
- export function parse(inputValue) {
71
- const result = parseSafe(inputValue);
72
- if (Array.isArray(result) && result.length > 0 && result.every(error => "path" in error && typeof error.path === "string" && error.path && "failure" in error && typeof error.failure === "string" && error.failure)) {
73
- throw new Error(\`The following validation errors occurred while parsing the input value: \\n\${Object.entries(result.reduce((acc, error) => ((acc[error.path] ??= []).push(error.failure), acc), {})).map(([path, failures]) => \`\${path.replace(/^\\$\\./, "") ? \`\${path.replace(/^\\$\\./, "")}: \\n\` : ""}\${failures.map(failure => \` - \${failure}\`).join("\\n")}\`).join("\\n")}\`);
74
- }
75
-
76
- return result;
77
- }`}export{D as generateParserCode,S as getJsonSchemaType,x as stringifyType,b as stringifyValue};
78
- //# sourceMappingURL=codegen.mjs.map
1
+ import{f as e,h as t,m as n,p as r}from"./metadata-DIEpQjbq.mjs";export{e as generateParserCode,r as getJsonSchemaType,n as stringifyType,t as stringifyValue};
@@ -1,5 +1,4 @@
1
1
  //#region src/constants.d.ts
2
- declare const VALID_SOURCE_FILE_EXTENSIONS: string[];
3
2
  declare const JsonSchemaTypeNames: {
4
3
  readonly STRING: "string";
5
4
  readonly NUMBER: "number";
@@ -11,7 +10,7 @@ declare const JsonSchemaTypeNames: {
11
10
  };
12
11
  declare const JSON_SCHEMA_PRIMITIVE_TYPES: readonly ["string", "number", "integer", "boolean", "null"];
13
12
  declare const JSON_SCHEMA_TYPES: readonly ["string", "number", "integer", "boolean", "null", "array", "object"];
14
- declare const JSON_SCHEMA_METADATA_KEYS: ("title" | "description" | "docs" | "examples" | "alias" | "tags" | "deprecated" | "hidden" | "ignore" | "internal" | "runtime" | "readOnly" | "writeOnly")[];
13
+ declare const JSON_SCHEMA_METADATA_KEYS: ("$id" | "$schema" | "$vocabulary" | "$comment" | "$anchor" | "$defs" | "$dynamicRef" | "$dynamicAnchor" | "name" | "version" | "displayName" | "description" | "docs" | "examples" | "alias" | "tags" | "deprecated" | "hidden" | "ignore" | "internal" | "runtime" | "readOnly" | "writeOnly")[];
15
14
  /**
16
15
  * Keywords whose values are a flat record of named JSON Schema fragments.
17
16
  * Each child schema is merged recursively with its counterpart.
@@ -28,5 +27,5 @@ declare const SCHEMA_SINGLE_KEYWORDS: Set<string>;
28
27
  */
29
28
  declare const SCHEMA_ARRAY_CONCAT_KEYWORDS: Set<string>;
30
29
  //#endregion
31
- export { SCHEMA_ARRAY_CONCAT_KEYWORDS as a, VALID_SOURCE_FILE_EXTENSIONS as c, JsonSchemaTypeNames as i, JSON_SCHEMA_PRIMITIVE_TYPES as n, SCHEMA_RECORD_KEYWORDS as o, JSON_SCHEMA_TYPES as r, SCHEMA_SINGLE_KEYWORDS as s, JSON_SCHEMA_METADATA_KEYS as t };
32
- //# sourceMappingURL=constants-Cx9_Shfk.d.cts.map
30
+ export { SCHEMA_ARRAY_CONCAT_KEYWORDS as a, JsonSchemaTypeNames as i, JSON_SCHEMA_PRIMITIVE_TYPES as n, SCHEMA_RECORD_KEYWORDS as o, JSON_SCHEMA_TYPES as r, SCHEMA_SINGLE_KEYWORDS as s, JSON_SCHEMA_METADATA_KEYS as t };
31
+ //# sourceMappingURL=constants-u7ovYS9e.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants-u7ovYS9e.d.cts","names":[],"sources":["../src/constants.ts"],"mappings":";cAoBa,mBAAA;EAAA;;;;;;;;cAUA,2BAAA;AAAA,cAQA,iBAAA;AAAA,cAMA,yBAAA;;;AAdb;;cA4Ca,sBAAA,EAAsB,GAAA;;AAtCzB;AAEV;;cAgDa,sBAAA,EAAsB,GAAA;;AA5CzB;AAEV;;cA2Da,4BAAA,EAA4B,GAAA"}
@@ -1,5 +1,4 @@
1
1
  //#region src/constants.d.ts
2
- declare const VALID_SOURCE_FILE_EXTENSIONS: string[];
3
2
  declare const JsonSchemaTypeNames: {
4
3
  readonly STRING: "string";
5
4
  readonly NUMBER: "number";
@@ -11,7 +10,7 @@ declare const JsonSchemaTypeNames: {
11
10
  };
12
11
  declare const JSON_SCHEMA_PRIMITIVE_TYPES: readonly ["string", "number", "integer", "boolean", "null"];
13
12
  declare const JSON_SCHEMA_TYPES: readonly ["string", "number", "integer", "boolean", "null", "array", "object"];
14
- declare const JSON_SCHEMA_METADATA_KEYS: ("title" | "description" | "docs" | "examples" | "alias" | "tags" | "deprecated" | "hidden" | "ignore" | "internal" | "runtime" | "readOnly" | "writeOnly")[];
13
+ declare const JSON_SCHEMA_METADATA_KEYS: ("$id" | "$schema" | "$vocabulary" | "$comment" | "$anchor" | "$defs" | "$dynamicRef" | "$dynamicAnchor" | "name" | "version" | "displayName" | "description" | "docs" | "examples" | "alias" | "tags" | "deprecated" | "hidden" | "ignore" | "internal" | "runtime" | "readOnly" | "writeOnly")[];
15
14
  /**
16
15
  * Keywords whose values are a flat record of named JSON Schema fragments.
17
16
  * Each child schema is merged recursively with its counterpart.
@@ -28,5 +27,5 @@ declare const SCHEMA_SINGLE_KEYWORDS: Set<string>;
28
27
  */
29
28
  declare const SCHEMA_ARRAY_CONCAT_KEYWORDS: Set<string>;
30
29
  //#endregion
31
- export { SCHEMA_ARRAY_CONCAT_KEYWORDS as a, VALID_SOURCE_FILE_EXTENSIONS as c, JsonSchemaTypeNames as i, JSON_SCHEMA_PRIMITIVE_TYPES as n, SCHEMA_RECORD_KEYWORDS as o, JSON_SCHEMA_TYPES as r, SCHEMA_SINGLE_KEYWORDS as s, JSON_SCHEMA_METADATA_KEYS as t };
32
- //# sourceMappingURL=constants-Cx9_Shfk.d.mts.map
30
+ export { SCHEMA_ARRAY_CONCAT_KEYWORDS as a, JsonSchemaTypeNames as i, JSON_SCHEMA_PRIMITIVE_TYPES as n, SCHEMA_RECORD_KEYWORDS as o, JSON_SCHEMA_TYPES as r, SCHEMA_SINGLE_KEYWORDS as s, JSON_SCHEMA_METADATA_KEYS as t };
31
+ //# sourceMappingURL=constants-u7ovYS9e.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants-u7ovYS9e.d.mts","names":[],"sources":["../src/constants.ts"],"mappings":""}
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=[`ts`,`cts`,`mts`,`tsx`,`js`,`cjs`,`mjs`,`jsx`,`json`,`jsonc`,`json5`,`yaml`,`yml`,`toml`],t={STRING:`string`,NUMBER:`number`,INTEGER:`integer`,BOOLEAN:`boolean`,NULL:`null`,OBJECT:`object`,ARRAY:`array`},n=[t.STRING,t.NUMBER,t.INTEGER,t.BOOLEAN,t.NULL],r=[...n,t.ARRAY,t.OBJECT],i=[`docs`,`deprecated`,`title`,`description`,`examples`,`hidden`,`ignore`,`internal`,`runtime`,`readOnly`,`writeOnly`,`alias`,`tags`],a=new Set([`properties`,`patternProperties`,`$defs`,`definitions`,`dependentSchemas`]),o=new Set([`if`,`then`,`else`,`not`,`contains`,`items`,`additionalProperties`,`unevaluatedProperties`,`propertyNames`,`unevaluatedItems`]),s=new Set([`allOf`,`anyOf`,`oneOf`]);exports.JSON_SCHEMA_METADATA_KEYS=i,exports.JSON_SCHEMA_PRIMITIVE_TYPES=n,exports.JSON_SCHEMA_TYPES=r,exports.JsonSchemaTypeNames=t,exports.SCHEMA_ARRAY_CONCAT_KEYWORDS=s,exports.SCHEMA_RECORD_KEYWORDS=a,exports.SCHEMA_SINGLE_KEYWORDS=o,exports.VALID_SOURCE_FILE_EXTENSIONS=e;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e={STRING:`string`,NUMBER:`number`,INTEGER:`integer`,BOOLEAN:`boolean`,NULL:`null`,OBJECT:`object`,ARRAY:`array`},t=[e.STRING,e.NUMBER,e.INTEGER,e.BOOLEAN,e.NULL],n=[...t,e.ARRAY,e.OBJECT],r=[`$id`,`$schema`,`$vocabulary`,`$comment`,`$anchor`,`$defs`,`$dynamicRef`,`$dynamicAnchor`,`alias`,`deprecated`,`description`,`displayName`,`docs`,`examples`,`hidden`,`ignore`,`internal`,`name`,`readOnly`,`runtime`,`tags`,`version`,`writeOnly`],i=new Set([`properties`,`patternProperties`,`$defs`,`definitions`,`dependentSchemas`]),a=new Set([`if`,`then`,`else`,`not`,`contains`,`items`,`additionalProperties`,`unevaluatedProperties`,`propertyNames`,`unevaluatedItems`]),o=new Set([`allOf`,`anyOf`,`oneOf`]);exports.JSON_SCHEMA_METADATA_KEYS=r,exports.JSON_SCHEMA_PRIMITIVE_TYPES=t,exports.JSON_SCHEMA_TYPES=n,exports.JsonSchemaTypeNames=e,exports.SCHEMA_ARRAY_CONCAT_KEYWORDS=o,exports.SCHEMA_RECORD_KEYWORDS=i,exports.SCHEMA_SINGLE_KEYWORDS=a;
@@ -1,2 +1,2 @@
1
- import { a as SCHEMA_ARRAY_CONCAT_KEYWORDS, c as VALID_SOURCE_FILE_EXTENSIONS, i as JsonSchemaTypeNames, n as JSON_SCHEMA_PRIMITIVE_TYPES, o as SCHEMA_RECORD_KEYWORDS, r as JSON_SCHEMA_TYPES, s as SCHEMA_SINGLE_KEYWORDS, t as JSON_SCHEMA_METADATA_KEYS } from "./constants-Cx9_Shfk.cjs";
2
- export { JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchemaTypeNames, SCHEMA_ARRAY_CONCAT_KEYWORDS, SCHEMA_RECORD_KEYWORDS, SCHEMA_SINGLE_KEYWORDS, VALID_SOURCE_FILE_EXTENSIONS };
1
+ import { a as SCHEMA_ARRAY_CONCAT_KEYWORDS, i as JsonSchemaTypeNames, n as JSON_SCHEMA_PRIMITIVE_TYPES, o as SCHEMA_RECORD_KEYWORDS, r as JSON_SCHEMA_TYPES, s as SCHEMA_SINGLE_KEYWORDS, t as JSON_SCHEMA_METADATA_KEYS } from "./constants-u7ovYS9e.cjs";
2
+ export { JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchemaTypeNames, SCHEMA_ARRAY_CONCAT_KEYWORDS, SCHEMA_RECORD_KEYWORDS, SCHEMA_SINGLE_KEYWORDS };
@@ -1,2 +1,2 @@
1
- import { a as SCHEMA_ARRAY_CONCAT_KEYWORDS, c as VALID_SOURCE_FILE_EXTENSIONS, i as JsonSchemaTypeNames, n as JSON_SCHEMA_PRIMITIVE_TYPES, o as SCHEMA_RECORD_KEYWORDS, r as JSON_SCHEMA_TYPES, s as SCHEMA_SINGLE_KEYWORDS, t as JSON_SCHEMA_METADATA_KEYS } from "./constants-Cx9_Shfk.mjs";
2
- export { JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchemaTypeNames, SCHEMA_ARRAY_CONCAT_KEYWORDS, SCHEMA_RECORD_KEYWORDS, SCHEMA_SINGLE_KEYWORDS, VALID_SOURCE_FILE_EXTENSIONS };
1
+ import { a as SCHEMA_ARRAY_CONCAT_KEYWORDS, i as JsonSchemaTypeNames, n as JSON_SCHEMA_PRIMITIVE_TYPES, o as SCHEMA_RECORD_KEYWORDS, r as JSON_SCHEMA_TYPES, s as SCHEMA_SINGLE_KEYWORDS, t as JSON_SCHEMA_METADATA_KEYS } from "./constants-u7ovYS9e.mjs";
2
+ export { JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchemaTypeNames, SCHEMA_ARRAY_CONCAT_KEYWORDS, SCHEMA_RECORD_KEYWORDS, SCHEMA_SINGLE_KEYWORDS };
@@ -1,2 +1,2 @@
1
- const e=[`ts`,`cts`,`mts`,`tsx`,`js`,`cjs`,`mjs`,`jsx`,`json`,`jsonc`,`json5`,`yaml`,`yml`,`toml`],t={STRING:`string`,NUMBER:`number`,INTEGER:`integer`,BOOLEAN:`boolean`,NULL:`null`,OBJECT:`object`,ARRAY:`array`},n=[t.STRING,t.NUMBER,t.INTEGER,t.BOOLEAN,t.NULL],r=[...n,t.ARRAY,t.OBJECT],i=[`docs`,`deprecated`,`title`,`description`,`examples`,`hidden`,`ignore`,`internal`,`runtime`,`readOnly`,`writeOnly`,`alias`,`tags`],a=new Set([`properties`,`patternProperties`,`$defs`,`definitions`,`dependentSchemas`]),o=new Set([`if`,`then`,`else`,`not`,`contains`,`items`,`additionalProperties`,`unevaluatedProperties`,`propertyNames`,`unevaluatedItems`]),s=new Set([`allOf`,`anyOf`,`oneOf`]);export{i as JSON_SCHEMA_METADATA_KEYS,n as JSON_SCHEMA_PRIMITIVE_TYPES,r as JSON_SCHEMA_TYPES,t as JsonSchemaTypeNames,s as SCHEMA_ARRAY_CONCAT_KEYWORDS,a as SCHEMA_RECORD_KEYWORDS,o as SCHEMA_SINGLE_KEYWORDS,e as VALID_SOURCE_FILE_EXTENSIONS};
1
+ const e={STRING:`string`,NUMBER:`number`,INTEGER:`integer`,BOOLEAN:`boolean`,NULL:`null`,OBJECT:`object`,ARRAY:`array`},t=[e.STRING,e.NUMBER,e.INTEGER,e.BOOLEAN,e.NULL],n=[...t,e.ARRAY,e.OBJECT],r=[`$id`,`$schema`,`$vocabulary`,`$comment`,`$anchor`,`$defs`,`$dynamicRef`,`$dynamicAnchor`,`alias`,`deprecated`,`description`,`displayName`,`docs`,`examples`,`hidden`,`ignore`,`internal`,`name`,`readOnly`,`runtime`,`tags`,`version`,`writeOnly`],i=new Set([`properties`,`patternProperties`,`$defs`,`definitions`,`dependentSchemas`]),a=new Set([`if`,`then`,`else`,`not`,`contains`,`items`,`additionalProperties`,`unevaluatedProperties`,`propertyNames`,`unevaluatedItems`]),o=new Set([`allOf`,`anyOf`,`oneOf`]);export{r as JSON_SCHEMA_METADATA_KEYS,t as JSON_SCHEMA_PRIMITIVE_TYPES,n as JSON_SCHEMA_TYPES,e as JsonSchemaTypeNames,o as SCHEMA_ARRAY_CONCAT_KEYWORDS,i as SCHEMA_RECORD_KEYWORDS,a as SCHEMA_SINGLE_KEYWORDS};
2
2
  //# sourceMappingURL=constants.mjs.map
package/dist/extract.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require("./type-checks.cjs");const e=require("./persistence-CLni2zCP.cjs");exports.bundleReferences=e.o,exports.extract=e.s,exports.extractHash=e.c,exports.extractJsonSchema=e.l,exports.extractResolvedVariant=e.u,exports.extractSchema=e.d,exports.extractSchemaWithSource=e.f,exports.extractSource=e.p,exports.extractVariant=e.m;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./metadata-CsY3HrP2.cjs"),t=require("./type-checks.cjs");let n=require("@stryke/type-checks"),r=require("@stryke/type-checks/is-set-object"),i=require("@stryke/string-format/list"),a=require("@stryke/path/find"),o=require("@stryke/resolve/constants"),s=require("@stryke/convert/extract-file-reference"),c=require("@stryke/hash"),l=require("@stryke/helpers/deep-clone"),u=require("@stryke/json"),d=require("@stryke/resolve/load"),f=require("@stryke/zod"),p=require("@valibot/to-json-schema"),m=require("ts-json-schema-generator/dist/factory/generator.js");const h=`https://power-plant.invalid/`;function g(e){return!(0,r.isSetObject)(e)||!(`schema`in e)||`hash`in e||`variant`in e||`source`in e?!1:Object.keys(e).every(e=>e===`schema`||e===`meta`)}function _(e){return g(e)?{input:e.schema,meta:(0,n.isSetString)(e.meta)?{description:e.meta}:e.meta}:{input:e}}function v(e){return e.endsWith(`#`)?e.slice(0,-1):e}function y(e){let t=e.indexOf(`#`);return t>=0?e.slice(0,t):e}function b(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function x(e){return e.length===0?``:`/${e.map(e=>b(e)).join(`/`)}`}function S(e,t){try{return v(new URL(e,t).toString())}catch{return v(e)}}function C(e,t,i,a,o){if(!(0,r.isSetObject)(e))return;let s=e,c=x(t),l=(0,n.isSetString)(s.$id)?S(s.$id,i):i,u=y(l);if(a.set(l,c),a.set(u,c),(0,n.isSetString)(s.$anchor)&&a.set(`${u}#${s.$anchor}`,c),(0,n.isSetString)(s.$dynamicAnchor)){let e=`${u}#${s.$dynamicAnchor}`;a.set(e,c),o.set(e,`#${s.$dynamicAnchor}`)}for(let[e,n]of Object.entries(s)){if(Array.isArray(n)){n.forEach((n,r)=>{C(n,[...t,e,String(r)],l,a,o)});continue}C(n,[...t,e],l,a,o)}}function w(e,t,i,a,o){if(!(0,r.isSetObject)(e))return;let s=e,c=(0,n.isSetString)(s.$id)?S(s.$id,i):i;if((0,n.isSetString)(s.$ref)){let e=S(s.$ref,c),t=a.get(e)??a.get(y(e));t!==void 0&&(s.$ref=t.length>0?`#${t}`:`#`)}if((0,n.isSetString)(s.$dynamicRef)){let e=S(s.$dynamicRef,c),t=o.get(e);if(t)s.$dynamicRef=t;else{let t=a.get(e)??a.get(y(e));t!==void 0&&(s.$dynamicRef=t.length>0?`#${t}`:`#`)}}for(let[e,n]of Object.entries(s)){if(Array.isArray(n)){n.forEach((n,r)=>{w(n,[...t,e,String(r)],c,a,o)});continue}w(n,[...t,e],c,a,o)}}function T(e){if(!(0,r.isSetObject)(e))return e;let t=(0,l.deepClone)(e),i=(0,n.isSetString)(t.$id)?S(t.$id,h):h,a=new Map,o=new Map;return C(t,[],i,a,o),w(t,[],i,a,o),t}function E(e){if(t.isUntypedSchema(e))return k(e);if((0,r.isSetObject)(e)){if(t.isUntypedInput(e))return A(e);let n=e;if(`$schema`in n&&t.isUntypedSchema(n.$schema))return k(n.$schema)}return e}function D(e){return Array.isArray(e)?e.map(e=>E(e)):e}function O(e){return(0,p.toJsonSchema)(e,{target:`draft-2020-12`})}function k(e){let t=e,i={};for(let[e,a]of Object.entries(t))if(!(e===`tsType`||e===`markdownType`||e===`tags`||e===`args`||e===`resolve`)){if(e===`id`&&(0,n.isSetString)(a)){i.$id=a;continue}if(e===`properties`||e===`patternProperties`||e===`dependentSchemas`||e===`$defs`||e===`definitions`){if(!(0,r.isSetObject)(a)){i[e]=a;continue}i[e]=Object.fromEntries(Object.entries(a).map(([e,t])=>[e,E(t)]));continue}if(e===`items`||e===`contains`||e===`if`||e===`then`||e===`else`||e===`not`||e===`propertyNames`||e===`additionalProperties`||e===`unevaluatedProperties`){i[e]=E(a);continue}if(e===`oneOf`||e===`anyOf`||e===`allOf`){i[e]=D(a);continue}i[e]=a}return i}function A(e){let n=e,i=t.isUntypedSchema(n.$schema)?k(n.$schema):{},a={};for(let[e,i]of Object.entries(n)){if(e.startsWith(`$`)||!(0,r.isSetObject)(i))continue;if(t.isUntypedInput(i)){a[e]=A(i);continue}let n=i;if(`$schema`in n&&t.isUntypedSchema(n.$schema)){a[e]=k(n.$schema);continue}t.isUntypedSchema(i)&&(a[e]=k(i))}if(!t.isJsonSchemaObject(i))throw Error(`Failed to convert untyped input to JSON Schema. The base schema must be a valid JSON Schema object.`);let o={...(0,r.isSetObject)(i.properties)?i.properties:{},...a};return{...i,type:i.type??`object`,...Object.keys(o).length>0?{properties:o}:{}}}function j(e,i){let{input:a}=_(i);if(t.isSchemaWithSource(a)||t.isSchema(a))return(0,c.murmurhash)({variant:e,input:a.schema});if((0,n.isSetString)(a)||typeof a==`boolean`)return(0,c.murmurhash)({variant:e,input:a});if((0,r.isSetObject)(a)){if((0,f.isZod3Type)(a))return(0,c.murmurhash)({variant:e,input:a._def});if((0,u.isStandardJsonSchema)(a))return(0,c.murmurhash)({variant:e,input:a[`~standard`]});if(t.isJsonSchema(a))return(0,c.murmurhash)({variant:e,input:a});if(t.isValibotSchema(a))return(0,c.murmurhash)({variant:e,input:O(a)});if(t.isUntypedInput(a))return(0,c.murmurhash)({variant:e,input:A(a)});if(t.isUntypedSchema(a))return(0,c.murmurhash)({variant:e,input:k(a)})}throw Error(`Failed to create an input hash for the provided schema definition input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, or a reflected Deepkit Type object.`)}function M(e){if((0,r.isSetObject)(e)){if((0,f.isZod3Type)(e))return(0,f.extractJsonSchema)(e,{target:`draft-2020-12`});if(t.isUntypedInputStrict(e))return A(e);if(t.isUntypedSchemaStrict(e))return k(e);if((0,u.isStandardJsonSchema)(e))return e[`~standard`].jsonSchema.input({target:`draft-2020-12`});if(t.isValibotSchema(e))return O(e);if(t.isJsonSchema(e))return e}}function N(e){if((0,r.isSetObject)(e)){if((0,f.isZod3Type)(e))return`zod3`;if(t.isUntypedInputStrict(e)||t.isUntypedSchemaStrict(e))return`untyped`;if((0,u.isStandardJsonSchema)(e))return`standard-schema`;if(t.isJsonSchema(e))return`json-schema`;if(t.isValibotSchema(e))return`valibot`}throw Error(`Failed to determine the variant of the provided schema definition input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, a reflected Deepkit Type object, or an Untyped schema.`)}function P(e){let{input:r}=_(e);return t.isSchemaWithSource(r)||t.isSchema(r)?r.variant:(0,n.isSetString)(r)||t.isFileReference(r)?`file-reference`:N(r)}async function F(e,n){if(t.isSchemaWithSource(e))return e.schema;let r=n??N(e),i;if((r===`zod3`||r===`json-schema`||r===`standard-schema`||r===`untyped`||r===`valibot`)&&(i=M(e)),i)return T(i);throw Error(`Failed to extract a valid schema from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, an untyped schema, or a reflected Deepkit Type object.`)}function I(e,t){if(e===`zod3`)return{hash:j(e,t),variant:`zod3`,schema:t};if(e===`untyped`)return{hash:j(e,t),variant:`untyped`,schema:t};if(e===`standard-schema`)return{hash:j(e,t),variant:`standard-schema`,schema:t};if(e===`json-schema`)return{hash:j(e,t),variant:`json-schema`,schema:t};if(e===`valibot`)return{hash:j(e,t),variant:`valibot`,schema:t};throw Error(`Failed to extract source information from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, an untyped schema, or a reflected Deepkit Type object.`)}async function L(e,t={}){let n=(0,s.extractFileReference)(e);if(!n)throw Error(`Failed to extract a file reference from the provided input. The input must be a string or an object with a "file" property that specifies the file path and optional export name.`);let r=n.export??`*`;try{return(0,m.createGenerator)({path:n.file,type:r,expose:`export`,jsDoc:`extended`,...t}).createSchema(r)}catch(e){throw Error(`Failed to generate a JSON schema for "${n.file}" using the type "${r}". Error: ${e.message}`)}}function R(t,n){let r=t.schema,i=t.meta??{};return i.name=e.u(r,i,n?.name),i.version=e.d(r,i,n?.version),i.id=e.c(r,i),i.displayName=e.o(r,i,n?.displayName),i.description=e.a(`A schema that describes the shape of the {displayName} specification.`,t.schema,i,n?.description),i.examples=e.s(t.schema,i,n?.examples),i.links=e.l(t.schema,i,n?.links),n?.deprecated&&(i.deprecated=n?.deprecated),n?.usage&&(i.usage=n?.usage),n?.tags&&(i.tags=n?.tags),i}async function z(e,n={}){let{input:r,meta:c}=_(e);if(t.isSchemaWithSource(r))return{...r,meta:R(r,c)};if(t.isSchema(r))return{...r,meta:R(r,c),source:{hash:j(`json-schema`,r.schema),variant:`json-schema`,schema:r.schema}};let l,u=c,f=P(r),p=j(f,r);if(f===`file-reference`){let e=(0,s.extractFileReference)(r);if(!e)throw Error(`Failed to extract a valid file reference from the provided input "${JSON.stringify(r)}". Please ensure that the input is correctly formatted as a file reference (e.g. "./schema.ts#MySchema") and that the file exists at the specified path.`);let c=(0,a.findFileExtensionSafe)(e.file);if(c&&!o.VALID_OBJECT_SOURCE_EXTENSIONS.includes(c))throw Error(`The provided schema file input "${e.file}" has an invalid file extension (.${c}). Please ensure that the file has one of the following extensions: ${(0,i.list)(o.VALID_OBJECT_SOURCE_EXTENSIONS,{conjunction:`or`})}.`);let f=await(0,d.loadSafe)(r,n);f??=await L(r,n);let{input:p,meta:m}=_(f);u?m&&(u={...m,...u}):u=m,l=t.isSchemaWithSource(p)?p.source:t.isSchema(p)?{hash:j(`json-schema`,p.schema),variant:`json-schema`,schema:p.schema}:I(N(p),p)}else if([`json-schema`,`standard-schema`,`zod3`,`untyped`,`valibot`,`reflection`].includes(f))l=I(f,r);else throw Error(`Invalid schema definition input "${f}". The variant must be one of "file-reference", "json-schema", "standard-schema", "zod3", "valibot", "untyped", or "reflection".`);let m={variant:f,source:l,schema:await F(l.schema,l.variant),hash:p,meta:{}};return m.meta=R(m,u),m}async function B(e,n={}){let r=_(e),i=r.input;if(t.isSchemaWithSource(i)||t.isSchemaOf(i))return{...i,meta:R(i,r.meta)};let a=await z(e,n);if(a.meta=R(a,r.meta),!a?.schema)throw Error(`Failed to extract a valid schema from the provided input. The input must be a Zod schema, a Valibot schema, any Standard JSON Schema type, a plain JSON Schema object, an untyped schema, or a reflected Deepkit Type object.`);return a}exports.bundleReferences=T,exports.extract=B,exports.extractHash=j,exports.extractJsonSchema=M,exports.extractResolvedVariant=N,exports.extractSchema=F,exports.extractSchemaMeta=R,exports.extractSchemaWithSource=z,exports.extractSource=I,exports.extractTSType=L,exports.extractVariant=P;
@@ -1,5 +1,6 @@
1
- import { BundleOptions } from "./bundle.cjs";
2
- import { ExtractedSchema, JsonSchema, SchemaInput, SchemaInputVariant, SchemaOf, SchemaSource, SchemaSourceInput, SchemaSourceVariant } from "./types.cjs";
1
+ import { ExtractedSchema, InferExtractOptions, JsonSchema, SchemaInput, SchemaInputVariant, SchemaMeta, SchemaMetaInput, SchemaOf, SchemaSource, SchemaSourceInput, SchemaSourceVariant } from "./types.cjs";
2
+ import { InferLoadOptions } from "@stryke/resolve/types";
3
+ import { FileReferenceInput } from "@stryke/types";
3
4
 
4
5
  //#region src/extract.d.ts
5
6
  /**
@@ -53,6 +54,22 @@ declare function extractSchema(input: SchemaSourceInput, variant?: SchemaInputVa
53
54
  * @throws Will throw an error if the provided variant is unsupported.
54
55
  */
55
56
  declare function extractSource(variant: SchemaSourceVariant, input: SchemaSourceInput): SchemaSource;
57
+ /**
58
+ * Resolves a type definition to a JSON Schema. This function passes the provided file reference to ts-json-schema-generator, using the referenced export name as the target type when one is provided.
59
+ *
60
+ * @param input - The type definition to compile. This can be either a string or a {@link FileReference} object.
61
+ * @param options - Optional overrides reserved for API compatibility.
62
+ * @returns A promise that resolves to the generated JSON Schema.
63
+ */
64
+ declare function extractTSType(input: FileReferenceInput, options?: InferLoadOptions<typeof input>): Promise<JsonSchema>;
65
+ /**
66
+ * Extracts and normalizes {@link SchemaMeta | schema metadata} from a given {@link SchemaMetaInput}. This function ensures that the metadata is in a consistent format, converting version numbers to strings and filtering out any invalid or empty tags.
67
+ *
68
+ * @param schema - The schema from which to extract metadata.
69
+ * @param input - The schema metadata input to extract and normalize.
70
+ * @returns The normalized schema metadata.
71
+ */
72
+ declare function extractSchemaMeta<TSpec = any>(schema: SchemaOf<TSpec>, input?: SchemaMetaInput<TSpec>): SchemaMeta<TSpec>;
56
73
  /**
57
74
  * Extracts a JSON Schema from a given schema definition input, which can be a Zod schema, a Valibot schema, any Standard JSON Schema type, a plain JSON Schema object, an untyped schema, or a {@link FileReferenceInput} to an exported TypeScript type definition or any of the previous options. If the input is a {@link FileReferenceInput} (e.g. a file path with an export), the source code will be bundled with [esbuild](esbuild.github.io) using [ts-json-schema-generator](https://github.com/vega/ts-json-schema-generator) to obtain the actual schema definition before extraction.
58
75
  *
@@ -86,11 +103,7 @@ declare function extractSource(variant: SchemaSourceVariant, input: SchemaSource
86
103
  * @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object.
87
104
  * @throws Will throw an error if the input is not a valid schema definition or if the extraction process fails to produce a valid schema.
88
105
  */
89
- declare function extractSchemaWithSource<TSpec = any>(input: SchemaInput, options?: ExtractOptions): Promise<ExtractedSchema<TSpec>>;
90
- type ExtractOptions = BundleOptions & {
91
- cachePath?: string;
92
- skipCache?: boolean;
93
- };
106
+ declare function extractSchemaWithSource<TSpec = any>(input: SchemaInput, options?: InferExtractOptions<typeof input>): Promise<ExtractedSchema<TSpec>>;
94
107
  /**
95
108
  * Extracts a JSON Schema from a given schema definition input, which can be a Zod schema, a Valibot schema, any Standard JSON Schema type, a plain JSON Schema object, an untyped schema, or a {@link FileReferenceInput} to an exported TypeScript type definition or any of the previous options. If the input is a {@link FileReferenceInput} (e.g. a file path with an export), the source code will be bundled with [esbuild](esbuild.github.io) using [ts-json-schema-generator](https://github.com/vega/ts-json-schema-generator) to obtain the actual schema definition before extraction.
96
109
  *
@@ -124,7 +137,7 @@ type ExtractOptions = BundleOptions & {
124
137
  * @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object.
125
138
  * @throws Will throw an error if the input is not a valid schema definition or if the extraction process fails to produce a valid schema.
126
139
  */
127
- declare function extract<TSpec = any>(input: SchemaInput<TSpec>, options?: ExtractOptions): Promise<SchemaOf<TSpec>>;
140
+ declare function extract<TSpec = any>(input: SchemaInput<TSpec>, options?: InferExtractOptions<typeof input>): Promise<SchemaOf<TSpec>>;
128
141
  //#endregion
129
- export { ExtractOptions, bundleReferences, extract, extractHash, extractJsonSchema, extractResolvedVariant, extractSchema, extractSchemaWithSource, extractSource, extractVariant };
142
+ export { bundleReferences, extract, extractHash, extractJsonSchema, extractResolvedVariant, extractSchema, extractSchemaMeta, extractSchemaWithSource, extractSource, extractTSType, extractVariant };
130
143
  //# sourceMappingURL=extract.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"extract.d.cts","names":[],"sources":["../src/extract.ts"],"mappings":";;;;;;AAiRA;;;;iBAAgB,gBAAA,CAAiB,MAAA,EAAQ,UAAA,GAAa,UAAU;;;;iBAgMhD,WAAA,CACd,OAAA,EAAS,kBAAA,EACT,KAAA,EAAO,WAAW;AAFpB;;;;;;AAAA,iBAkDgB,iBAAA,CAAkB,MAAA,YAAkB,UAAU;;;AAhD1C;AAgDpB;;;;iBAoCgB,sBAAA,CACd,KAAA,EAAO,iBAAA,GACN,mBAAmB;AAFtB;;;;;;AAAA,iBA4BgB,cAAA,CAAe,KAAA,EAAO,WAAA,GAAc,kBAAkB;;AA1BhD;AA0BtB;;;;;;iBAsBsB,aAAA,CACpB,KAAA,EAAO,iBAAA,EACP,OAAA,GAAU,kBAAA,GACT,OAAA,CAAQ,UAAA;;AAzB2D;AAsBtE;;;;;;iBAsCgB,aAAA,CACd,OAAA,EAAS,mBAAA,EACT,KAAA,EAAO,iBAAA,GACN,YAAA;;;;;;;;;;AAtCkB;AAmCrB;;;;;;;;;;;;;;AAGe;AAuEf;;;;;;;;iBAAsB,uBAAA,cACpB,KAAA,EAAO,WAAA,EACP,OAAA,GAAS,cAAA,GACR,OAAA,CAAQ,eAAA,CAAgB,KAAA;AAAA,KA0Hf,cAAA,GAAiB,aAAa;EACxC,SAAA;EACA,SAAA;AAAA;;;;;;;AA5H8B;AA0HhC;;;;;;;;AAEW;AAoCX;;;;;;;;;;;;;;;;;iBAAsB,OAAA,cACpB,KAAA,EAAO,WAAA,CAAY,KAAA,GACnB,OAAA,GAAS,cAAA,GACR,OAAA,CAAQ,QAAA,CAAS,KAAA"}
1
+ {"version":3,"file":"extract.d.cts","names":[],"sources":["../src/extract.ts"],"mappings":";;;;;;;AAwRA;;;;iBAAgB,gBAAA,CAAiB,MAAA,EAAQ,UAAA,GAAa,UAAU;;;;iBAgMhD,WAAA,CACd,OAAA,EAAS,kBAAA,EACT,KAAA,EAAO,WAAW;AAFpB;;;;;;AAAA,iBAkDgB,iBAAA,CAAkB,MAAA,YAAkB,UAAU;;;AAhD1C;AAgDpB;;;;iBAoCgB,sBAAA,CACd,KAAA,EAAO,iBAAA,GACN,mBAAmB;AAFtB;;;;;;AAAA,iBA4BgB,cAAA,CAAe,KAAA,EAAO,WAAA,GAAc,kBAAkB;;AA1BhD;AA0BtB;;;;;;iBAsBsB,aAAA,CACpB,KAAA,EAAO,iBAAA,EACP,OAAA,GAAU,kBAAA,GACT,OAAA,CAAQ,UAAA;;AAzB2D;AAsBtE;;;;;;iBAsCgB,aAAA,CACd,OAAA,EAAS,mBAAA,EACT,KAAA,EAAO,iBAAA,GACN,YAAA;;;;;;;;iBA6CmB,aAAA,CACpB,KAAA,EAAO,kBAAA,EACP,OAAA,GAAS,gBAAA,QAAwB,KAAA,IAChC,OAAA,CAAQ,UAAA;;AAtFU;AAmCrB;;;;;iBAuFgB,iBAAA,cACd,MAAA,EAAQ,QAAA,CAAS,KAAA,GACjB,KAAA,GAAQ,eAAA,CAAgB,KAAA,IACvB,UAAA,CAAW,KAAA;;;;;;;;;AAvFC;AA6Cf;;;;;;;;;;;;;;;;;;AAGqB;AAoCrB;;;;;iBAsEsB,uBAAA,cACpB,KAAA,EAAO,WAAA,EACP,OAAA,GAAS,mBAAA,QAA2B,KAAA,IACnC,OAAA,CAAQ,eAAA,CAAgB,KAAA;;;;;;;;;;;;;;;;AAtER;AAmEnB;;;;;;;;;;;;;;;;;iBA2JsB,OAAA,cACpB,KAAA,EAAO,WAAA,CAAY,KAAA,GACnB,OAAA,GAAS,mBAAA,QAA2B,KAAA,IACnC,OAAA,CAAQ,QAAA,CAAS,KAAA"}