@nemmtor/ts-databuilders 0.0.1-alpha.3 → 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 +4 -4
- package/package.json +3 -2
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
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as
|
|
3
|
-
${
|
|
2
|
+
import*as Ke from"@effect/platform-node/NodeContext";import*as Ze from"@effect/platform-node/NodeRuntime";import{Effect as Tt}from"effect";import*as ze from"effect/Layer";import*as M from"@effect/cli/Command";import*as Z from"effect/Layer";import*as De from"@effect/platform/FileSystem";import*as N from"effect/Effect";import*as ce from"@effect/platform/FileSystem";import*as he from"@effect/platform/Path";import*as Se from"effect/Context";import*as D from"effect/Effect";import*as k from"effect/Option";import*as a from"effect/Schema";import*as X from"effect/Effect";class J extends X.Service()("@TSDataBuilders/Process",{succeed:{cwd:X.sync(()=>process.cwd())}}){}var qe="ts-databuilders.json",ye=a.Struct({jsdocTag:a.NonEmptyTrimmedString,outputDir:a.NonEmptyTrimmedString,include:a.NonEmptyTrimmedString,fileSuffix:a.NonEmptyTrimmedString,builderSuffix:a.NonEmptyTrimmedString,defaults:a.Struct({string:a.String,number:a.Number,boolean:a.Boolean})}),ge=ye.make({jsdocTag:"DataBuilder",outputDir:"generated/builders",include:"src/**/*.ts{,x}",fileSuffix:".builder",builderSuffix:"Builder",defaults:{string:"",number:0,boolean:!1}}),He=ye.pipe(a.omit("defaults"),a.extend(a.Struct({$schema:a.optional(a.String),defaults:a.Struct({string:a.String,number:a.Number,boolean:a.Boolean}).pipe(a.partial)})),a.partial);class F extends Se.Tag("Configuration")(){}var U=a.Struct({jsdocTag:a.NonEmptyTrimmedString,outputDir:a.NonEmptyTrimmedString,include:a.NonEmptyTrimmedString,fileSuffix:a.NonEmptyTrimmedString,builderSuffix:a.NonEmptyTrimmedString,defaults:a.Struct({string:a.String,number:a.Number,boolean:a.Boolean}).pipe(a.partial)}),Ee=(t)=>D.gen(function*(){let m=yield*(yield*J).cwd,p=(yield*he.Path).join(m,qe),s=yield*et(p),n=yield*Qe({providedConfiguration:t,configFileContent:s});return F.of(n)}),Qe=(t)=>D.gen(function*(){let i=Xe(t),m=t.providedConfiguration.defaults.pipe(k.getOrElse(()=>({}))),e=k.flatMap(t.configFileContent,(f)=>k.fromNullable(f.defaults)).pipe(k.getOrElse(()=>({}))),p=Object.fromEntries(Object.entries(m).filter(([f,r])=>typeof r<"u")),n={...Object.fromEntries(Object.entries(e).filter(([f,r])=>typeof r<"u")),...p};return{builderSuffix:yield*i("builderSuffix"),include:yield*i("include"),fileSuffix:yield*i("fileSuffix"),jsdocTag:yield*i("jsdocTag"),outputDir:yield*i("outputDir"),defaults:{...ge.defaults,...n}}}),Xe=(t)=>(i)=>t.providedConfiguration[i].pipe(D.orElse(()=>k.flatMap(t.configFileContent,(m)=>k.fromNullable(m[i]))),D.orElseSucceed(()=>ge[i])),et=(t)=>D.gen(function*(){let i=yield*ce.FileSystem;if(yield*D.orDie(i.exists(t))){let e=yield*tt(t),p=yield*a.decodeUnknown(He)(e);return k.some(p)}else return k.none()}),tt=(t)=>D.gen(function*(){let i=yield*ce.FileSystem,m=yield*D.orDie(i.readFileString(t));return yield*D.try({try:()=>JSON.parse(m),catch:(e)=>`[FileSystem] Unable to read and parse JSON file from '${t}': ${String(e)}`})}).pipe(D.orDie);import{Path as it}from"@effect/platform";import*as be from"@effect/platform/FileSystem";import*as P from"effect/Effect";import*as T from"effect/Match";import{Project as nt}from"ts-morph";var ee=(t)=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z][a-z])/g,"$1-$2").replace(/_/g,"-").toLowerCase(),le=(t)=>{return t.split(/[-_\s]+/).flatMap((i)=>i.split(/(?=[A-Z])/)).filter(Boolean).map((i)=>i.charAt(0).toUpperCase()+i.slice(1).toLowerCase()).join("")},me=(t)=>{return t.split(/[-_\s]+/).flatMap((m)=>m.split(/(?=[A-Z])/)).filter(Boolean).map((m,e)=>{let p=m.toLowerCase();return e===0?p:p.charAt(0).toUpperCase()+p.slice(1)}).join("")};var Ce=(t)=>{let{fieldName:i,optional:m,typeName:e,isNestedBuilder:p}=t,s=i.replaceAll("'","").replaceAll('"',""),n=me(s),f=`with${le(s)}`,r=[`return this.with({ ${i}: ${n} });`],y=[`return this.with({ ${i}: ${n}.build() });`],o=p?y:r,l=[`if (!${n}) {`,` const { "${s}": _unused, ...rest } = this.build();`," return this.with(rest);","}"],E=m?[...l,...o]:o,h=`${e}['${s}']`;return{name:f,isPublic:!0,parameters:[{name:n,type:p?`DataBuilder<${h}>`:h}],statements:E}};class te extends P.Service()("@TSDataBuilders/BuilderGenerator",{effect:P.gen(function*(){let t=yield*be.FileSystem,i=yield*it.Path,{outputDir:m,fileSuffix:e,builderSuffix:p,defaults:s}=yield*F,n=(f)=>T.value(f).pipe(T.when({kind:"STRING"},()=>`"${s.string}"`),T.when({kind:"NUMBER"},()=>s.number),T.when({kind:"BOOLEAN"},()=>s.boolean),T.when({kind:"UNDEFINED"},()=>"undefined"),T.when({kind:"DATE"},()=>"new Date()"),T.when({kind:"ARRAY"},()=>"[]"),T.when({kind:"LITERAL"},(r)=>r.literalValue),T.when({kind:"TYPE_CAST"},(r)=>n(r.baseTypeMetadata)),T.when({kind:"TUPLE"},(r)=>{return`[${r.members.map((o)=>n(o)).map((o)=>`${o}`).join(", ")}]`}),T.when({kind:"TYPE_LITERAL"},(r)=>{return`{${Object.entries(r.metadata).filter(([o,{optional:l}])=>!l).map(([o,l])=>`${o}: ${n(l)}`).join(", ")}}`}),T.when({kind:"RECORD"},(r)=>{if(r.keyType.kind==="STRING"||r.keyType.kind==="NUMBER")return"{}";let y=n(r.keyType),o=n(r.valueType);return`{${y}: ${o}}`}),T.when({kind:"UNION"},(r)=>{let o=r.members.slice().sort((l,E)=>{let h=Te.indexOf(l.kind),C=Te.indexOf(E.kind);return(h===-1?1/0:h)-(C===-1?1/0:C)})[0];if(!o)return"never";return n(o)}),T.when({kind:"BUILDER"},(r)=>{return`new ${r.name}${p}().build()`}),T.exhaustive);return{generateBaseBuilder:P.fnUntraced(function*(){let f=i.resolve(m,"data-builder.ts");yield*P.orDie(t.writeFileString(f,ot))}),generateBuilder:P.fnUntraced(function*(f){let r=new nt,y=f.name,o=i.resolve(m,`${ee(y)}${e}.ts`),l=r.createSourceFile(o,"",{overwrite:!0}),E=i.resolve(f.path),h=i.relative(i.dirname(o),E).replace(/\.ts$/,"");if(l.addImportDeclaration({namedImports:[y],isTypeOnly:!0,moduleSpecifier:h}),l.addImportDeclaration({namedImports:["DataBuilder"],moduleSpecifier:"./data-builder"}),f.shape.kind!=="TYPE_LITERAL")return yield*P.dieMessage("[BuilderGenerator]: Expected root type to be type literal");[...new Set(at(f.shape.metadata))].forEach((B)=>{l.addImportDeclaration({namedImports:[`${B}${p}`],moduleSpecifier:`./${ee(B)}${e}`})});let $=Object.entries(f.shape.metadata).filter(([B,{optional:O}])=>!O).map(([B,O])=>`${B}: ${O.kind==="TYPE_CAST"?`${n(O)} as ${y}['${B}']`:n(O)}`),w=Object.entries(f.shape.metadata).map(([B,{optional:O,kind:Q}])=>Ce({fieldName:B,optional:O,typeName:y,isNestedBuilder:Q==="BUILDER"})),z=`{
|
|
3
|
+
${$.join(`,
|
|
4
4
|
`)}
|
|
5
|
-
}`;
|
|
5
|
+
}`;l.addClass({name:`${y}${p}`,isExported:!0,extends:`DataBuilder<${y}>`,methods:[{name:"constructor",statements:[`super(${z});`]},...w]}),l.saveSync()})}})}){}var Te=["UNDEFINED","BOOLEAN","NUMBER","STRING","DATE","LITERAL","TYPE_LITERAL","ARRAY","TUPLE","RECORD"],ot=`export abstract class DataBuilder<T> {
|
|
6
6
|
private data: T;
|
|
7
7
|
|
|
8
8
|
constructor(initialData: T) {
|
|
@@ -18,4 +18,4 @@ import*as We from"@effect/platform-node/NodeContext";import*as Ye from"@effect/p
|
|
|
18
18
|
return this;
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
-
`;function nt(t){let n=[];function i(e){switch(e.kind){case"BUILDER":n.push(e.name);break;case"TYPE_LITERAL":Object.values(e.metadata).forEach(i);break;case"UNION":case"TUPLE":e.members.forEach(i);break;case"RECORD":i(e.keyType),i(e.valueType);break}}return Object.values(t).forEach(i),n}class I extends $.Service()("@TSDataBuilders/Builders",{effect:$.gen(function*(){let t=yield*Ne.FileSystem,n=yield*X,{outputDir:i}=yield*x;return{create:$.fnUntraced(function*(e){if(yield*t.exists(i))yield*t.remove(i,{recursive:!0});yield*t.makeDirectory(i,{recursive:!0}),yield*n.generateBaseBuilder();let r=e.map((m)=>m.name),f=r.filter((m,a)=>r.indexOf(m)!==a),o=[...new Set(f)];if(f.length>0)return yield*$.dieMessage(`Duplicated builders: ${o.join(", ")}`);yield*$.all(e.map((m)=>n.generateBuilder(m)),{concurrency:"unbounded"})})}}),dependencies:[X.Default]}){}import*as p from"@effect/cli/Options";import*as U from"effect/HashMap";import*as T from"effect/Schema";import{Option as se}from"effect";var it=p.text("jsdocTag").pipe(p.withDescription("JSDoc tag used to mark types for data building generation."),p.withSchema(A.fields.jsdocTag),p.optional),ot=p.text("output-dir").pipe(p.withAlias("o"),p.withDescription("Output directory for generated builders."),p.withSchema(A.fields.outputDir),p.optional),at=p.text("include").pipe(p.withAlias("i"),p.withDescription("Glob pattern for files included while searching for jsdoc tag."),p.withSchema(A.fields.include),p.optional),st=p.text("file-suffix").pipe(p.withDescription("File suffix for created builder files."),p.withSchema(A.fields.fileSuffix),p.optional),ct=p.text("builder-suffix").pipe(p.withDescription("Suffix for generated classes."),p.withSchema(A.fields.builderSuffix),p.optional),lt=p.keyValueMap("defaults").pipe(p.withDescription("Default values to be used in data builder constructor."),p.withSchema(T.HashMapFromSelf({key:T.Literal("string","number","boolean"),value:T.String}).pipe(T.transform(T.Struct({string:T.String,number:T.NumberFromString,boolean:T.BooleanFromString}).pipe(T.partial),{decode:(t)=>{return{string:t.pipe(U.get("string"),se.getOrUndefined),number:t.pipe(U.get("number"),se.getOrUndefined),boolean:t.pipe(U.get("boolean"),se.getOrUndefined)}},encode:(t)=>{return U.make(["string",t.string],["number",t.number],["boolean",t.boolean])},strict:!1}))),p.optional),ke={jsdocTag:it,outputDir:ot,include:at,fileSuffix:st,builderSuffix:ct,defaults:lt};import*as M from"effect/Chunk";import*as O from"effect/Effect";import*as $e from"effect/Function";import*as v from"effect/Option";import*as te from"effect/Stream";import*as De from"effect/Data";import*as Fe from"effect/Effect";import*as Be from"effect/Stream";import{glob as mt}from"glob";class R extends Fe.Service()("@TSDataBuilders/TreeWalker",{succeed:{walk:(t)=>{return Be.fromAsyncIterable(mt.stream(t,{cwd:".",nodir:!0}),(n)=>new Oe({cause:n}))}}}){}class Oe extends De.TaggedError("TreeWalkerError"){}import{FileSystem as dt}from"@effect/platform";import*as j from"effect/Effect";import*as P from"effect/Stream";class ee extends j.Service()("@TSDataBuilders/FileContentChecker",{effect:j.gen(function*(){let t=yield*dt.FileSystem,n=new TextDecoder;return{check:j.fnUntraced(function*(i){let{content:e,filePath:l}=i;return yield*t.stream(l,{chunkSize:16384}).pipe(P.map((o)=>n.decode(o,{stream:!0})),P.mapAccum("",(o,m)=>{let a=o+m;return[a.slice(-e.length+1),a.includes(e)]}),P.find(Boolean),P.runCollect)})}})}){}class _ extends O.Service()("@TSDataBuilders/Finder",{effect:O.gen(function*(){let t=yield*ee,{include:n,jsdocTag:i}=yield*x,e=`@${i}`;return{find:O.fnUntraced(function*(){return yield*(yield*R).walk(n).pipe(te.mapEffect((o)=>t.check({filePath:o,content:e}).pipe(O.map(M.map((m)=>m?v.some(o):v.none()))),{concurrency:"unbounded"}),te.runCollect,O.map(M.flatMap($e.identity)),O.map(M.filter((o)=>v.isSome(o))),O.map(M.map((o)=>o.value)))})}}),dependencies:[ee.Default]}){}import*as Le from"@effect/platform/FileSystem";import*as G from"effect/Data";import*as y from"effect/Effect";import*as q from"effect/Either";import{Project as ut,SyntaxKind as ie}from"ts-morph";import{randomUUID as ft}from"node:crypto";import*as V from"effect/Data";import*as d from"effect/Effect";import*as u from"effect/Match";import*as we from"effect/Option";import{Node as pt,SyntaxKind as E}from"ts-morph";class ne extends d.Service()("@TSDataBuilders/TypeNodeParser",{effect:d.gen(function*(){let{jsdocTag:t}=yield*x,n=(e)=>d.gen(function*(){let{type:l,contextNode:r,optional:f}=e,o=l.getProperties();if(!l.isObject()||o.length===0)return yield*new Pe({raw:l.getText(),kind:r.getKind()});let m={};for(let a of o){let c=a.getName(),g=a.getTypeAtLocation(r),S=a.isOptional(),h=r.getProject().createSourceFile(`__temp_${ft()}.ts`,`type __T = ${g.getText()}`,{overwrite:!0}),D=h.getTypeAliasOrThrow("__T").getTypeNodeOrThrow(),B=yield*d.suspend(()=>i({typeNode:D,optional:S}));m[c]=B,r.getProject().removeSourceFile(h)}return{kind:"TYPE_LITERAL",metadata:m,optional:f}}),i=(e)=>d.gen(function*(){let{typeNode:l,optional:r}=e,f=l.getKind(),o=u.value(f).pipe(u.when(u.is(E.StringKeyword),()=>d.succeed({kind:"STRING",optional:r})),u.when(u.is(E.NumberKeyword),()=>d.succeed({kind:"NUMBER",optional:r})),u.when(u.is(E.BooleanKeyword),()=>d.succeed({kind:"BOOLEAN",optional:r})),u.when(u.is(E.UndefinedKeyword),()=>d.succeed({kind:"UNDEFINED",optional:r})),u.when(u.is(E.ArrayType),()=>d.succeed({kind:"ARRAY",optional:r})),u.when(u.is(E.LiteralType),()=>d.succeed({kind:"LITERAL",literalValue:l.asKindOrThrow(E.LiteralType).getLiteral().getText(),optional:r})),u.when(u.is(E.TypeLiteral),()=>d.gen(function*(){let c=l.asKindOrThrow(E.TypeLiteral).getMembers();return{kind:"TYPE_LITERAL",metadata:yield*d.reduce(c,{},(S,h)=>d.gen(function*(){if(!h.isKind(E.PropertySignature))return S;let D=h.getTypeNode();if(!D)return S;let B=h.getNameNode().getText(),Z=h.hasQuestionToken(),N=yield*d.suspend(()=>i({typeNode:D,optional:Z}));return{...S,[B]:N}})),optional:r}})),u.when(u.is(E.ImportType),()=>d.gen(function*(){let a=l.asKindOrThrow(E.ImportType),c=a.getType(),g=c.getSymbol();if(!g)throw Error("TODO: missing symbol");let S=g.getDeclarations();if(S&&S.length>1)return yield*new ce;let[h]=S;if(!h)return yield*new le;return yield*n({type:c,contextNode:a,optional:r})})),u.when(u.is(E.TupleType),()=>d.gen(function*(){let c=l.asKindOrThrow(E.TupleType).getElements(),g=yield*d.all(c.map((S)=>d.suspend(()=>i({typeNode:S,optional:!1}))));return{kind:"TUPLE",optional:r,members:g}})),u.when(u.is(E.TypeReference),()=>d.gen(function*(){let a=l.asKindOrThrow(E.TypeReference),c=a.getTypeName().getText();if(c==="Date")return{kind:"DATE",optional:r};if(c==="Array")return{kind:"ARRAY",optional:r};let g=a.getTypeArguments();if(c==="Record"){let[F,H]=g;if(!F||!H)return yield*new re({kind:f,raw:l.getText()});let Ze=yield*d.suspend(()=>i({typeNode:F,optional:!1})),ze=yield*d.suspend(()=>i({typeNode:H,optional:!1}));return{kind:"RECORD",keyType:Ze,valueType:ze,optional:r}}if(["Pick","Omit","Partial","Required","Readonly","Extract","NonNullable"].includes(c))return yield*n({type:a.getType(),contextNode:a,optional:r});let h=a.getType().getAliasSymbol();if(!h)return yield*n({type:a.getType(),contextNode:a,optional:r});let D=h.getDeclarations();if(D&&D.length>1)return yield*new ce;let[B]=D;if(!B)return yield*new le;let Z=h?.getJsDocTags().map((F)=>F.getName()).includes(t);if(!pt.isTypeAliasDeclaration(B))throw Error("TODO: for non-type-alias declarations (interfaces, etc.)");let N=B.getTypeNode();if(!N)return yield*new re({kind:f,raw:l.getText()});if(!Z)return yield*d.suspend(()=>i({typeNode:N,optional:r}));return{kind:"BUILDER",name:B.getName(),optional:r}})),u.when(u.is(E.UnionType),()=>d.gen(function*(){let a=yield*d.all(l.asKindOrThrow(E.UnionType).getTypeNodes().map((c)=>d.suspend(()=>i({typeNode:c,optional:!1}))));return{kind:"UNION",optional:r,members:a}})),u.when(u.is(E.IntersectionType),()=>d.gen(function*(){let c=l.asKindOrThrow(E.IntersectionType).getTypeNodes(),g=[E.StringKeyword,E.NumberKeyword,E.BooleanKeyword],S=c.find((h)=>g.includes(h.getKind()));if(S&&c.length>1)return{kind:"TYPE_CAST",baseTypeMetadata:yield*d.suspend(()=>i({typeNode:S,optional:!1})),optional:r};throw Error("TODO: handle it")})),u.option);if(we.isNone(o))return yield*new re({kind:f,raw:l.getText()});return yield*o.value});return{generateMetadata:i}})}){}class re extends V.TaggedError("UnsupportedSyntaxKindError"){}class ce extends V.TaggedError("MultipleSymbolDeclarationsError"){}class le extends V.TaggedError("MissingSymbolDeclarationError"){}class Pe extends V.TaggedError("CannotBuildTypeReferenceMetadata"){}class W extends y.Service()("@TSDataBuilders/Parser",{effect:y.gen(function*(){let t=yield*Le.FileSystem,n=yield*ne,{jsdocTag:i}=yield*x;return{generateBuildersMetadata:y.fnUntraced(function*(e){let l=yield*t.readFileString(e),r=yield*y.try({try:()=>{return new ut().createSourceFile(e,l,{overwrite:!0}).getTypeAliases().filter((g)=>g.getJsDocs().flatMap((S)=>S.getTags().flatMap((h)=>h.getTagName())).includes(i)).map((g)=>{let S=g.getName();if(!g.isExported())return q.left(new Ae({path:e,typeName:S}));let h=g.getTypeNode();if(!(h?.isKind(ie.TypeLiteral)||h?.isKind(ie.TypeReference)))return q.left(new Ie({path:e,typeName:g.getName()}));return q.right({name:g.getName(),node:h})}).filter(Boolean)},catch:(m)=>new Me({cause:m})}),f=yield*y.all(r.map((m)=>m));return yield*y.all(f.map(({name:m,node:a})=>n.generateMetadata({typeNode:a,optional:!1}).pipe(y.map((c)=>({name:m,shape:c,path:e})),y.catchTags({UnsupportedSyntaxKindError:(c)=>y.fail(new Ue({kind:c.kind,raw:c.raw,path:e,typeName:m})),CannotBuildTypeReferenceMetadata:(c)=>y.fail(new Re({kind:c.kind,raw:c.raw,path:e,typeName:m}))}))))},y.catchTags({ParserError:(e)=>y.die(e),UnexportedDatabuilderError:(e)=>y.dieMessage(`[Parser]: Unexported databuilder ${e.typeName} at ${e.path}`),RichUnsupportedSyntaxKindError:(e)=>y.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)=>y.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)=>y.dieMessage(`[Parser]: Unsupported builder type ${e.typeName} in file ${e.path}.`)}))}}),dependencies:[ne.Default]}){}class Me extends G.TaggedError("ParserError"){}class Ae extends G.TaggedError("UnexportedDatabuilderError"){}class Ie extends G.TaggedError("UnsupportedBuilderTypeError"){}class Ue extends G.TaggedError("RichUnsupportedSyntaxKindError"){}class Re extends G.TaggedError("RichCannotBuildTypeReferenceMetadata"){}import*as je from"effect/Chunk";import*as Y from"effect/Effect";import*as ve from"effect/Function";var _e=Y.gen(function*(){let t=yield*_,n=yield*W,i=yield*I,e=yield*t.find(),l=yield*Y.all(je.map(e,(r)=>n.generateBuildersMetadata(r)),{concurrency:"unbounded"}).pipe(Y.map((r)=>r.flatMap(ve.identity)));if(l.length===0)return;yield*i.create(l)});var ht=L.make("ts-databuilders",ke),Ge=ht.pipe(L.withHandler(()=>_e),L.provide((t)=>K.mergeAll(_.Default,W.Default,I.Default,R.Default).pipe(K.provide(K.effect(x,Ce(t))))),L.run({name:"Typescript Databuilders generator",version:"v0.0.1"}));var yt=Ke.mergeAll(pe,We.layer);Ge(process.argv).pipe(St.provide(yt),Ye.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
|
@@ -36,7 +36,8 @@
|
|
|
36
36
|
"check-actions:fix": "pnpm exec biome check --formatter-enabled=false --linter-enabled=false --write",
|
|
37
37
|
"check-types": "tsc -b tsconfig.json",
|
|
38
38
|
"check-knip": "knip",
|
|
39
|
-
"check-dep": "depcruise --output-type err-long src"
|
|
39
|
+
"check-dep": "depcruise --output-type err-long src",
|
|
40
|
+
"gen:schema": "bun scripts/generate-schema.ts"
|
|
40
41
|
},
|
|
41
42
|
"devDependencies": {
|
|
42
43
|
"@biomejs/biome": "^2.2.7",
|
|
@@ -57,5 +58,5 @@
|
|
|
57
58
|
"glob": "^11.0.3",
|
|
58
59
|
"ts-morph": "^27.0.2"
|
|
59
60
|
},
|
|
60
|
-
"version": "0.0.1-alpha.
|
|
61
|
+
"version": "0.0.1-alpha.5"
|
|
61
62
|
}
|