Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/to-valibot/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) Rokas Muningis

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
152 changes: 152 additions & 0 deletions packages/to-valibot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
# (OpenAPI Declaration, JSON Schema) to Valibot

Utility to convert JSON Schemas and OpenAPI Declarations to [Valibot](https://valibot.dev) schemas.

## Example usage

### 1. Converting list of OpenAPI Declarations in .json format to Valibot
```ts
import { valibotGenerator } from "@valibot/to-valibot";

const generate = valibotGenerator({
outDir: "./src/types",
});

const schemas = await Promise.all([
fetch("http://api.example.org/v2/api-docs?group=my-awesome-api").then(r => r.json()),
fetch("http://api.example.org/v2/api-docs?group=other-api").then(r => r.json()),
fetch("http://api.example.org/v2/api-docs?group=legacy-api").then(r => r.json()),
]);

await generate({
format: 'openapi-json',
schemas,
});
```

### 2. Converting OpenAPI Declarations in .yaml format to Valibot
```ts
import { readFile } from "node:fs/promises";;
import { valibotGenerator } from "@valibot/to-valibot";

const generate = valibotGenerator({
outDir: "./src/types",
});

const schema = readFile("./declarations/my-awesome-api.yaml");

await generate({
format: 'openapi-yaml',
schema,
});
```

### 3. Converting JSON Schema to Valibot
```ts
import { readFile } from "node:fs/promises";;
import { valibotGenerator } from "@valibot/to-valibot";
import schema from "~/schemas/my-api.json";

const generate = valibotGenerator({
outDir: "./src/types",
});

await generate({
format: 'json',
schema,
});
```

## API

### valibotGenerator

`valibotGenerator` accepts options object with these parameters

| Name | Type | Required | Description |
| ------- | ------- | --------- | ----------------------------------------------------------------- |
| outDir | string | yes | Declare in which directory generated schema(s) should be written |

### generate

`generate` function returned by `valibotGenerator` accepts different set of options, depending on format.

| Name | Type | Required | Description |
| -------- | -------------- | --------- | --------------------------------------------- |
| format | 'openapi-yaml' | yes | Format specification for the generated output |
| schema | string | no* | Single schema to be processed |
| schemas | string[] | no* | Multiple schemas to be processed |
\* Either `schema` OR `schemas` must be provided, but not both.

| Name | Type | Required | Description |
| -------- | ------------------------ | --------- | --------------------------------------------- |
| format | 'openapi-json' \| 'json' | yes | Format specification for the generated output |
| schema | string \| object | no* | Single schema to be processed |
| schemas | (string \| object)[] | no* | Multiple schemas to be processed |
\* Either `schema` OR `schemas` must be provided, but not both.


## Supported features

Same set of features are supported both in OpenAPI Declarations and JSON Schemas

| Feature | Status | Note |
| ------------------------------- | ------ | ------------------------------------------------------------------- |
| required | ✅ | |
| description | ✅ | |
| const | ⚠️ | Only works with primitive values |
|---------------------------------|--------|---------------------------------------------------------------------|
| string | ✅ | |
| enum | ✅ | |
| minLength | ✅ | |
| maxLength | ✅ | |
| pattern | ✅ | |
| format="email" | ✅ | |
| format="uuid" | ✅ | |
| format="date-time" | ✅ | |
| format="date" | ✅ | |
| format="time" | ✅ | |
| format="duration" | ⚠️ | https://github.com/fabian-hiller/valibot/pull/1102 |
| format="idn-email" | ❌ | |
| format="hostname" | ❌ | |
| format="idn-hostname" | ❌ | |
| format="ipv4" | ✅ | |
| format="ipv6" | ✅ | |
| format="json-pointer" | ❌ | |
| format="relative-json-pointer" | ❌ | |
| format="uri" | ❌ | |
| format="uri-reference" | ❌ | |
| format="uri-template" | ❌ | |
| format="iri" | ❌ | |
| format="iri-reference" | ❌ | |
|---------------------------------|--------|---------------------------------------------------------------------|
| number | ✅ | |
| integer | ✅ | |
| exclusiveMaximum | ✅ | |
| exclusiveMinium | ✅ | |
| maximum | ✅ | |
| minium | ✅ | |
| multipleOf | ✅ | |
|---------------------------------|--------|---------------------------------------------------------------------|
| array | ⚠️ | Only single array item kind is supported for now |
| minItems | ✅ | |
| maxItems | ✅ | |
| uniqueItems | ✅ | |
| prefixItems | ❌ | |
| contains | ❌ | |
| minContains | ❌ | |
| maxContains | ❌ | |
|---------------------------------|--------|---------------------------------------------------------------------|
| object | ✅ | |
| patternProperties | ❌ | |
| additionalProperties | ✅ | |
| minProperties | ⚠️ | https://github.com/fabian-hiller/valibot/pull/1100 |
| maxProperties | ⚠️ | https://github.com/fabian-hiller/valibot/pull/1100 |
|---------------------------------|--------|---------------------------------------------------------------------|
| boolean | ✅ | |
| null | ✅ | |
|---------------------------------|--------|---------------------------------------------------------------------|
| anyOf | ❌ | |
| allOf | ❌ | |
| oneOf | ❌ | |
| not | ❌ | |
72 changes: 72 additions & 0 deletions packages/to-valibot/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import eslint from '@eslint/js';
import importPlugin from 'eslint-plugin-import';
import jsdoc from 'eslint-plugin-jsdoc';
import pluginSecurity from 'eslint-plugin-security';
import tseslint from 'typescript-eslint';

export default tseslint.config(
eslint.configs.recommended,
tseslint.configs.strict,
tseslint.configs.stylistic,
jsdoc.configs['flat/recommended'],
pluginSecurity.configs.recommended,
{
files: ['lib/**/*.ts'],
extends: [importPlugin.flatConfigs.recommended],
plugins: { jsdoc },
rules: {
// Enable rules -----------------------------------------------------------

// TypeScript
'@typescript-eslint/consistent-type-definitions': 'off', // Enforce declaring types using `interface` keyword for better TS performance.
'@typescript-eslint/consistent-type-imports': 'warn',

// Import
'import/extensions': ['error', 'always'], // Require file extensions

// JSDoc
'jsdoc/tag-lines': ['error', 'any', { startLines: 1 }],
'jsdoc/sort-tags': [
'error',
{
linesBetween: 1,
tagSequence: [
{ tags: ['deprecated'] },
{ tags: ['param'] },
{ tags: ['returns'] },
],
},
],
// NOTE: For overloads functions, we only require a JSDoc at the top
// SEE: https://github.com/gajus/eslint-plugin-jsdoc/issues/666
'jsdoc/require-jsdoc': [
'error',
{
contexts: [
'ExportNamedDeclaration[declaration.type="TSDeclareFunction"]:not(ExportNamedDeclaration[declaration.type="TSDeclareFunction"] + ExportNamedDeclaration[declaration.type="TSDeclareFunction"])',
'ExportNamedDeclaration[declaration.type="FunctionDeclaration"]:not(ExportNamedDeclaration[declaration.type="TSDeclareFunction"] + ExportNamedDeclaration[declaration.type="FunctionDeclaration"])',
],
require: {
FunctionDeclaration: false,
},
},
],

// Disable rules ----------------------------------------------------------

// TypeScript
'@typescript-eslint/ban-ts-comment': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',

// Imports
'no-duplicate-imports': 'off',

// JSDoc
'jsdoc/require-param-type': 'off',
'jsdoc/require-returns-type': 'off',

// Security
'security/detect-object-injection': 'off', // Too many false positives
},
}
);
9 changes: 9 additions & 0 deletions packages/to-valibot/jsr.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "@valibot/to-valibot",
"version": "0.0.0",
"exports": "./src/index.ts",
"publish": {
"include": ["lib/**/*.ts", "README.md"],
"exclude": ["lib/**/*.spec.ts", "spec/**/*"]
}
}
55 changes: 55 additions & 0 deletions packages/to-valibot/lib/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { writeFile } from 'node:fs/promises';
import { ValibotGenerator } from './parser-and-generator.ts';
import { slugify } from './utils/basic.ts';

