@nemmtor/ts-databuilders 0.0.1-alpha.4 → 0.0.1-alpha.5
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.
- package/README.md +168 -10
- package/dist/main.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,14 +1,172 @@
|
|
|
1
1
|
# 🧱 TS DataBuilders
|
|
2
|
-
|
|
3
|
-
Just add a @DataBuilder JSDoc tag, run one command, and get a fully-typed builder ready to use in your tests or factories.
|
|
2
|
+
A CLI tool that automatically generates builder classes from annotated TypeScript types.
|
|
4
3
|
|
|
5
|
-
|
|
4
|
+
## Usage
|
|
5
|
+
Install the package:
|
|
6
|
+
```bash
|
|
7
|
+
pnpm add -D @nemmtor/ts-databuilders
|
|
8
|
+
```
|
|
6
9
|
|
|
7
|
-
|
|
10
|
+
Annotate the types you want to build with JsDoc tag:
|
|
11
|
+
```ts
|
|
12
|
+
/**
|
|
13
|
+
* @DataBuilder
|
|
14
|
+
*/
|
|
15
|
+
type Example = {
|
|
16
|
+
bar: string;
|
|
17
|
+
baz: string;
|
|
18
|
+
}
|
|
19
|
+
```
|
|
8
20
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
21
|
+
Run the command:
|
|
22
|
+
```bash
|
|
23
|
+
pnpm ts-databuilders
|
|
24
|
+
```
|
|
25
|
+
By default it tries to find annotated types in `src/**/*.ts{,x}` and outputs builders in `generated/builders`.
|
|
26
|
+
Above and much more is configurable - check out configuration section.
|
|
27
|
+
|
|
28
|
+
Above example will result in output:
|
|
29
|
+
```ts
|
|
30
|
+
import type { Example } from "../../src/example";
|
|
31
|
+
import { DataBuilder } from "./data-builder";
|
|
32
|
+
|
|
33
|
+
export class ExampleBuilder extends DataBuilder<Example> {
|
|
34
|
+
constructor() {
|
|
35
|
+
super({
|
|
36
|
+
bar: "",
|
|
37
|
+
baz: ""
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
withBar(bar: Example['bar']) {
|
|
42
|
+
return this.with({ bar: bar });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
withBaz(baz: Example['baz']) {
|
|
46
|
+
return this.with({ baz: baz });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Configuration
|
|
52
|
+
> [!NOTE]
|
|
53
|
+
> Name column is equal to field names in ts-databuilders.json file.
|
|
54
|
+
|
|
55
|
+
| Name | Flag | Description | Default | Type |
|
|
56
|
+
|---------------|-----------------|----------------------------------------------------------------|--------------------------------------------------|------------|
|
|
57
|
+
| jsdocTag | --jsdoc-tag | JSDoc tag used to mark types for data building generation. | DataBuilder | string |
|
|
58
|
+
| outputDir | --output-dir -o | Output directory for generated builders. | generated/builders | string |
|
|
59
|
+
| include | --include -i | Glob pattern for files included while searching for jsdoc tag. | src/**/*.ts{,x} | string |
|
|
60
|
+
| fileSuffix | --file-suffix | File suffix for created builder files. | .builder | string |
|
|
61
|
+
| builderSuffix | --builder-suffix | Suffix for generated classes. | Builder | string |
|
|
62
|
+
| defaults | --defaults | Default values to be used in data builder constructor. | { string: '', number: 0, boolean: false, } | object/map |
|
|
63
|
+
|
|
64
|
+
All of the above flags are optional and are having sensible defaults which should be good enough for most cases.
|
|
65
|
+
You can configure these via cli flags or by creating `ts-databuilders.json` file in the root of your repository.
|
|
66
|
+
Example of config file:
|
|
67
|
+
```json
|
|
68
|
+
{
|
|
69
|
+
"$schema": "https://raw.githubusercontent.com/nemmtor/ts-databuilders/refs/heads/main/schema.json",
|
|
70
|
+
"include": "example-data/**",
|
|
71
|
+
"builderSuffix": "GeneratedBuilder",
|
|
72
|
+
"fileSuffix": ".generated-builder",
|
|
73
|
+
"jsdocTag": "GenerateBuilder",
|
|
74
|
+
"outputDir": "generated-builders/",
|
|
75
|
+
"defaults": {
|
|
76
|
+
"boolean": true,
|
|
77
|
+
"number": 2000,
|
|
78
|
+
"string": "foo"
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Priority when resolving config values is:
|
|
84
|
+
1. Cli flags
|
|
85
|
+
2. Config file values
|
|
86
|
+
3. Hardcoded defaults
|
|
87
|
+
|
|
88
|
+
## Motivation
|
|
89
|
+
When writing tests you often want to test some scenario that is happening when
|
|
90
|
+
one of the input values is in a specific shape.
|
|
91
|
+
Often times this value is only one of many options provided.
|
|
92
|
+
|
|
93
|
+
Imagine testing a case where document aggregate should emit an event when it successfully
|
|
94
|
+
update it's content:
|
|
95
|
+
```ts
|
|
96
|
+
it('should emit a ContentUpdatedEvent', () => {
|
|
97
|
+
const aggregate = DocumentAggregate.create({
|
|
98
|
+
id: '1',
|
|
99
|
+
createdAt: new Date(),
|
|
100
|
+
updatedAt: new Date(),
|
|
101
|
+
content: 'old-content'
|
|
102
|
+
});
|
|
103
|
+
const userId = '1';
|
|
104
|
+
|
|
105
|
+
aggregate.updateContent({ updatedBy: userId, content: 'new-content' });
|
|
106
|
+
|
|
107
|
+
expect(...);
|
|
108
|
+
})
|
|
109
|
+
```
|
|
110
|
+
Above code obfuscated with all of the default values you need to provide in order to satisfy typescript.
|
|
111
|
+
Where in reality the only thing specific to this single test is the fact that some new content was provided to `updateContent` method.
|
|
112
|
+
|
|
113
|
+
Imagine even more complex scenario:
|
|
114
|
+
```tsx
|
|
115
|
+
it('should show validation error when email is invalid', async () => {
|
|
116
|
+
render(<ProfileForm defaultValues={
|
|
117
|
+
firstName: '',
|
|
118
|
+
lastName: '',
|
|
119
|
+
age: 0,
|
|
120
|
+
socials: {
|
|
121
|
+
linkedin: '',
|
|
122
|
+
github: '',
|
|
123
|
+
website: '',
|
|
124
|
+
twitter: '',
|
|
125
|
+
},
|
|
126
|
+
address: {
|
|
127
|
+
street: '',
|
|
128
|
+
city: '',
|
|
129
|
+
state: '',
|
|
130
|
+
zip: '',
|
|
131
|
+
},
|
|
132
|
+
skills: [],
|
|
133
|
+
bio: '',
|
|
134
|
+
email: 'invalid-email'
|
|
135
|
+
}
|
|
136
|
+
/>)
|
|
137
|
+
|
|
138
|
+
await submitForm();
|
|
139
|
+
|
|
140
|
+
expect(...);
|
|
141
|
+
})
|
|
142
|
+
```
|
|
143
|
+
Again - in reality you should only be worried about email, not about whole form data.
|
|
144
|
+
|
|
145
|
+
Here's how above tests could be written with databuilders:
|
|
146
|
+
```ts
|
|
147
|
+
it('should emit a ContentUpdatedEvent', () => {
|
|
148
|
+
const aggregate = DocumentAggregate.create(new CreateDocumentAggregatedPayloadBuilder().build());
|
|
149
|
+
|
|
150
|
+
aggregate.updateContent(new UpdateDocumentContentPayloadBuilder().withContent('new-content').build());
|
|
151
|
+
|
|
152
|
+
expect(...);
|
|
153
|
+
})
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
```tsx
|
|
157
|
+
it('should show validation error when email is invalid', async () => {
|
|
158
|
+
render(<ProfileForm defaultValues={new ProfileFormInputBuilder.withEmail('invalid-email').build()} />)
|
|
159
|
+
|
|
160
|
+
await submitForm();
|
|
161
|
+
|
|
162
|
+
expect(...);
|
|
163
|
+
})
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
This not only makes the test code less verbose but also highlights what is really being tested.
|
|
167
|
+
|
|
168
|
+
## Nested builders
|
|
169
|
+
TODO
|
|
170
|
+
|
|
171
|
+
## Supported types
|
|
172
|
+
TODO
|
package/dist/main.js
CHANGED
|
@@ -18,4 +18,4 @@ import*as Ke from"@effect/platform-node/NodeContext";import*as Ze from"@effect/p
|
|
|
18
18
|
return this;
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
-
`;function at(t){let i=[];function m(e){switch(e.kind){case"BUILDER":i.push(e.name);break;case"TYPE_LITERAL":Object.values(e.metadata).forEach(m);break;case"UNION":case"TUPLE":e.members.forEach(m);break;case"RECORD":m(e.keyType),m(e.valueType);break}}return Object.values(t).forEach(m),i}class R extends N.Service()("@TSDataBuilders/Builders",{effect:N.gen(function*(){let t=yield*De.FileSystem,i=yield*te,{outputDir:m}=yield*F;return{create:N.fnUntraced(function*(e){if(yield*N.orDie(t.exists(m)))yield*N.orDie(t.remove(m,{recursive:!0}));yield*N.orDie(t.makeDirectory(m,{recursive:!0})),yield*i.generateBaseBuilder();let s=e.map((r)=>r.name),n=s.filter((r,y)=>s.indexOf(r)!==y),f=[...new Set(n)];if(n.length>0)return yield*N.dieMessage(`Duplicated builders: ${f.join(", ")}`);yield*N.all(e.map((r)=>i.generateBuilder(r)),{concurrency:"unbounded"})})}}),dependencies:[te.Default]}){}import*as d from"@effect/cli/Options";import{Option as fe}from"effect";import*as v from"effect/HashMap";import*as b from"effect/Schema";var ct=d.text("jsdocTag").pipe(d.withDescription("JSDoc tag used to mark types for data building generation."),d.withSchema(U.fields.jsdocTag),d.optional),lt=d.text("output-dir").pipe(d.withAlias("o"),d.withDescription("Output directory for generated builders."),d.withSchema(U.fields.outputDir),d.optional),mt=d.text("include").pipe(d.withAlias("i"),d.withDescription("Glob pattern for files included while searching for jsdoc tag."),d.withSchema(U.fields.include),d.optional),ft=d.text("file-suffix").pipe(d.withDescription("File suffix for created builder files."),d.withSchema(U.fields.fileSuffix),d.optional),dt=d.text("builder-suffix").pipe(d.withDescription("Suffix for generated classes."),d.withSchema(U.fields.builderSuffix),d.optional),pt=d.keyValueMap("defaults").pipe(d.withDescription("Default values to be used in data builder constructor."),d.withSchema(b.HashMapFromSelf({key:b.Literal("string","number","boolean"),value:b.String}).pipe(b.transform(b.Struct({string:b.String,number:b.NumberFromString,boolean:b.BooleanFromString}).pipe(b.partial),{decode:(t)=>{return{string:t.pipe(v.get("string"),fe.getOrUndefined),number:t.pipe(v.get("number"),fe.getOrUndefined),boolean:t.pipe(v.get("boolean"),fe.getOrUndefined)}},encode:(t)=>{return v.make(["string",t.string],["number",t.number],["boolean",t.boolean])},strict:!1}))),d.optional),xe={jsdocTag:ct,outputDir:lt,include:mt,fileSuffix:ft,builderSuffix:dt,defaults:pt};import*as A from"effect/Chunk";import*as x from"effect/Effect";import*as $e from"effect/Function";import*as _ from"effect/Option";import*as ie from"effect/Stream";import*as Fe from"effect/Data";import*as Ne from"effect/Effect";import*as Be from"effect/Stream";import{glob as ut}from"glob";class V extends Ne.Service()("@TSDataBuilders/TreeWalker",{succeed:{walk:(t)=>{return Be.fromAsyncIterable(ut.stream(t,{cwd:".",nodir:!0}),(i)=>new ke({cause:i}))}}}){}class ke extends Fe.TaggedError("TreeWalkerError"){}import*as Oe from"@effect/platform/FileSystem";import*as j from"effect/Effect";import*as I from"effect/Stream";class re extends j.Service()("@TSDataBuilders/FileContentChecker",{effect:j.gen(function*(){let t=yield*Oe.FileSystem,i=new TextDecoder;return{check:j.fnUntraced(function*(m){let{content:e,filePath:p}=m;return yield*I.orDie(t.stream(p,{chunkSize:16384})).pipe(I.map((f)=>i.decode(f,{stream:!0})),I.mapAccum("",(f,r)=>{let y=f+r;return[y.slice(-e.length+1),y.includes(e)]}),I.find(Boolean),I.runCollect)})}})}){}class G extends x.Service()("@TSDataBuilders/Finder",{effect:x.gen(function*(){let t=yield*re,i=yield*V,{include:m,jsdocTag:e}=yield*F,p=`@${e}`;return{find:x.fnUntraced(function*(){return yield*i.walk(m).pipe(ie.mapEffect((f)=>t.check({filePath:f,content:p}).pipe(x.map(A.map((r)=>r?_.some(f):_.none()))),{concurrency:"unbounded"}),ie.runCollect,x.map(A.flatMap($e.identity)),x.map(A.filter((f)=>_.isSome(f))),x.map(A.map((f)=>f.value)))},x.catchTag("TreeWalkerError",(s)=>x.die(s)))}}),dependencies:[V.Default,re.Default]}){}import*as Ae from"@effect/platform/FileSystem";import*as W from"effect/Data";import*as S from"effect/Effect";import*as H from"effect/Either";import{Project as gt,SyntaxKind as se}from"ts-morph";import*as L from"effect/Data";import*as c from"effect/Effect";import*as u from"effect/Match";import*as we from"effect/Option";import{Node as yt,SyntaxKind as g}from"ts-morph";import{randomUUID as St}from"node:crypto";import*as ne from"effect/Effect";class oe extends ne.Service()("@TSDataBuilders/RandomUUID",{succeed:{generate:ne.sync(()=>St())}}){}class ae extends c.Service()("@TSDataBuilders/TypeNodeParser",{effect:c.gen(function*(){let{jsdocTag:t}=yield*F,i=yield*oe,m=(p)=>c.gen(function*(){let{type:s,contextNode:n,optional:f}=p,r=s.getProperties();if(!s.isObject()||r.length===0)return yield*new Me({raw:s.getText(),kind:n.getKind()});let y={};for(let o of r){let l=o.getName(),E=o.getTypeAtLocation(n),h=o.isOptional(),C=n.getProject().createSourceFile(`__temp_${yield*i.generate}.ts`,`type __T = ${E.getText()}`,{overwrite:!0}),$=C.getTypeAliasOrThrow("__T").getTypeNodeOrThrow(),w=yield*c.suspend(()=>e({typeNode:$,optional:h}));y[l]=w,n.getProject().removeSourceFile(C)}return{kind:"TYPE_LITERAL",metadata:y,optional:f}}),e=(p)=>c.gen(function*(){let{typeNode:s,optional:n}=p,f=s.getKind(),r=u.value(f).pipe(u.when(u.is(g.StringKeyword),()=>c.succeed({kind:"STRING",optional:n})),u.when(u.is(g.NumberKeyword),()=>c.succeed({kind:"NUMBER",optional:n})),u.when(u.is(g.BooleanKeyword),()=>c.succeed({kind:"BOOLEAN",optional:n})),u.when(u.is(g.UndefinedKeyword),()=>c.succeed({kind:"UNDEFINED",optional:n})),u.when(u.is(g.ArrayType),()=>c.succeed({kind:"ARRAY",optional:n})),u.when(u.is(g.LiteralType),()=>c.succeed({kind:"LITERAL",literalValue:s.asKindOrThrow(g.LiteralType).getLiteral().getText(),optional:n})),u.when(u.is(g.TypeLiteral),()=>c.gen(function*(){let l=s.asKindOrThrow(g.TypeLiteral).getMembers();return{kind:"TYPE_LITERAL",metadata:yield*c.reduce(l,{},(h,C)=>c.gen(function*(){if(!C.isKind(g.PropertySignature))return h;let $=C.getTypeNode();if(!$)return h;let w=C.getNameNode().getText(),z=C.hasQuestionToken(),B=yield*c.suspend(()=>e({typeNode:$,optional:z}));return{...h,[w]:B}})),optional:n}})),u.when(u.is(g.ImportType),()=>c.gen(function*(){let o=s.asKindOrThrow(g.ImportType),l=o.getType(),E=l.getSymbol();if(!E)return yield*c.die(new Pe);let h=E.getDeclarations();if(h&&h.length>1)return yield*c.die(new de);let[C]=h;if(!C)return yield*c.die(new pe);return yield*m({type:l,contextNode:o,optional:n})})),u.when(u.is(g.TupleType),()=>c.gen(function*(){let l=s.asKindOrThrow(g.TupleType).getElements(),E=yield*c.all(l.map((h)=>c.suspend(()=>e({typeNode:h,optional:!1}))));return{kind:"TUPLE",optional:n,members:E}})),u.when(u.is(g.TypeReference),()=>c.gen(function*(){let o=s.asKindOrThrow(g.TypeReference),l=o.getTypeName().getText();if(l==="Date")return{kind:"DATE",optional:n};if(l==="Array")return{kind:"ARRAY",optional:n};let E=o.getTypeArguments();if(l==="Record"){let[O,Q]=E;if(!O||!Q)return yield*new q({kind:f,raw:s.getText()});let Je=yield*c.suspend(()=>e({typeNode:O,optional:!1})),Ve=yield*c.suspend(()=>e({typeNode:Q,optional:!1}));return{kind:"RECORD",keyType:Je,valueType:Ve,optional:n}}if(["Pick","Omit","Partial","Required","Readonly","Extract","NonNullable"].includes(l))return yield*m({type:o.getType(),contextNode:o,optional:n});let C=o.getType().getAliasSymbol();if(!C)return yield*m({type:o.getType(),contextNode:o,optional:n});let $=C.getDeclarations();if($&&$.length>1)return yield*c.die(new de);let[w]=$;if(!w)return yield*c.die(new pe);let z=C?.getJsDocTags().map((O)=>O.getName()).includes(t);if(!yt.isTypeAliasDeclaration(w))return yield*c.die(new Ie);let B=w.getTypeNode();if(!B)return yield*new q({kind:f,raw:s.getText()});if(!z)return yield*c.suspend(()=>e({typeNode:B,optional:n}));return{kind:"BUILDER",name:w.getName(),optional:n}})),u.when(u.is(g.UnionType),()=>c.gen(function*(){let o=yield*c.all(s.asKindOrThrow(g.UnionType).getTypeNodes().map((l)=>c.suspend(()=>e({typeNode:l,optional:!1}))));return{kind:"UNION",optional:n,members:o}})),u.when(u.is(g.IntersectionType),()=>c.gen(function*(){let l=s.asKindOrThrow(g.IntersectionType).getTypeNodes(),E=[g.StringKeyword,g.NumberKeyword,g.BooleanKeyword],h=l.find((C)=>E.includes(C.getKind()));if(h&&l.length>1)return{kind:"TYPE_CAST",baseTypeMetadata:yield*c.suspend(()=>e({typeNode:h,optional:!1})),optional:n};return yield*new q({kind:f,raw:s.getText()})})),u.option);if(we.isNone(r))return yield*new q({kind:f,raw:s.getText()});return yield*r.value});return{generateMetadata:e}}),dependencies:[oe.Default]}){}class q extends L.TaggedError("UnsupportedSyntaxKindError"){}class de extends L.TaggedError("MultipleSymbolDeclarationsError"){}class pe extends L.TaggedError("MissingSymbolDeclarationError"){}class Pe extends L.TaggedError("MissingSymbolError"){}class Ie extends L.TaggedError("UnsupportedTypeAliasDeclaration"){}class Me extends L.TaggedError("CannotBuildTypeReferenceMetadata"){}class Y extends S.Service()("@TSDataBuilders/Parser",{effect:S.gen(function*(){let t=yield*Ae.FileSystem,i=yield*ae,{jsdocTag:m}=yield*F;return{generateBuildersMetadata:S.fnUntraced(function*(e){let p=yield*S.orDie(t.readFileString(e)),s=yield*S.try({try:()=>{return new gt().createSourceFile(e,p,{overwrite:!0}).getTypeAliases().filter((l)=>l.getJsDocs().flatMap((E)=>E.getTags().flatMap((h)=>h.getTagName())).includes(m)).map((l)=>{let E=l.getName();if(!l.isExported())return H.left(new Ue({path:e,typeName:E}));let h=l.getTypeNode();if(!(h?.isKind(se.TypeLiteral)||h?.isKind(se.TypeReference)))return H.left(new Re({path:e,typeName:l.getName()}));return H.right({name:l.getName(),node:h})}).filter(Boolean)},catch:(r)=>new Le({cause:r})}),n=yield*S.all(s.map((r)=>r));return yield*S.all(n.map(({name:r,node:y})=>i.generateMetadata({typeNode:y,optional:!1}).pipe(S.map((o)=>({name:r,shape:o,path:e})),S.catchTags({UnsupportedSyntaxKindError:(o)=>S.fail(new ve({kind:o.kind,raw:o.raw,path:e,typeName:r})),CannotBuildTypeReferenceMetadata:(o)=>S.fail(new je({kind:o.kind,raw:o.raw,path:e,typeName:r}))}))))},S.catchTags({ParserError:(e)=>S.die(e),UnexportedDatabuilderError:(e)=>S.dieMessage(`[Parser]: Unexported databuilder ${e.typeName} at ${e.path}`),RichUnsupportedSyntaxKindError:(e)=>S.dieMessage(`[Parser]: Unsupported syntax kind of id: ${e.kind} with raw type: ${e.raw} found in type ${e.typeName} in file ${e.path}`),RichCannotBuildTypeReferenceMetadata:(e)=>S.dieMessage(`[Parser]: Cannot build type reference metadata with kind of id: ${e.kind} with raw type: ${e.raw} found in type ${e.typeName} in file ${e.path}. Is it a root of databuilder?`),UnsupportedBuilderTypeError:(e)=>S.dieMessage(`[Parser]: Unsupported builder type ${e.typeName} in file ${e.path}.`)}))}}),dependencies:[ae.Default]}){}class Le extends W.TaggedError("ParserError"){}class Ue extends W.TaggedError("UnexportedDatabuilderError"){}class Re extends W.TaggedError("UnsupportedBuilderTypeError"){}class ve extends W.TaggedError("RichUnsupportedSyntaxKindError"){}class je extends W.TaggedError("RichCannotBuildTypeReferenceMetadata"){}import*as _e from"effect/Chunk";import*as K from"effect/Effect";import*as Ge from"effect/Function";var We=K.gen(function*(){let t=yield*G,i=yield*Y,m=yield*R,e=yield*t.find(),p=yield*K.all(_e.map(e,(s)=>i.generateBuildersMetadata(s)),{concurrency:"unbounded"}).pipe(K.map((s)=>s.flatMap(Ge.identity)));if(p.length===0)return;yield*m.create(p)});var Ct=M.make("ts-databuilders",xe),Ye=Ct.pipe(M.withHandler(()=>We),M.provide((t)=>Z.mergeAll(G.Default,Y.Default,R.Default).pipe(Z.provide(Z.effect(F,Ee(t))))),M.run({name:"Typescript Databuilders generator",version:"v0.0.1"}));var bt=ze.mergeAll(J.Default,Ke.layer);Ye(process.argv).pipe(Tt.provide(bt),Ze.runMain);
|
|
21
|
+
`;function at(t){let i=[];function m(e){switch(e.kind){case"BUILDER":i.push(e.name);break;case"TYPE_LITERAL":Object.values(e.metadata).forEach(m);break;case"UNION":case"TUPLE":e.members.forEach(m);break;case"RECORD":m(e.keyType),m(e.valueType);break}}return Object.values(t).forEach(m),i}class R extends N.Service()("@TSDataBuilders/Builders",{effect:N.gen(function*(){let t=yield*De.FileSystem,i=yield*te,{outputDir:m}=yield*F;return{create:N.fnUntraced(function*(e){if(yield*N.orDie(t.exists(m)))yield*N.orDie(t.remove(m,{recursive:!0}));yield*N.orDie(t.makeDirectory(m,{recursive:!0})),yield*i.generateBaseBuilder();let s=e.map((r)=>r.name),n=s.filter((r,y)=>s.indexOf(r)!==y),f=[...new Set(n)];if(n.length>0)return yield*N.dieMessage(`Duplicated builders: ${f.join(", ")}`);yield*N.all(e.map((r)=>i.generateBuilder(r)),{concurrency:"unbounded"})})}}),dependencies:[te.Default]}){}import*as d from"@effect/cli/Options";import{Option as fe}from"effect";import*as v from"effect/HashMap";import*as b from"effect/Schema";var ct=d.text("jsdoc-tag").pipe(d.withDescription("JSDoc tag used to mark types for data building generation."),d.withSchema(U.fields.jsdocTag),d.optional),lt=d.text("output-dir").pipe(d.withAlias("o"),d.withDescription("Output directory for generated builders."),d.withSchema(U.fields.outputDir),d.optional),mt=d.text("include").pipe(d.withAlias("i"),d.withDescription("Glob pattern for files included while searching for jsdoc tag."),d.withSchema(U.fields.include),d.optional),ft=d.text("file-suffix").pipe(d.withDescription("File suffix for created builder files."),d.withSchema(U.fields.fileSuffix),d.optional),dt=d.text("builder-suffix").pipe(d.withDescription("Suffix for generated classes."),d.withSchema(U.fields.builderSuffix),d.optional),pt=d.keyValueMap("defaults").pipe(d.withDescription("Default values to be used in data builder constructor."),d.withSchema(b.HashMapFromSelf({key:b.Literal("string","number","boolean"),value:b.String}).pipe(b.transform(b.Struct({string:b.String,number:b.NumberFromString,boolean:b.BooleanFromString}).pipe(b.partial),{decode:(t)=>{return{string:t.pipe(v.get("string"),fe.getOrUndefined),number:t.pipe(v.get("number"),fe.getOrUndefined),boolean:t.pipe(v.get("boolean"),fe.getOrUndefined)}},encode:(t)=>{return v.make(["string",t.string],["number",t.number],["boolean",t.boolean])},strict:!1}))),d.optional),xe={jsdocTag:ct,outputDir:lt,include:mt,fileSuffix:ft,builderSuffix:dt,defaults:pt};import*as A from"effect/Chunk";import*as x from"effect/Effect";import*as $e from"effect/Function";import*as _ from"effect/Option";import*as ie from"effect/Stream";import*as Fe from"effect/Data";import*as Ne from"effect/Effect";import*as Be from"effect/Stream";import{glob as ut}from"glob";class V extends Ne.Service()("@TSDataBuilders/TreeWalker",{succeed:{walk:(t)=>{return Be.fromAsyncIterable(ut.stream(t,{cwd:".",nodir:!0}),(i)=>new ke({cause:i}))}}}){}class ke extends Fe.TaggedError("TreeWalkerError"){}import*as Oe from"@effect/platform/FileSystem";import*as j from"effect/Effect";import*as I from"effect/Stream";class re extends j.Service()("@TSDataBuilders/FileContentChecker",{effect:j.gen(function*(){let t=yield*Oe.FileSystem,i=new TextDecoder;return{check:j.fnUntraced(function*(m){let{content:e,filePath:p}=m;return yield*I.orDie(t.stream(p,{chunkSize:16384})).pipe(I.map((f)=>i.decode(f,{stream:!0})),I.mapAccum("",(f,r)=>{let y=f+r;return[y.slice(-e.length+1),y.includes(e)]}),I.find(Boolean),I.runCollect)})}})}){}class G extends x.Service()("@TSDataBuilders/Finder",{effect:x.gen(function*(){let t=yield*re,i=yield*V,{include:m,jsdocTag:e}=yield*F,p=`@${e}`;return{find:x.fnUntraced(function*(){return yield*i.walk(m).pipe(ie.mapEffect((f)=>t.check({filePath:f,content:p}).pipe(x.map(A.map((r)=>r?_.some(f):_.none()))),{concurrency:"unbounded"}),ie.runCollect,x.map(A.flatMap($e.identity)),x.map(A.filter((f)=>_.isSome(f))),x.map(A.map((f)=>f.value)))},x.catchTag("TreeWalkerError",(s)=>x.die(s)))}}),dependencies:[V.Default,re.Default]}){}import*as Ae from"@effect/platform/FileSystem";import*as W from"effect/Data";import*as S from"effect/Effect";import*as H from"effect/Either";import{Project as gt,SyntaxKind as se}from"ts-morph";import*as L from"effect/Data";import*as c from"effect/Effect";import*as u from"effect/Match";import*as we from"effect/Option";import{Node as yt,SyntaxKind as g}from"ts-morph";import{randomUUID as St}from"node:crypto";import*as ne from"effect/Effect";class oe extends ne.Service()("@TSDataBuilders/RandomUUID",{succeed:{generate:ne.sync(()=>St())}}){}class ae extends c.Service()("@TSDataBuilders/TypeNodeParser",{effect:c.gen(function*(){let{jsdocTag:t}=yield*F,i=yield*oe,m=(p)=>c.gen(function*(){let{type:s,contextNode:n,optional:f}=p,r=s.getProperties();if(!s.isObject()||r.length===0)return yield*new Me({raw:s.getText(),kind:n.getKind()});let y={};for(let o of r){let l=o.getName(),E=o.getTypeAtLocation(n),h=o.isOptional(),C=n.getProject().createSourceFile(`__temp_${yield*i.generate}.ts`,`type __T = ${E.getText()}`,{overwrite:!0}),$=C.getTypeAliasOrThrow("__T").getTypeNodeOrThrow(),w=yield*c.suspend(()=>e({typeNode:$,optional:h}));y[l]=w,n.getProject().removeSourceFile(C)}return{kind:"TYPE_LITERAL",metadata:y,optional:f}}),e=(p)=>c.gen(function*(){let{typeNode:s,optional:n}=p,f=s.getKind(),r=u.value(f).pipe(u.when(u.is(g.StringKeyword),()=>c.succeed({kind:"STRING",optional:n})),u.when(u.is(g.NumberKeyword),()=>c.succeed({kind:"NUMBER",optional:n})),u.when(u.is(g.BooleanKeyword),()=>c.succeed({kind:"BOOLEAN",optional:n})),u.when(u.is(g.UndefinedKeyword),()=>c.succeed({kind:"UNDEFINED",optional:n})),u.when(u.is(g.ArrayType),()=>c.succeed({kind:"ARRAY",optional:n})),u.when(u.is(g.LiteralType),()=>c.succeed({kind:"LITERAL",literalValue:s.asKindOrThrow(g.LiteralType).getLiteral().getText(),optional:n})),u.when(u.is(g.TypeLiteral),()=>c.gen(function*(){let l=s.asKindOrThrow(g.TypeLiteral).getMembers();return{kind:"TYPE_LITERAL",metadata:yield*c.reduce(l,{},(h,C)=>c.gen(function*(){if(!C.isKind(g.PropertySignature))return h;let $=C.getTypeNode();if(!$)return h;let w=C.getNameNode().getText(),z=C.hasQuestionToken(),B=yield*c.suspend(()=>e({typeNode:$,optional:z}));return{...h,[w]:B}})),optional:n}})),u.when(u.is(g.ImportType),()=>c.gen(function*(){let o=s.asKindOrThrow(g.ImportType),l=o.getType(),E=l.getSymbol();if(!E)return yield*c.die(new Pe);let h=E.getDeclarations();if(h&&h.length>1)return yield*c.die(new de);let[C]=h;if(!C)return yield*c.die(new pe);return yield*m({type:l,contextNode:o,optional:n})})),u.when(u.is(g.TupleType),()=>c.gen(function*(){let l=s.asKindOrThrow(g.TupleType).getElements(),E=yield*c.all(l.map((h)=>c.suspend(()=>e({typeNode:h,optional:!1}))));return{kind:"TUPLE",optional:n,members:E}})),u.when(u.is(g.TypeReference),()=>c.gen(function*(){let o=s.asKindOrThrow(g.TypeReference),l=o.getTypeName().getText();if(l==="Date")return{kind:"DATE",optional:n};if(l==="Array")return{kind:"ARRAY",optional:n};let E=o.getTypeArguments();if(l==="Record"){let[O,Q]=E;if(!O||!Q)return yield*new q({kind:f,raw:s.getText()});let Je=yield*c.suspend(()=>e({typeNode:O,optional:!1})),Ve=yield*c.suspend(()=>e({typeNode:Q,optional:!1}));return{kind:"RECORD",keyType:Je,valueType:Ve,optional:n}}if(["Pick","Omit","Partial","Required","Readonly","Extract","NonNullable"].includes(l))return yield*m({type:o.getType(),contextNode:o,optional:n});let C=o.getType().getAliasSymbol();if(!C)return yield*m({type:o.getType(),contextNode:o,optional:n});let $=C.getDeclarations();if($&&$.length>1)return yield*c.die(new de);let[w]=$;if(!w)return yield*c.die(new pe);let z=C?.getJsDocTags().map((O)=>O.getName()).includes(t);if(!yt.isTypeAliasDeclaration(w))return yield*c.die(new Ie);let B=w.getTypeNode();if(!B)return yield*new q({kind:f,raw:s.getText()});if(!z)return yield*c.suspend(()=>e({typeNode:B,optional:n}));return{kind:"BUILDER",name:w.getName(),optional:n}})),u.when(u.is(g.UnionType),()=>c.gen(function*(){let o=yield*c.all(s.asKindOrThrow(g.UnionType).getTypeNodes().map((l)=>c.suspend(()=>e({typeNode:l,optional:!1}))));return{kind:"UNION",optional:n,members:o}})),u.when(u.is(g.IntersectionType),()=>c.gen(function*(){let l=s.asKindOrThrow(g.IntersectionType).getTypeNodes(),E=[g.StringKeyword,g.NumberKeyword,g.BooleanKeyword],h=l.find((C)=>E.includes(C.getKind()));if(h&&l.length>1)return{kind:"TYPE_CAST",baseTypeMetadata:yield*c.suspend(()=>e({typeNode:h,optional:!1})),optional:n};return yield*new q({kind:f,raw:s.getText()})})),u.option);if(we.isNone(r))return yield*new q({kind:f,raw:s.getText()});return yield*r.value});return{generateMetadata:e}}),dependencies:[oe.Default]}){}class q extends L.TaggedError("UnsupportedSyntaxKindError"){}class de extends L.TaggedError("MultipleSymbolDeclarationsError"){}class pe extends L.TaggedError("MissingSymbolDeclarationError"){}class Pe extends L.TaggedError("MissingSymbolError"){}class Ie extends L.TaggedError("UnsupportedTypeAliasDeclaration"){}class Me extends L.TaggedError("CannotBuildTypeReferenceMetadata"){}class Y extends S.Service()("@TSDataBuilders/Parser",{effect:S.gen(function*(){let t=yield*Ae.FileSystem,i=yield*ae,{jsdocTag:m}=yield*F;return{generateBuildersMetadata:S.fnUntraced(function*(e){let p=yield*S.orDie(t.readFileString(e)),s=yield*S.try({try:()=>{return new gt().createSourceFile(e,p,{overwrite:!0}).getTypeAliases().filter((l)=>l.getJsDocs().flatMap((E)=>E.getTags().flatMap((h)=>h.getTagName())).includes(m)).map((l)=>{let E=l.getName();if(!l.isExported())return H.left(new Ue({path:e,typeName:E}));let h=l.getTypeNode();if(!(h?.isKind(se.TypeLiteral)||h?.isKind(se.TypeReference)))return H.left(new Re({path:e,typeName:l.getName()}));return H.right({name:l.getName(),node:h})}).filter(Boolean)},catch:(r)=>new Le({cause:r})}),n=yield*S.all(s.map((r)=>r));return yield*S.all(n.map(({name:r,node:y})=>i.generateMetadata({typeNode:y,optional:!1}).pipe(S.map((o)=>({name:r,shape:o,path:e})),S.catchTags({UnsupportedSyntaxKindError:(o)=>S.fail(new ve({kind:o.kind,raw:o.raw,path:e,typeName:r})),CannotBuildTypeReferenceMetadata:(o)=>S.fail(new je({kind:o.kind,raw:o.raw,path:e,typeName:r}))}))))},S.catchTags({ParserError:(e)=>S.die(e),UnexportedDatabuilderError:(e)=>S.dieMessage(`[Parser]: Unexported databuilder ${e.typeName} at ${e.path}`),RichUnsupportedSyntaxKindError:(e)=>S.dieMessage(`[Parser]: Unsupported syntax kind of id: ${e.kind} with raw type: ${e.raw} found in type ${e.typeName} in file ${e.path}`),RichCannotBuildTypeReferenceMetadata:(e)=>S.dieMessage(`[Parser]: Cannot build type reference metadata with kind of id: ${e.kind} with raw type: ${e.raw} found in type ${e.typeName} in file ${e.path}. Is it a root of databuilder?`),UnsupportedBuilderTypeError:(e)=>S.dieMessage(`[Parser]: Unsupported builder type ${e.typeName} in file ${e.path}.`)}))}}),dependencies:[ae.Default]}){}class Le extends W.TaggedError("ParserError"){}class Ue extends W.TaggedError("UnexportedDatabuilderError"){}class Re extends W.TaggedError("UnsupportedBuilderTypeError"){}class ve extends W.TaggedError("RichUnsupportedSyntaxKindError"){}class je extends W.TaggedError("RichCannotBuildTypeReferenceMetadata"){}import*as _e from"effect/Chunk";import*as K from"effect/Effect";import*as Ge from"effect/Function";var We=K.gen(function*(){let t=yield*G,i=yield*Y,m=yield*R,e=yield*t.find(),p=yield*K.all(_e.map(e,(s)=>i.generateBuildersMetadata(s)),{concurrency:"unbounded"}).pipe(K.map((s)=>s.flatMap(Ge.identity)));if(p.length===0)return;yield*m.create(p)});var Ct=M.make("ts-databuilders",xe),Ye=Ct.pipe(M.withHandler(()=>We),M.provide((t)=>Z.mergeAll(G.Default,Y.Default,R.Default).pipe(Z.provide(Z.effect(F,Ee(t))))),M.run({name:"Typescript Databuilders generator",version:"v0.0.1"}));var bt=ze.mergeAll(J.Default,Ke.layer);Ye(process.argv).pipe(Tt.provide(bt),Ze.runMain);
|
package/package.json
CHANGED