@nemmtor/ts-databuilders 0.0.1-alpha.0

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/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 nemmtor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,14 @@
1
+ # 🧱 TS DataBuilders
2
+ DataBuilder Generator is a lightweight CLI tool that automatically generates builder classes from annotated TypeScript types.
3
+ Just add a @DataBuilder JSDoc tag, run one command, and get a fully-typed builder ready to use in your tests or factories.
4
+
5
+ Built with [Effect](https://effect.website/).
6
+
7
+ [Read about TS DataBuilders.](http://www.natpryce.com/articles/000714.html)
8
+
9
+ ## 🚀 Features
10
+ - 🔍 Scans your repo for specific pattern to understand what builders to build
11
+ - ⚡ Generates builder classes with fluent withX() methods and sensible defaults
12
+ - 🧩 Type-safe — builders are generated directly from your TypeScript types
13
+ - 🧠 Fast and Memory-efficient — processes files asynchronously and incrementally via streams
14
+ - 🛠️ Pluggable — works with any TypeScript project layout
package/dist/main.js ADDED
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+ import*as Se from"@effect/platform-node/NodeContext";import*as Re from"@effect/platform-node/NodeRuntime";import{Effect as Ve}from"effect";import*as R from"@effect/cli/Command";import*as G from"effect/Layer";import*as le from"@effect/platform/FileSystem";import*as L from"effect/Effect";import*as oe from"effect/Context";import*as I from"effect/Schema";var ae={string:"",number:0,boolean:!1},ie=I.Struct({string:I.String,number:I.NumberFromString,boolean:I.BooleanFromString});class k extends oe.Tag("Configuration")(){}import Z from"node:path";import*as me from"@effect/platform/FileSystem";import*as w from"effect/Effect";import*as T from"effect/Match";import{Project as Pe}from"ts-morph";var q=(r)=>r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z][a-z])/g,"$1-$2").replace(/_/g,"-").toLowerCase(),te=(r)=>{return r.split(/[-_\s]+/).flatMap((n)=>n.split(/(?=[A-Z])/)).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join("")},re=(r)=>{return r.split(/[-_\s]+/).flatMap((m)=>m.split(/(?=[A-Z])/)).filter(Boolean).map((m,e)=>{let o=m.toLowerCase();return e===0?o:o.charAt(0).toUpperCase()+o.slice(1)}).join("")};var se=(r)=>{let{fieldName:n,optional:m,typeName:e,isNestedBuilder:o}=r,l=n.replaceAll("'","").replaceAll('"',""),h=re(l),i=`with${te(l)}`,t=[`return this.with({ ${n}: ${h} });`],a=[`return this.with({ ${n}: ${h}.build() });`],f=o?a:t,u=[`if (!${h}) {`,` const { "${l}": _unused, ...rest } = this.build();`," return this.with(rest);","}"],C=m?[...u,...f]:f,B=`${e}['${l}']`;return{name:i,isPublic:!0,parameters:[{name:h,type:o?`DataBuilder<${B}>`:B}],statements:C}};class H extends w.Service()("@TSDataBuilders/BuilderGenerator",{effect:w.gen(function*(){let r=yield*me.FileSystem,{outputDir:n,fileSuffix:m,builderSuffix:e,defaults:o}=yield*k,l=(h)=>T.value(h).pipe(T.when({kind:"STRING"},()=>`"${o.string}"`),T.when({kind:"NUMBER"},()=>o.number),T.when({kind:"BOOLEAN"},()=>o.boolean),T.when({kind:"UNDEFINED"},()=>"undefined"),T.when({kind:"DATE"},()=>"new Date()"),T.when({kind:"ARRAY"},()=>"[]"),T.when({kind:"LITERAL"},(i)=>i.literalValue),T.when({kind:"TYPE_CAST"},(i)=>l(i.baseTypeMetadata)),T.when({kind:"TUPLE"},(i)=>{return`[${i.members.map((a)=>l(a)).map((a)=>`${a}`).join(", ")}]`}),T.when({kind:"TYPE_LITERAL"},(i)=>{return`{${Object.entries(i.metadata).filter(([a,{optional:f}])=>!f).map(([a,f])=>`${a}: ${l(f)}`).join(", ")}}`}),T.when({kind:"RECORD"},(i)=>{if(i.keyType.kind==="STRING"||i.keyType.kind==="NUMBER")return"{}";let t=l(i.keyType),a=l(i.valueType);return`{${t}: ${a}}`}),T.when({kind:"UNION"},(i)=>{let a=i.members.slice().sort((f,u)=>{let C=ce.indexOf(f.kind),B=ce.indexOf(u.kind);return(C===-1?1/0:C)-(B===-1?1/0:B)})[0];if(!a)return"never";return l(a)}),T.when({kind:"BUILDER"},(i)=>{return`new ${i.name}${e}().build()`}),T.exhaustive);return{generateBaseBuilder:w.fnUntraced(function*(){let h=Z.resolve(n,"data-builder.ts");yield*r.writeFileString(h,xe)}),generateBuilder:w.fnUntraced(function*(h){let i=new Pe,t=h.name,a=Z.resolve(n,`${q(t)}${m}.ts`),f=i.createSourceFile(a,"",{overwrite:!0}),u=Z.resolve(h.path),C=Z.relative(Z.dirname(a),u).replace(/\.ts$/,"");if(f.addImportDeclaration({namedImports:[t],isTypeOnly:!0,moduleSpecifier:C}),f.addImportDeclaration({namedImports:["DataBuilder"],moduleSpecifier:"./data-builder"}),h.shape.kind!=="TYPE_LITERAL")return yield*w.dieMessage("[BuilderGenerator]: Expected root type to be type literal");[...new Set(Me(h.shape.metadata))].forEach((g)=>{f.addImportDeclaration({namedImports:[`${g}${e}`],moduleSpecifier:`./${q(g)}${m}`})});let M=Object.entries(h.shape.metadata).filter(([g,{optional:b}])=>!b).map(([g,b])=>`${g}: ${b.kind==="TYPE_CAST"?`${l(b)} as ${t}['${g}']`:l(b)}`),P=Object.entries(h.shape.metadata).map(([g,{optional:b,kind:ee}])=>se({fieldName:g,optional:b,typeName:t,isNestedBuilder:ee==="BUILDER"})),F=`{
3
+ ${M.join(`,
4
+ `)}
5
+ }`;f.addClass({name:`${t}${e}`,isExported:!0,extends:`DataBuilder<${t}>`,methods:[{name:"constructor",statements:[`super(${F});`]},...P]}),f.saveSync()})}})}){}var ce=["UNDEFINED","BOOLEAN","NUMBER","STRING","DATE","LITERAL","TYPE_LITERAL","ARRAY","TUPLE","RECORD"],xe=`export abstract class DataBuilder<T> {
6
+ private data: T;
7
+
8
+ constructor(initialData: T) {
9
+ this.data = initialData;
10
+ }
11
+
12
+ public build(): Readonly<T> {
13
+ return structuredClone(this.data);
14
+ }
15
+
16
+ protected with(partial: Partial<T>): this {
17
+ this.data = { ...this.data, ...partial };
18
+ return this;
19
+ }
20
+ }
21
+ `;function Me(r){let n=[];function m(e){switch(e.kind){case"BUILDER":n.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(r).forEach(m),n}class O extends L.Service()("@TSDataBuilders/Builders",{effect:L.gen(function*(){let r=yield*le.FileSystem,n=yield*H,{outputDir:m}=yield*k;return{create:L.fnUntraced(function*(e){if(yield*r.exists(m))yield*r.remove(m,{recursive:!0});yield*r.makeDirectory(m,{recursive:!0}),yield*n.generateBaseBuilder(),yield*L.all(e.map((l)=>n.generateBuilder(l)),{concurrency:"unbounded"})})}}),dependencies:[H.Default]}){}import*as s from"@effect/cli/Options";import*as N from"effect/HashMap";import*as J from"effect/Option";import*as $ from"effect/Schema";var Oe=s.text("jsdocTag").pipe(s.withDescription("JSDoc tag used to mark types for data building generation."),s.withSchema($.NonEmptyTrimmedString),s.withDefault("DataBuilder")),Ne=s.text("output-dir").pipe(s.withAlias("o"),s.withDescription("Output directory for generated builders."),s.withSchema($.NonEmptyTrimmedString),s.withDefault("generated/builders")),_e=s.text("include").pipe(s.withAlias("i"),s.withDescription("Glob pattern for files included while searching for jsdoc tag."),s.withSchema($.NonEmptyTrimmedString),s.withDefault("src/**/*.ts{,x}")),Ae=s.text("file-suffix").pipe(s.withDescription("File suffix for created builder files."),s.withSchema($.NonEmptyTrimmedString),s.withDefault(".builder")),Ue=s.text("builder-suffix").pipe(s.withDescription("Suffix for generated classes."),s.withSchema($.NonEmptyTrimmedString),s.withDefault("Builder")),je=s.keyValueMap("defaults").pipe(s.withDescription("Default values to be used in data builder constructor."),s.withSchema($.HashMapFromSelf({key:$.Literal("string","number","boolean"),value:$.String}).pipe($.transform(ie,{decode:(r)=>{return{string:r.pipe(N.get("string"),J.getOrElse(()=>"")),number:r.pipe(N.get("number"),J.getOrElse(()=>"0")),boolean:r.pipe(N.get("boolean"),J.getOrElse(()=>"false"))}},encode:(r)=>{return N.make(["string",r.string],["number",r.number],["boolean",r.boolean])},strict:!1}))),s.withDefault(ae)),fe={jsdocTag:Oe,outputDir:Ne,include:_e,fileSuffix:Ae,builderSuffix:Ue,defaults:je};import*as x from"effect/Chunk";import*as D from"effect/Effect";import*as he from"effect/Function";import*as U from"effect/Option";import*as X from"effect/Stream";import*as ue from"effect/Data";import*as de from"effect/Effect";import*as pe from"effect/Stream";import{glob as We}from"glob";class _ extends de.Service()("@TSDataBuilders/TreeWalker",{succeed:{walk:(r)=>{return pe.fromAsyncIterable(We.stream(r,{cwd:".",nodir:!0}),(n)=>new ne({cause:n}))}}}){}class ne extends ue.TaggedError("TreeWalkerError"){}import{FileSystem as Ye}from"@effect/platform";import*as A from"effect/Effect";import*as S from"effect/Stream";class Q extends A.Service()("@TSDataBuilders/FileContentChecker",{effect:A.gen(function*(){let r=yield*Ye.FileSystem,n=new TextDecoder;return{check:A.fnUntraced(function*(m){let{content:e,filePath:o}=m;return yield*r.stream(o,{chunkSize:16384}).pipe(S.map((i)=>n.decode(i,{stream:!0})),S.mapAccum("",(i,t)=>{let a=i+t;return[a.slice(-e.length+1),a.includes(e)]}),S.find(Boolean),S.runCollect)})}})}){}class j extends D.Service()("@TSDataBuilders/Finder",{effect:D.gen(function*(){let r=yield*Q,{include:n,jsdocTag:m}=yield*k,e=`@${m}`;return{find:D.fnUntraced(function*(){return yield*(yield*_).walk(n).pipe(X.mapEffect((i)=>r.check({filePath:i,content:e}).pipe(D.map(x.map((t)=>t?U.some(i):U.none()))),{concurrency:"unbounded"}),X.runCollect,D.map(x.flatMap(he.identity)),D.map(x.filter((i)=>U.isSome(i))),D.map(x.map((i)=>i.value)))})}}),dependencies:[Q.Default]}){}import*as ke from"@effect/platform/FileSystem";import*as V from"effect/Data";import*as p from"effect/Effect";import*as z from"effect/Either";import{Project as Ze,SyntaxKind as ve}from"ts-morph";import*as v from"effect/Data";import*as c from"effect/Effect";import*as d from"effect/Match";import*as Ce from"effect/Option";import{Node as Ge,SyntaxKind as E}from"ts-morph";class K extends c.Service()("@TSDataBuilders/TypeNodeParser",{effect:c.gen(function*(){let{jsdocTag:r}=yield*k,n=(m)=>c.gen(function*(){let{typeNode:e,optional:o}=m,l=e.getKind(),h=d.value(l).pipe(d.when(d.is(E.StringKeyword),()=>c.succeed({kind:"STRING",optional:o})),d.when(d.is(E.NumberKeyword),()=>c.succeed({kind:"NUMBER",optional:o})),d.when(d.is(E.BooleanKeyword),()=>c.succeed({kind:"BOOLEAN",optional:o})),d.when((t)=>t===E.TypeReference&&e.getText()==="Date",()=>c.succeed({kind:"DATE",optional:o})),d.when((t)=>t===E.UndefinedKeyword,()=>c.succeed({kind:"UNDEFINED",optional:o})),d.when((t)=>t===E.ArrayType,()=>c.succeed({kind:"ARRAY",optional:o})),d.when((t)=>t===E.LiteralType,()=>c.succeed({kind:"LITERAL",literalValue:e.asKindOrThrow(E.LiteralType).getLiteral().getText(),optional:o})),d.when((t)=>t===E.TypeLiteral,()=>c.gen(function*(){let a=e.asKindOrThrow(E.TypeLiteral).getMembers();return{kind:"TYPE_LITERAL",metadata:yield*c.reduce(a,{},(u,C)=>c.gen(function*(){if(!C.isKind(E.PropertySignature))return u;let B=C.getTypeNode();if(!B)return u;let M=C.getNameNode().getText(),P=C.hasQuestionToken(),F=yield*c.suspend(()=>n({typeNode:B,optional:P}));return{...u,[M]:F}})),optional:o}})),d.when(d.is(E.TupleType),()=>c.gen(function*(){let a=e.asKindOrThrow(E.TupleType).getElements(),f=yield*c.all(a.map((u)=>c.suspend(()=>n({typeNode:u,optional:!1}))));return{kind:"TUPLE",optional:o,members:f}})),d.when(d.is(E.TypeReference),()=>c.gen(function*(){let t=e.asKindOrThrow(E.TypeReference),a=t.getTypeName().getText(),f=t.getTypeArguments();if(a==="Record"){let[F,g]=f;if(!F||!g)return yield*new y({kind:l,raw:e.getText()});let b=yield*c.suspend(()=>n({typeNode:F,optional:!1})),ee=yield*c.suspend(()=>n({typeNode:g,optional:!1}));return{kind:"RECORD",keyType:b,valueType:ee,optional:o}}if(a==="Array")return{kind:"ARRAY",optional:o};let u=t.getType().getAliasSymbol();if(!u)return yield*new Te;let C=u.getDeclarations();if(C&&C.length>1)return yield*new Ee;let[B]=C;if(!B)return yield*new Be;let M=u?.getJsDocTags().map((F)=>F.getName()).includes(r);if(!Ge.isTypeAliasDeclaration(B))throw Error("TODO: for non-type-alias declarations (interfaces, etc.)");let P=B.getTypeNode();if(!P)return yield*new y({kind:l,raw:e.getText()});if(!M)return yield*c.suspend(()=>n({typeNode:P,optional:o}));return{kind:"BUILDER",name:B.getName(),optional:o}})),d.when(d.is(E.UnionType),()=>c.gen(function*(){let t=yield*c.all(e.asKindOrThrow(E.UnionType).getTypeNodes().map((a)=>c.suspend(()=>n({typeNode:a,optional:!1}))));return{kind:"UNION",optional:o,members:t}})),d.when(d.is(E.IntersectionType),()=>c.gen(function*(){let a=e.asKindOrThrow(E.IntersectionType).getTypeNodes(),f=[E.StringKeyword,E.NumberKeyword,E.BooleanKeyword],u=a.find((C)=>f.includes(C.getKind()));if(u&&a.length>1)return{kind:"TYPE_CAST",baseTypeMetadata:yield*c.suspend(()=>n({typeNode:u,optional:!1})),optional:o};throw Error("TODO: handle it")})),d.option);if(Ce.isNone(h))return yield*new y({kind:l,raw:e.getText()});return yield*h.value});return{generateMetadata:n}})}){}class y extends v.TaggedError("UnsupportedSyntaxKindError"){}class Ee extends v.TaggedError("MultipleSymbolDeclarationsError"){}class Be extends v.TaggedError("MissingSymbolDeclarationError"){}class Te extends v.TaggedError("MissingSymbolError"){}class W extends p.Service()("@TSDataBuilders/Parser",{effect:p.gen(function*(){let r=yield*ke.FileSystem,n=yield*K,{jsdocTag:m}=yield*k;return{generateBuildersMetadata:p.fnUntraced(function*(e){let o=yield*r.readFileString(e),l=yield*p.try({try:()=>{return new Ze().createSourceFile(e,o,{overwrite:!0}).getTypeAliases().filter((u)=>u.getJsDocs().flatMap((C)=>C.getTags().flatMap((B)=>B.getTagName())).includes(m)).map((u)=>{let C=u.getName();if(!u.isExported())return z.left(new ge({path:e,typeName:C}));let B=u.getTypeNode();if(!B||!B.isKind(ve.TypeLiteral))return z.left(new De({path:e,typeName:u.getName()}));return z.right({name:u.getName(),node:B})}).filter(Boolean)},catch:(t)=>new $e({cause:t})}),h=yield*p.all(l.map((t)=>t));return yield*p.all(h.map(({name:t,node:a})=>n.generateMetadata({typeNode:a,optional:!1}).pipe(p.map((f)=>({name:t,shape:f,path:e})),p.catchTag("UnsupportedSyntaxKindError",(f)=>p.fail(new be({kind:f.kind,raw:f.raw,path:e,typeName:t}))))))},p.catchTags({ParserError:(e)=>p.die(e),UnexportedDatabuilderError:(e)=>p.dieMessage(`[Parser]: Unexported databuilder ${e.typeName} at ${e.path}`),RichUnsupportedSyntaxKindError:(e)=>p.dieMessage(`[Parser]: Unsupported syntax kind of id: ${e.kind} with raw type: ${e.raw} found in type ${e.typeName} in file ${e.path}`),UnsupportedBuilderTypeError:(e)=>p.dieMessage(`[Parser]: Unsupported builder type ${e.typeName} in file ${e.path}.`)}))}}),dependencies:[K.Default]}){}class $e extends V.TaggedError("ParserError"){}class ge extends V.TaggedError("UnexportedDatabuilderError"){}class De extends V.TaggedError("UnsupportedBuilderTypeError"){}class be extends V.TaggedError("RichUnsupportedSyntaxKindError"){}import*as we from"effect/Chunk";import*as Y from"effect/Effect";import*as Fe from"effect/Function";var Ie=Y.gen(function*(){let r=yield*j,n=yield*W,m=yield*O,e=yield*r.find(),o=yield*Y.all(we.map(e,(l)=>n.generateBuildersMetadata(l)),{concurrency:"unbounded"}).pipe(Y.map((l)=>l.flatMap(Fe.identity)));if(o.length===0)return;yield*m.create(o)});var ze=R.make("ts-databuilders",fe),Le=ze.pipe(R.withHandler(()=>Ie),R.provide((r)=>G.mergeAll(j.Default,W.Default,O.Default,_.Default).pipe(G.provide(G.succeed(k,k.of(r))))),R.run({name:"Typescript Databuilders generator",version:"v0.0.1"}));Le(process.argv).pipe(Ve.provide(Se.layer),Re.runMain);
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "$schema": "https://json.schemastore.org/package.json",
3
+ "name": "@nemmtor/ts-databuilders",
4
+ "type": "module",
5
+ "private": false,
6
+ "description": "CLI tool that automatically generates builder classes from annotated TypeScript types.",
7
+ "keywords": [
8
+ "typescript",
9
+ "codegen",
10
+ "data-builder",
11
+ "testing"
12
+ ],
13
+ "author": {
14
+ "name": "nemmtor",
15
+ "url": "https://github.com/nemmtor"
16
+ },
17
+ "license": "MIT",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/nemmtor/ts-databuilders.git"
21
+ },
22
+ "bin": {
23
+ "ts-databuilders": "./dist/main.js"
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "scripts": {
29
+ "build:node": "bun build src/main.ts --target node --outfile dist/main.js --production --packages external",
30
+ "start": "bun --console-depth 10 src/main.ts",
31
+ "format": "biome format",
32
+ "format:fix": "biome format --write",
33
+ "lint": "biome lint",
34
+ "lint:fix": "biome lint --write",
35
+ "check-actions": "pnpm exec biome check --formatter-enabled=false --linter-enabled=false",
36
+ "check-actions:fix": "pnpm exec biome check --formatter-enabled=false --linter-enabled=false --write",
37
+ "check-types": "tsc -b tsconfig.json",
38
+ "check-knip": "knip",
39
+ "check-dep": "depcruise --output-type err-long src"
40
+ },
41
+ "devDependencies": {
42
+ "@biomejs/biome": "^2.2.7",
43
+ "@effect/language-service": "^0.47.3",
44
+ "@total-typescript/ts-reset": "^0.6.1",
45
+ "@types/bun": "^1.3.0",
46
+ "dependency-cruiser": "^17.1.0",
47
+ "knip": "^5.66.2"
48
+ },
49
+ "peerDependencies": {
50
+ "typescript": "^5.9.3"
51
+ },
52
+ "dependencies": {
53
+ "@effect/cli": "^0.71.0",
54
+ "@effect/platform": "^0.92.1",
55
+ "@effect/platform-node": "^0.98.4",
56
+ "effect": "^3.18.4",
57
+ "glob": "^11.0.3",
58
+ "ts-morph": "^27.0.2"
59
+ },
60
+ "version": "0.0.1-alpha.0"
61
+ }