interface GeneratorOptions {
outDir: string;
}

type GenerateOptions =
| { format: 'openapi-json' | 'json'; schema: object }
| { format: 'openapi-json' | 'json'; schemas: object[] }
| { format: 'openapi-json' | 'json' | 'openapi-yaml'; schema: string }
| { format: 'openapi-json' | 'json' | 'openapi-yaml'; schemas: string[] };

interface ValibotGeneratorReturn {
generate: (opt: GenerateOptions) => Promise<void>;
}
const valibotGenerator = (
options: GeneratorOptions
): ValibotGeneratorReturn => {
const generate = async (opt: GenerateOptions): Promise<void> => {
if ('schemas' in opt) {
for (const schema of opt.schemas) {
const schemaCode =
typeof schema === 'string'
? new ValibotGenerator(schema, opt.format)
: new ValibotGenerator(
schema,
opt.format as 'openapi-json' | 'json'
);

const code = schemaCode.generate();
const name = slugify(schemaCode.title);
console.log(code, name, `${options.outDir}/${name}.ts`);
await writeFile(`${options.outDir}/${name}.ts`, code);
}
} else {
const schemaCode =
typeof opt.schema === 'string'
? new ValibotGenerator(opt.schema, opt.format)
: new ValibotGenerator(
opt.schema,
opt.format as 'openapi-json' | 'json'
);

const code = schemaCode.generate();
const name = slugify(schemaCode.title);
await writeFile(`${options.outDir}/${name}.ts`, code);
}
};

return { generate };
};

export { valibotGenerator };
Loading