Skip to content

Commit

Permalink
Add plugin for Effect (colinhacks#3445)
Browse files Browse the repository at this point in the history
* Update README_ZH.md (colinhacks#3433)

fix Demo -> Deno

* Clean up code, fix build/test

* Write docs

* Fix rollup build

* Fix setup-deno

* Add types field

* Fix types

* Use globalThis check

* Add _tag to ZodError

* Comments

* Add better tests

* suggestions for effect plugin (colinhacks#3449)

* Updates

* Move to .effect.parse()

* Bind this in getter

* Clean up

---------

Co-authored-by: sdshaoda <21106848+sdshaoda@users.noreply.github.com>
Co-authored-by: Tim <hello@timsmart.co>
  • Loading branch information
3 people committed May 3, 2024
1 parent edd31b1 commit adc005e
Show file tree
Hide file tree
Showing 16 changed files with 3,234 additions and 0 deletions.
3 changes: 3 additions & 0 deletions plugin/effect/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
lib
node_modules
playground.ts
21 changes: 21 additions & 0 deletions plugin/effect/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Colin McDonnell

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.
105 changes: 105 additions & 0 deletions plugin/effect/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<p align="center">
<img src="logo.svg" width="200px" align="center" alt="Zod logo" />
<h1 align="center">Zod</h1>
<p align="center">
✨ <a href="https://zod.dev">https://zod.dev</a> ✨
<br/>
TypeScript-first schema validation with static type inference
</p>
</p>
<br/>
<!-- <p align="center">
<a href="https://github.com/colinhacks/zod/actions?query=branch%3Amaster"><img src="https://github.com/colinhacks/zod/actions/workflows/test.yml/badge.svg?event=push&branch=master" alt="Zod CI status" /></a>
<a href="https://twitter.com/colinhacks" rel="nofollow"><img src="https://img.shields.io/badge/created%20by-@colinhacks-4BBAAB.svg" alt="Created by Colin McDonnell"></a>
<a href="https://opensource.org/licenses/MIT" rel="nofollow"><img src="https://img.shields.io/github/license/colinhacks/zod" alt="License"></a>
<a href="https://www.npmjs.com/package/zod" rel="nofollow"><img src="https://img.shields.io/npm/dw/zod.svg" alt="npm"></a>
<a href="https://www.npmjs.com/package/zod" rel="nofollow"><img src="https://img.shields.io/github/stars/colinhacks/zod" alt="stars"></a>
<a href="https://discord.gg/KaSRdyX2vc" rel="nofollow"><img src="https://img.shields.io/discord/893487829802418277?label=Discord&logo=discord&logoColor=white" alt="discord server"></a>
</p> -->
<!--
<div align="center">
<a href="https://zod.dev">Documentation</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://discord.gg/RcG33DQJdf">Discord</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://www.npmjs.com/package/zod">npm</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://deno.land/x/zod">deno</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://github.com/colinhacks/zod/issues/new">Issues</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://twitter.com/colinhacks">@colinhacks</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://trpc.io">tRPC</a>
<br />
</div> -->

<br/>
<br/>

## `Effect` plugin for Zod

This is a plugin to add support for `Effect` to Zod. Effect provides a foundation for writing TypeScript in a functional, composable way. Refer to the [Effect docs](https://effect.website/docs/guides/essentials/importing-effect) for details.

## Usage

Requirements (peer dependencies):

- `zod@^3.0.0`
- `effect@^3.0.0`

To install the plugin:

```bash
npm add effect zod @zod-plugin/effect
```

To use the plugin, add the following line in the _entry point_ of your application:

```ts
import "@zod-plugin/effect";
```

This adds two new methods to the `ZodType` base class. These methods are now available on all schemas throughout your application.

### `.effect.parse(data): Effect<T, ZodError, never>`

This method accepts some input data and parses it _asynchronously_.

```ts
import * as z from "zod";
import { Effect } from "effect";

import "@zod-plugin/effect";

const schema = z.object({
name: z.string(),
});

const effect = schema.effect.parse({ name: "Michael Arnaldi" });
//=> Effect<{ name: string }, ZodError, never>;

await Effect.runPromise(effect);
// => { name: "Michael Arnaldi" }
```

### `.effect.parseSync(data): Effect<T, ZodError, never>`

This method accepts some input data and parses it _synchronously_. If any asynchronous refinements or transforms are encountered, Effect will throw an error.

```ts
import * as z from "zod";
import { Effect } from "effect";

import "@zod-plugin/effect";

const schema = z.object({
name: z.string(),
});

const effect = schema.effect.parseSync({ name: "Michael Arnaldi" });
//=> Effect<{ name: string }, ZodError, never>;

await Effect.runSync(effect);
// => { name: "Michael Arnaldi" }
```
28 changes: 28 additions & 0 deletions plugin/effect/configs/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// rollup.config.js
// node resolve
import commonjs from "@rollup/plugin-commonjs";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import typescript from "@rollup/plugin-typescript";

export default [
{
input: "src/index.ts",
output: [
{
file: "lib/index.mjs",
format: "es",
sourcemap: false,
exports: "named",
},
],
plugins: [
nodeResolve(),
commonjs(),
typescript({
tsconfig: "./configs/tsconfig.esm.json",
sourceMap: false,
}),
],
external: ["zod", "effect"],
},
];
10 changes: 10 additions & 0 deletions plugin/effect/configs/ts-jest.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"rootDir": "..",
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"testRegex": "src/.*\\.test\\.ts$",
"modulePathIgnorePatterns": ["language-server", "__vitest__"],
"moduleFileExtensions": ["ts", "tsx", "js", "jsx", "json", "node"],
"coverageReporters": ["json-summary", "text", "lcov"]
}
21 changes: 21 additions & 0 deletions plugin/effect/configs/tsconfig.base.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"lib": ["es5", "es6", "es7", "esnext", "dom"],
"target": "es2018",
"removeComments": false,
"esModuleInterop": true,
"moduleResolution": "node",
"module": "ESNext",
"resolveJsonModule": true,
"strict": true,
"skipLibCheck": true,
"strictPropertyInitialization": false,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"downlevelIteration": true,
"isolatedModules": true
},
"include": ["../src/**/*", "../playground.ts"]
}
12 changes: 12 additions & 0 deletions plugin/effect/configs/tsconfig.cjs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"module": "commonjs",
"outDir": "../lib",
"declaration": true,
"declarationMap": false,
"sourceMap": false,
"skipLibCheck": true
},
"exclude": ["../tests", "../playground.ts", "node_modules"]
}
11 changes: 11 additions & 0 deletions plugin/effect/configs/tsconfig.esm.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"module": "es2015",
"skipLibCheck": true,
"declaration": false,
"declarationMap": false,
"sourceMap": false
},
"exclude": ["../src/**/__tests__", "../src/playground.ts"]
}
13 changes: 13 additions & 0 deletions plugin/effect/configs/tsconfig.test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"module": "commonjs",
"outDir": "__buildtest__",
"target": "es5",
"declaration": true,
"declarationMap": false,
"sourceMap": false,
"noEmit": true
},
"exclude": []
}
10 changes: 10 additions & 0 deletions plugin/effect/configs/tsconfig.types.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"outDir": "../lib/types",
"declaration": true,
"declarationMap": true,
"emitDeclarationOnly": true
},
"exclude": ["../src/**/__tests__", "../src/playground.ts"]
}
10 changes: 10 additions & 0 deletions plugin/effect/jest.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"rootDir": ".",
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"testRegex": "src/.*\\.test\\.ts$",
"modulePathIgnorePatterns": ["language-server", "__vitest__"],
"moduleFileExtensions": ["ts", "tsx", "js", "jsx", "json", "node"],
"coverageReporters": ["json-summary", "text", "lcov"]
}
60 changes: 60 additions & 0 deletions plugin/effect/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
{
"name": "@zod-plugin/effect",
"version": "0.1.0",
"type": "module",
"author": "Colin McDonnell <colin@colinhacks.com>",
"types": "./lib/index.d.ts",
"description": "TypeScript-first schema declaration and validation library with static type inference",
"files": ["/lib"],
"keywords": ["typescript", "schema", "validation", "type", "inference"],
"license": "MIT",
"main": "./lib/index.js",
"module": "./lib/index.mjs",
"sideEffects": true,
"repository": {
"type": "git",
"url": "git+https://github.com/colinhacks/zod.git"
},
"scripts": {
"clean": "rm -rf lib/*",
"build": "yarn run clean && npm run build:cjs && npm run build:esm",
"build:esm": "rollup --config ./configs/rollup.config.js",
"build:cjs": "tsc -p ./configs/tsconfig.cjs.json",
"build:types": "tsc -p ./configs/tsconfig.types.json",
"build:test": "tsc -p ./configs/tsconfig.test.json",
"test:watch": "yarn test:ts-jest --watch",
"test": "yarn tsx tests/*.ts",
"prepublishOnly": "npm run test && npm run build"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^25.0.7",
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-typescript": "^8.2.0",
"@types/node": "^20.0.0",
"effect": "^3.0.0",
"jest": "^29.3.1",
"lint-staged": "^12.3.7",
"prettier": "^2.6.0",
"pretty-quick": "^3.1.3",
"rollup": "^2.70.1",
"ts-jest": "^29.1.0",
"tsx": "^3.8.0",
"typescript": "^5.0.0",
"zod": "^3.0.0"
},
"peerDependencies": {
"effect": "^3.0.0",
"zod": "^3.0.0"
},
"exports": {
".": {
"types": "./lib/index.d.ts",
"require": "./lib/index.js",
"import": "./lib/index.mjs"
},
"./package.json": "./package.json"
},
"bugs": {
"url": "https://github.com/colinhacks/zod/issues"
}
}
51 changes: 51 additions & 0 deletions plugin/effect/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import * as Effect from "effect/Effect";
import * as z from "zod";

function zodEffect(this: z.ZodType, data: unknown, params?: any) {
return Effect.flatMap(
Effect.promise(() => this.safeParseAsync(data, params)),
(result) =>
result.success ? Effect.succeed(result.data) : Effect.fail(result.error)
);
}

function zodEffectSync(this: z.ZodType, data: unknown, params?: any) {
return Effect.suspend(() => {
const result = this.safeParse(data, params);
return result.success
? Effect.succeed(result.data)
: Effect.fail(result.error);
});
}

const sym = Symbol.for("zod_effect_executed");
if (!(globalThis as { [k: symbol]: unknown })[sym]) {
(globalThis as { [k: symbol]: unknown })[sym] = true;
Object.defineProperty(z.ZodType.prototype, "effect", {
get() {
return {
parse: zodEffect.bind(this),
parseSync: zodEffectSync.bind(this),
};
},
});
z.ZodError.prototype._tag = "ZodError";
}

interface EffectMethods<T> {
parse(
...args: Parameters<z.ZodType["parseAsync"]>
): Effect.Effect<T, z.ZodError<T>>;
parseSync(
...args: Parameters<z.ZodType["parse"]>
): Effect.Effect<T, z.ZodError<T>>;
}
declare module "zod" {
interface ZodType {
effect: EffectMethods<this["_output"]>;
}

interface ZodError {
_tag: "ZodError";
}
}

0 comments on commit adc005e

Please sign in to comment.