@nemmtor/ts-databuilders 0.0.1-alpha.1 → 0.0.1-alpha.10

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.
Files changed (3) hide show
  1. package/README.md +454 -10
  2. package/package.json +26 -12
  3. package/dist/main.js +0 -21
package/README.md CHANGED
@@ -1,14 +1,458 @@
1
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.
2
+ Automatically generate type-safe builder classes from your TypeScript types to write cleaner, more focused tests.
4
3
 
5
- Built with [Effect](https://effect.website/).
4
+ ## Installation
5
+ Install the package:
6
+ ```bash
7
+ # npm
8
+ npm install -D @nemmtor/ts-databuilders
6
9
 
7
- [Read about TS DataBuilders.](http://www.natpryce.com/articles/000714.html)
10
+ # pnpm
11
+ pnpm add -D @nemmtor/ts-databuilders
8
12
 
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
13
+ # yarn
14
+ yarn add -D @nemmtor/ts-databuilders
15
+ ```
16
+
17
+ ## Configuration
18
+ All configuration is optional with sensible defaults.
19
+
20
+ ### Initialize Config File (optional)
21
+ Generate a default `ts-databuilders.json` configuration file:
22
+ ```bash
23
+ pnpm ts-databuilders init
24
+ ```
25
+ You can also generate configuration file by providing values step by step in an interactive wizard:
26
+ ```bash
27
+ pnpm ts-databuilders init --wizard
28
+ ```
29
+
30
+ ### Configure via CLI flags (optional):
31
+ ```bash
32
+ pnpm ts-databuilders --output-dir="src/__generated__" --jsdoc-tag=MyBuilder
33
+ ```
34
+ You can also provide configuration by going through interactive wizard:
35
+ ```bash
36
+ pnpm ts-databuilders --wizard
37
+ ```
38
+
39
+ ### Options Reference
40
+
41
+ | Name | Flag | Description | Default |
42
+ |---------------|-------------------------------------------------------|-----------------------------------------|----------------------|
43
+ | jsdocTag | `--jsdoc-tag` | JSDoc tag to mark types for generation | `DataBuilder` |
44
+ | inlineDefaultJsdocTag | `--inline-default-jsdoc-tag` | JSDoc tag used to set default value of given field. | `DataBuilderDefault` |
45
+ | outputDir | `--output-dir -o` | Output directory for generated builders | `generated/builders` |
46
+ | include | `--include -i` | Glob pattern for source files | `src/**/*.ts{,x}` |
47
+ | fileSuffix | `--file-suffix` | File suffix for builder files | `.builder` |
48
+ | builderSuffix | `--builder-suffix` | Class name suffix | `Builder` |
49
+ | defaults | `--default-string --default-number --default-boolean` | Default values for primitives | See example above |
50
+
51
+ **Priority:** CLI flags > Config file > Built-in defaults
52
+
53
+ #### Debugging
54
+ In order to turn on debug logs pass a flag: `--log-level debug`.
55
+
56
+ ## Quick Start
57
+ **1. Annotate your types with JSDoc:**
58
+ ```ts
59
+ /**
60
+ * @DataBuilder
61
+ */
62
+ type User = {
63
+ id: string;
64
+ email: string;
65
+ name: string;
66
+ isActive: boolean;
67
+ }
68
+ ```
69
+ **2. Generate builders:**
70
+ ```bash
71
+ pnpm ts-databuilders
72
+ ```
73
+ For the `User` type above, you'll get:
74
+ ```ts
75
+ import type { User } from "...";
76
+ import { DataBuilder } from "./data-builder";
77
+
78
+ export class UserBuilder extends DataBuilder<User> {
79
+ constructor() {
80
+ super({
81
+ id: "",
82
+ email: "",
83
+ name: "",
84
+ isActive: false
85
+ });
86
+ }
87
+
88
+ withId(id: User['id']) {
89
+ return this.with({ id });
90
+ }
91
+
92
+ withEmail(email: User['email']) {
93
+ return this.with({ email });
94
+ }
95
+
96
+ withName(name: User['name']) {
97
+ return this.with({ name });
98
+ }
99
+
100
+ withIsActive(isActive: User['isActive']) {
101
+ return this.with({ isActive });
102
+ }
103
+ }
104
+ ```
105
+
106
+ **3. Use in your tests:**
107
+ ```ts
108
+ import { UserBuilder } from '...';
109
+
110
+ const testUser = new UserBuilder()
111
+ .withEmail('test@example.com')
112
+ .withIsActive(false)
113
+ .build();
114
+ ```
115
+
116
+ ## Why?
117
+ Tests often become cluttered with boilerplate when you need to create complex objects just to test one specific field. DataBuilders let you focus on what matters:
118
+ Imagine testing a case where document aggregate should emit an event when it successfully update it's content:
119
+ ```ts
120
+ it('should emit a ContentUpdatedEvent', () => {
121
+ const aggregate = DocumentAggregate.create({
122
+ id: '1',
123
+ createdAt: new Date(),
124
+ updatedAt: new Date(),
125
+ content: 'old-content'
126
+ });
127
+ const userId = '1';
128
+
129
+ aggregate.updateContent({ updatedBy: userId, content: 'new-content' });
130
+
131
+ expect(...);
132
+ })
133
+ ```
134
+ Above code is obfuscated with all of the default values you need to provide in order to satisfy typescript.
135
+ Where in reality the only thing specific to this single test is the fact that some new content was provided to `updateContent` method.
136
+
137
+ Imagine even more complex scenario:
138
+ ```tsx
139
+ it('should show validation error when email is invalid', async () => {
140
+ render(<ProfileForm defaultValues={{
141
+ firstName: '',
142
+ lastName: '',
143
+ age: 0,
144
+ socials: {
145
+ linkedin: '',
146
+ github: '',
147
+ website: '',
148
+ twitter: '',
149
+ },
150
+ address: {
151
+ street: '',
152
+ city: '',
153
+ state: '',
154
+ zip: '',
155
+ },
156
+ skills: [],
157
+ bio: '',
158
+ email: 'invalid-email'
159
+ }}
160
+ />)
161
+
162
+ await submitForm();
163
+
164
+ expect(...);
165
+ })
166
+ ```
167
+ Again - in reality you should only be worried about email, not about whole form data.
168
+
169
+ Here's how above tests could be written with databuilders:
170
+ ```ts
171
+ it('should emit a ContentUpdatedEvent', () => {
172
+ const aggregate = DocumentAggregate.create(
173
+ new CreateDocumentAggregatedPayloadBuilder().build()
174
+ );
175
+
176
+ aggregate.updateContent(
177
+ new UpdateDocumentContentPayloadBuilder().withContent('new-content').build()
178
+ );
179
+
180
+ expect(...);
181
+ })
182
+ ```
183
+
184
+ ```tsx
185
+ it('should show validation error when email is invalid', async () => {
186
+ render(<ProfileForm defaultValues={
187
+ new ProfileFormInputBuilder.withEmail('invalid-email').build()} />
188
+ )
189
+
190
+ await submitForm();
191
+
192
+ expect(...);
193
+ })
194
+ ```
195
+
196
+ This not only makes the test code less verbose but also highlights what is really being tested.
197
+
198
+ **Why not use AI for that?** While AI can generate test data, ts-databuilders is fast, free and deterministic.
199
+
200
+ [Read more about data builders.](http://www.natpryce.com/articles/000714.html)
201
+
202
+ ## Nested Builders
203
+ When your types contain complex nested objects, you can annotate their type definitions and TS DataBuilders will automatically generate nested builders, allowing you to compose them fluently.
204
+ ### Example
205
+
206
+ **Input types:**
207
+ ```ts
208
+ /**
209
+ * @DataBuilder
210
+ */
211
+ export type User = {
212
+ name: string;
213
+ address: Address;
214
+ };
215
+
216
+ /**
217
+ * @DataBuilder
218
+ */
219
+ export type Address = {
220
+ street: string;
221
+ city: string;
222
+ country: string;
223
+ };
224
+ ```
225
+ **Generated builders:**
226
+ ```ts
227
+ export class UserBuilder extends DataBuilder<User> {
228
+ constructor() {
229
+ super({
230
+ name: "",
231
+ address: new AddressBuilder().build();
232
+ });
233
+ }
234
+
235
+ withName(name: User['name']) {
236
+ return this.with({ name });
237
+ }
238
+
239
+ withAddress(address: DataBuilder<User['address']>) {
240
+ return this.with({ address: address.build() });
241
+ }
242
+ }
243
+
244
+ export class AddressBuilder extends DataBuilder<Address> {
245
+ constructor() {
246
+ super({
247
+ street: "",
248
+ city: "",
249
+ country: ""
250
+ });
251
+ }
252
+
253
+ withStreet(street: Address['street']) {
254
+ return this.with({ street });
255
+ }
256
+
257
+ withCity(city: Address['city']) {
258
+ return this.with({ city });
259
+ }
260
+
261
+ withCountry(country: Address['country']) {
262
+ return this.with({ country });
263
+ }
264
+ }
265
+ ```
266
+ **Usage:**
267
+ ```ts
268
+ // ✅ Compose builders fluently
269
+ const user = new UserBuilder()
270
+ .withName('John Doe')
271
+ .withAddress(
272
+ new AddressBuilder()
273
+ .withStreet('123 Main St')
274
+ .withCity('New York')
275
+ )
276
+ .build();
277
+ // {..., address: { street: "123 Main st", city: "New York", country: "" } }
278
+
279
+ // ✅ Use default values
280
+ const userWithDefaultAddress = new UserBuilder().build();
281
+ // {..., address: { street: "", city: "", country: "" } }
282
+
283
+ // ✅ Override just one nested field
284
+ const userWithCity = new UserBuilder()
285
+ .withAddress(
286
+ new AddressBuilder()
287
+ .withCity('San Francisco')
288
+ )
289
+ .build();
290
+ // {..., address: { street: "", city: "San Francisco", country: "" } }
291
+ ```
292
+
293
+ ## Inline Default Values
294
+
295
+ While global defaults work well for most cases, sometimes you need field-specific default values. This is especially important for specialized string types like ISO dates, UUIDs etc.
296
+
297
+ ```typescript
298
+ /** @DataBuilder */
299
+ type Order = {
300
+ id: string; // Empty string - won't work as UUID
301
+ createdAt: string; // Empty string - Invalid Date!
302
+ }
303
+
304
+ // Generated:
305
+ constructor() {
306
+ super({
307
+ id: "",
308
+ createdAt: "", // new Date("") = Invalid Date
309
+ });
310
+ }
311
+ ```
312
+
313
+ Use `@DataBuilderDefault` JSDoc tag to override defaults per field:
314
+ ```typescript
315
+ /** @DataBuilder */
316
+ type Order = {
317
+ /** @DataBuilderDefault '550e8400-e29b-41d4-a716-446655440000' */
318
+ id: string;
319
+
320
+ /** @DataBuilderDefault '2025-11-05T15:32:58.727Z' */
321
+ createdAt: string;
322
+ }
323
+
324
+ // Generated:
325
+ constructor() {
326
+ super({
327
+ id: '550e8400-e29b-41d4-a716-446655440000',
328
+ createdAt: '2025-11-05T15:32:58.727Z',
329
+ });
330
+ }
331
+ ```
332
+
333
+ ## Supported Types
334
+
335
+ The library supports a wide range of TypeScript type features:
336
+
337
+ ✅ **Primitives & Built-ins**
338
+ - `string`, `number`, `boolean`, `Date`
339
+ - Literal types: `'active' | 'inactive'`, `1 | 2 | 3`
340
+
341
+ ✅ **Complex Structures**
342
+ - Objects and nested objects
343
+ - Arrays: `string[]`, `Array<number>`
344
+ - Tuples: `[string, number]`
345
+ - Records: `Record<string, string>` `Record<'foo' | 'bar', string>`
346
+
347
+ ✅ **Type Operations**
348
+ - Unions: `string | number | true | false`
349
+ - Intersections: `A & B`
350
+ - Utility types: `Pick<T, K>`, `Omit<T, K>`, `Partial<T>`, `Required<T>`, `Readonly<T>`, `Extract<T, U>`, `NonNullable<T>`
351
+ - Branded types: `type UserId = string & { __brand: 'UserId' }`
352
+
353
+ ✅ **References**
354
+ - Type references from the same file
355
+ - Type references from other files
356
+ - External library types (e.g., `z.infer<typeof schema>`)
357
+
358
+ **For a comprehensive example** of supported types, check out the [example-data/bar.ts](https://github.com/nemmtor/ts-databuilders/blob/main/example-data/bar.ts) file in the repository. This file is used during development and demonstrates complex real-world type scenarios.
359
+
360
+ ## Important Rules & Limitations
361
+
362
+ ### Unique Builder Names
363
+ Each type annotated with the JSDoc tag must have a **unique name** across your codebase:
364
+ ```ts
365
+ // ❌ Error: Duplicate builder names
366
+ // In file-a.ts
367
+ /** @DataBuilder */
368
+ export type User = { name: string };
369
+
370
+ // In file-b.ts
371
+ /** @DataBuilder */
372
+ export type User = { email: string }; // 💥 Duplicate!
373
+ ```
374
+
375
+ ### Exported Types Only
376
+ Types must be **exported** to generate builders:
377
+ ```ts
378
+ // ❌ Won't work
379
+ /** @DataBuilder */
380
+ type User = { name: string };
381
+
382
+ // ✅ Works
383
+ /** @DataBuilder */
384
+ export type User = { name: string };
385
+ ```
386
+
387
+ ### Type Aliases Only
388
+ Currently, only **type aliases** are supported as root builder types. Interfaces, classes etc. are not supported:
389
+ ```ts
390
+ // ❌ Not supported
391
+ /** @DataBuilder */
392
+ export interface User {
393
+ name: string;
394
+ }
395
+
396
+ // ❌ Not supported
397
+ /** @DataBuilder */
398
+ export class User {
399
+ name: string;
400
+ }
401
+
402
+ // ✅ Supported
403
+ /** @DataBuilder */
404
+ export type User = {
405
+ name: string;
406
+ };
407
+ ```
408
+
409
+ ### Unsupported TypeScript Features
410
+
411
+ Some TypeScript features are not yet supported and will cause generation errors:
412
+
413
+ - **Recursive types**: Types that reference themselves
414
+ ```ts
415
+ // ❌ Not supported
416
+ type TreeNode = {
417
+ value: string;
418
+ children: TreeNode[]; // Self-reference
419
+ };
420
+ ```
421
+
422
+ - **Function types**: Properties that are functions
423
+ ```ts
424
+ // ❌ Not supported
425
+ type WithCallback = {
426
+ onSave: (data: string) => void;
427
+ };
428
+ ```
429
+
430
+ - typeof, keyof, any, unknown, bigint, symbol
431
+
432
+ ### Alpha Stage
433
+ ⚠️ **This library is in active development**
434
+
435
+ - Breaking changes may occur
436
+ - Not all edge cases are covered yet
437
+ - Test thoroughly before using in production
438
+
439
+ **Found an issue?** Please [report it on GitHub](https://github.com/nemmtor/ts-databuilders/issues) with:
440
+ - A minimal reproducible example (if possible)
441
+ - The type definition causing the issue
442
+ - The error message received
443
+ - Your `ts-databuilders.json` config and any provided CLI flags (if applicable)
444
+
445
+ You can also turn on debug logs by passing `--log-level debug` flag.
446
+
447
+ Your feedback helps improve the library for everyone! 🙏
448
+
449
+ ## Similar Projects
450
+ - [effect-builder](https://github.com/slashlifeai/effect-builder) - a runtime library for building objects with Effect Schema validation.
451
+
452
+ ## Contributing
453
+
454
+ Contributions welcome! Please open an issue or PR on [GitHub](https://github.com/nemmtor/ts-databuilders).
455
+
456
+ ## License
457
+
458
+ MIT © [nemmtor](https://github.com/nemmtor)
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@nemmtor/ts-databuilders",
4
+ "version": "0.0.1-alpha.10",
4
5
  "type": "module",
5
6
  "private": false,
6
7
  "description": "CLI tool that automatically generates builder classes from annotated TypeScript types.",
@@ -26,8 +27,11 @@
26
27
  "dist"
27
28
  ],
28
29
  "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",
30
+ "build": "tsup",
31
+ "test": "vitest run",
32
+ "test:watch": "vitest",
33
+ "test:coverage": "vitest run --coverage",
34
+ "start": "tsx src/main.ts",
31
35
  "format": "biome format",
32
36
  "format:fix": "biome format --write",
33
37
  "lint": "biome lint",
@@ -36,26 +40,36 @@
36
40
  "check-actions:fix": "pnpm exec biome check --formatter-enabled=false --linter-enabled=false --write",
37
41
  "check-types": "tsc -b tsconfig.json",
38
42
  "check-knip": "knip",
39
- "check-dep": "depcruise --output-type err-long src"
43
+ "check-dep": "depcruise --output-type err-long src",
44
+ "gen:schema": "tsx scripts/generate-schema.ts"
40
45
  },
41
46
  "devDependencies": {
42
- "@biomejs/biome": "^2.2.7",
43
- "@effect/language-service": "^0.47.3",
47
+ "@biomejs/biome": "^2.3.2",
48
+ "@effect/language-service": "^0.55.0",
49
+ "@effect/vitest": "^0.27.0",
44
50
  "@total-typescript/ts-reset": "^0.6.1",
45
- "@types/bun": "^1.3.0",
46
- "dependency-cruiser": "^17.1.0",
47
- "knip": "^5.66.2"
51
+ "@types/node": "^24.0.0",
52
+ "@vitest/coverage-v8": "4.0.7",
53
+ "dependency-cruiser": "^17.2.0",
54
+ "knip": "^5.66.4",
55
+ "lefthook": "^2.0.2",
56
+ "tsup": "^8.5.0",
57
+ "tsx": "^4.20.6",
58
+ "vitest": "^4.0.6"
48
59
  },
49
60
  "peerDependencies": {
50
61
  "typescript": "^5.9.3"
51
62
  },
52
63
  "dependencies": {
53
- "@effect/cli": "^0.71.0",
54
- "@effect/platform": "^0.92.1",
55
- "@effect/platform-node": "^0.98.4",
64
+ "@effect/cli": "^0.72.0",
65
+ "@effect/platform": "^0.93.0",
66
+ "@effect/platform-node": "^0.100.0",
56
67
  "effect": "^3.18.4",
57
68
  "glob": "^11.0.3",
58
69
  "ts-morph": "^27.0.2"
59
70
  },
60
- "version": "0.0.1-alpha.1"
71
+ "packageManager": "pnpm@10.20.0+sha512.cf9998222162dd85864d0a8102e7892e7ba4ceadebbf5a31f9c2fce48dfce317a9c53b9f6464d1ef9042cba2e02ae02a9f7c143a2b438cd93c91840f0192b9dd",
72
+ "engines": {
73
+ "node": ">=20.0.0"
74
+ }
61
75
  }
package/dist/main.js DELETED
@@ -1,21 +0,0 @@
1
- #!/usr/bin/env node
2
- import*as Le from"@effect/platform-node/NodeContext";import*as Pe from"@effect/platform-node/NodeRuntime";import{Effect as Qe}from"effect";import*as F from"@effect/cli/Command";import*as G from"effect/Layer";import*as he from"@effect/platform/FileSystem";import*as N from"effect/Effect";import*as le from"effect/Context";import*as M from"effect/Schema";var me={string:"",number:0,boolean:!1},de=M.Struct({string:M.String,number:M.NumberFromString,boolean:M.BooleanFromString});class b extends le.Tag("Configuration")(){}import Z from"node:path";import*as ue from"@effect/platform/FileSystem";import*as $ from"effect/Effect";import*as S from"effect/Match";import{Project as Oe}from"ts-morph";var H=(o)=>o.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z][a-z])/g,"$1-$2").replace(/_/g,"-").toLowerCase(),ne=(o)=>{return o.split(/[-_\s]+/).flatMap((p)=>p.split(/(?=[A-Z])/)).filter(Boolean).map((p)=>p.charAt(0).toUpperCase()+p.slice(1).toLowerCase()).join("")},oe=(o)=>{return o.split(/[-_\s]+/).flatMap((i)=>i.split(/(?=[A-Z])/)).filter(Boolean).map((i,e)=>{let s=i.toLowerCase();return e===0?s:s.charAt(0).toUpperCase()+s.slice(1)}).join("")};var pe=(o)=>{let{fieldName:p,optional:i,typeName:e,isNestedBuilder:s}=o,r=p.replaceAll("'","").replaceAll('"',""),m=oe(r),n=`with${ne(r)}`,c=[`return this.with({ ${p}: ${m} });`],t=[`return this.with({ ${p}: ${m}.build() });`],a=s?t:c,u=[`if (!${m}) {`,` const { "${r}": _unused, ...rest } = this.build();`," return this.with(rest);","}"],h=i?[...u,...a]:a,f=`${e}['${r}']`;return{name:n,isPublic:!0,parameters:[{name:m,type:s?`DataBuilder<${f}>`:f}],statements:h}};class J extends $.Service()("@TSDataBuilders/BuilderGenerator",{effect:$.gen(function*(){let o=yield*ue.FileSystem,{outputDir:p,fileSuffix:i,builderSuffix:e,defaults:s}=yield*b,r=(m)=>S.value(m).pipe(S.when({kind:"STRING"},()=>`"${s.string}"`),S.when({kind:"NUMBER"},()=>s.number),S.when({kind:"BOOLEAN"},()=>s.boolean),S.when({kind:"UNDEFINED"},()=>"undefined"),S.when({kind:"DATE"},()=>"new Date()"),S.when({kind:"ARRAY"},()=>"[]"),S.when({kind:"LITERAL"},(n)=>n.literalValue),S.when({kind:"TYPE_CAST"},(n)=>r(n.baseTypeMetadata)),S.when({kind:"TUPLE"},(n)=>{return`[${n.members.map((t)=>r(t)).map((t)=>`${t}`).join(", ")}]`}),S.when({kind:"TYPE_LITERAL"},(n)=>{return`{${Object.entries(n.metadata).filter(([t,{optional:a}])=>!a).map(([t,a])=>`${t}: ${r(a)}`).join(", ")}}`}),S.when({kind:"RECORD"},(n)=>{if(n.keyType.kind==="STRING"||n.keyType.kind==="NUMBER")return"{}";let c=r(n.keyType),t=r(n.valueType);return`{${c}: ${t}}`}),S.when({kind:"UNION"},(n)=>{let t=n.members.slice().sort((a,u)=>{let h=fe.indexOf(a.kind),f=fe.indexOf(u.kind);return(h===-1?1/0:h)-(f===-1?1/0:f)})[0];if(!t)return"never";return r(t)}),S.when({kind:"BUILDER"},(n)=>{return`new ${n.name}${e}().build()`}),S.exhaustive);return{generateBaseBuilder:$.fnUntraced(function*(){let m=Z.resolve(p,"data-builder.ts");yield*o.writeFileString(m,_e)}),generateBuilder:$.fnUntraced(function*(m){let n=new Oe,c=m.name,t=Z.resolve(p,`${H(c)}${i}.ts`),a=n.createSourceFile(t,"",{overwrite:!0}),u=Z.resolve(m.path),h=Z.relative(Z.dirname(t),u).replace(/\.ts$/,"");if(a.addImportDeclaration({namedImports:[c],isTypeOnly:!0,moduleSpecifier:h}),a.addImportDeclaration({namedImports:["DataBuilder"],moduleSpecifier:"./data-builder"}),m.shape.kind!=="TYPE_LITERAL")return yield*$.dieMessage("[BuilderGenerator]: Expected root type to be type literal");[...new Set(je(m.shape.metadata))].forEach((T)=>{a.addImportDeclaration({namedImports:[`${T}${e}`],moduleSpecifier:`./${H(T)}${i}`})});let x=Object.entries(m.shape.metadata).filter(([T,{optional:k}])=>!k).map(([T,k])=>`${T}: ${k.kind==="TYPE_CAST"?`${r(k)} as ${c}['${T}']`:r(k)}`),C=Object.entries(m.shape.metadata).map(([T,{optional:k,kind:L}])=>pe({fieldName:T,optional:k,typeName:c,isNestedBuilder:L==="BUILDER"})),w=`{
3
- ${x.join(`,
4
- `)}
5
- }`;a.addClass({name:`${c}${e}`,isExported:!0,extends:`DataBuilder<${c}>`,methods:[{name:"constructor",statements:[`super(${w});`]},...C]}),a.saveSync()})}})}){}var fe=["UNDEFINED","BOOLEAN","NUMBER","STRING","DATE","LITERAL","TYPE_LITERAL","ARRAY","TUPLE","RECORD"],_e=`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 je(o){let p=[];function i(e){switch(e.kind){case"BUILDER":p.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(o).forEach(i),p}class P extends N.Service()("@TSDataBuilders/Builders",{effect:N.gen(function*(){let o=yield*he.FileSystem,p=yield*J,{outputDir:i}=yield*b;return{create:N.fnUntraced(function*(e){if(yield*o.exists(i))yield*o.remove(i,{recursive:!0});yield*o.makeDirectory(i,{recursive:!0}),yield*p.generateBaseBuilder();let r=e.map((c)=>c.name),m=r.filter((c,t)=>r.indexOf(c)!==t),n=[...new Set(m)];if(m.length>0)return yield*N.dieMessage(`Duplicated builders: ${n.join(", ")}`);yield*N.all(e.map((c)=>p.generateBuilder(c)),{concurrency:"unbounded"})})}}),dependencies:[J.Default]}){}import*as d from"@effect/cli/Options";import*as R from"effect/HashMap";import*as Q from"effect/Option";import*as B from"effect/Schema";var ve=d.text("jsdocTag").pipe(d.withDescription("JSDoc tag used to mark types for data building generation."),d.withSchema(B.NonEmptyTrimmedString),d.withDefault("DataBuilder")),We=d.text("output-dir").pipe(d.withAlias("o"),d.withDescription("Output directory for generated builders."),d.withSchema(B.NonEmptyTrimmedString),d.withDefault("generated/builders")),Ye=d.text("include").pipe(d.withAlias("i"),d.withDescription("Glob pattern for files included while searching for jsdoc tag."),d.withSchema(B.NonEmptyTrimmedString),d.withDefault("src/**/*.ts{,x}")),Ge=d.text("file-suffix").pipe(d.withDescription("File suffix for created builder files."),d.withSchema(B.NonEmptyTrimmedString),d.withDefault(".builder")),Ze=d.text("builder-suffix").pipe(d.withDescription("Suffix for generated classes."),d.withSchema(B.NonEmptyTrimmedString),d.withDefault("Builder")),ze=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(de,{decode:(o)=>{return{string:o.pipe(R.get("string"),Q.getOrElse(()=>"")),number:o.pipe(R.get("number"),Q.getOrElse(()=>"0")),boolean:o.pipe(R.get("boolean"),Q.getOrElse(()=>"false"))}},encode:(o)=>{return R.make(["string",o.string],["number",o.number],["boolean",o.boolean])},strict:!1}))),d.withDefault(me)),ye={jsdocTag:ve,outputDir:We,include:Ye,fileSuffix:Ge,builderSuffix:Ze,defaults:ze};import*as I from"effect/Chunk";import*as D from"effect/Effect";import*as Te from"effect/Function";import*as _ from"effect/Option";import*as ee from"effect/Stream";import*as Ee from"effect/Data";import*as ge from"effect/Effect";import*as Se from"effect/Stream";import{glob as Ke}from"glob";class U extends ge.Service()("@TSDataBuilders/TreeWalker",{succeed:{walk:(o)=>{return Se.fromAsyncIterable(Ke.stream(o,{cwd:".",nodir:!0}),(p)=>new ie({cause:p}))}}}){}class ie extends Ee.TaggedError("TreeWalkerError"){}import{FileSystem as Ve}from"@effect/platform";import*as O from"effect/Effect";import*as A from"effect/Stream";class X extends O.Service()("@TSDataBuilders/FileContentChecker",{effect:O.gen(function*(){let o=yield*Ve.FileSystem,p=new TextDecoder;return{check:O.fnUntraced(function*(i){let{content:e,filePath:s}=i;return yield*o.stream(s,{chunkSize:16384}).pipe(A.map((n)=>p.decode(n,{stream:!0})),A.mapAccum("",(n,c)=>{let t=n+c;return[t.slice(-e.length+1),t.includes(e)]}),A.find(Boolean),A.runCollect)})}})}){}class j extends D.Service()("@TSDataBuilders/Finder",{effect:D.gen(function*(){let o=yield*X,{include:p,jsdocTag:i}=yield*b,e=`@${i}`;return{find:D.fnUntraced(function*(){return yield*(yield*U).walk(p).pipe(ee.mapEffect((n)=>o.check({filePath:n,content:e}).pipe(D.map(I.map((c)=>c?_.some(n):_.none()))),{concurrency:"unbounded"}),ee.runCollect,D.map(I.flatMap(Te.identity)),D.map(I.filter((n)=>_.isSome(n))),D.map(I.map((n)=>n.value)))})}}),dependencies:[X.Default]}){}import*as Be from"@effect/platform/FileSystem";import*as v from"effect/Data";import*as E from"effect/Effect";import*as V from"effect/Either";import{Project as He,SyntaxKind as re}from"ts-morph";import{randomUUID as Ce}from"node:crypto";import*as K from"effect/Data";import*as l from"effect/Effect";import*as y from"effect/Match";import*as ke from"effect/Option";import{Node as qe,SyntaxKind as g}from"ts-morph";class te extends l.Service()("@TSDataBuilders/TypeNodeParser",{effect:l.gen(function*(){let{jsdocTag:o}=yield*b,p=(e)=>l.gen(function*(){let{node:s,optional:r}=e,m=s.getType(),n=m.getProperties();if(m.isObject()&&n.length>0){let c={};for(let t of n){let a=t.getName(),u=t.getTypeAtLocation(s),h=t.isOptional(),x=s.getProject().createSourceFile(`__temp_${Ce()}.ts`,`type __T = ${u.getText()}`,{overwrite:!0}).getTypeAliasOrThrow("__T").getTypeNodeOrThrow(),C=yield*l.suspend(()=>i({typeNode:x,optional:h}));c[a]=C}return{kind:"TYPE_LITERAL",metadata:c,optional:r}}return yield*new be({raw:m.getText(),kind:s.getKind()})}),i=(e)=>l.gen(function*(){let{typeNode:s,optional:r}=e,m=s.getKind(),n=y.value(m).pipe(y.when(y.is(g.StringKeyword),()=>l.succeed({kind:"STRING",optional:r})),y.when(y.is(g.NumberKeyword),()=>l.succeed({kind:"NUMBER",optional:r})),y.when(y.is(g.BooleanKeyword),()=>l.succeed({kind:"BOOLEAN",optional:r})),y.when((t)=>t===g.UndefinedKeyword,()=>l.succeed({kind:"UNDEFINED",optional:r})),y.when((t)=>t===g.ArrayType,()=>l.succeed({kind:"ARRAY",optional:r})),y.when((t)=>t===g.LiteralType,()=>l.succeed({kind:"LITERAL",literalValue:s.asKindOrThrow(g.LiteralType).getLiteral().getText(),optional:r})),y.when((t)=>t===g.TypeLiteral,()=>l.gen(function*(){let a=s.asKindOrThrow(g.TypeLiteral).getMembers();return{kind:"TYPE_LITERAL",metadata:yield*l.reduce(a,{},(h,f)=>l.gen(function*(){if(!f.isKind(g.PropertySignature))return h;let x=f.getTypeNode();if(!x)return h;let C=f.getNameNode().getText(),w=f.hasQuestionToken(),T=yield*l.suspend(()=>i({typeNode:x,optional:w}));return{...h,[C]:T}})),optional:r}})),y.when(y.is(g.ImportType),()=>l.gen(function*(){let t=s.asKindOrThrow(g.ImportType),a=t.getType(),u=a.getSymbol();if(!u)throw Error("TODO: missing symbol");let h=u.getDeclarations();if(h&&h.length>1)return yield*new se;let[f]=h;if(!f)return yield*new ce;let x=u.getJsDocTags().map((C)=>C.getName()).includes(o);if(a.isObject()){let C=a.getProperties();if(C.length>0){let w={};for(let T of C){let k=T.getName(),L=T.getTypeAtLocation(t),ae=T.isOptional(),q=t.getProject().createSourceFile(`__temp_${Ce()}.ts`,`type __T = ${L.getText()}`,{overwrite:!0}),Re=q.getTypeAliasOrThrow("__T").getTypeNodeOrThrow(),Ue=yield*l.suspend(()=>i({typeNode:Re,optional:ae}));w[k]=Ue,t.getProject().removeSourceFile(q)}return{kind:"TYPE_LITERAL",metadata:w,optional:r}}}return yield*new z({kind:m,raw:s.getText()})})),y.when(y.is(g.TupleType),()=>l.gen(function*(){let a=s.asKindOrThrow(g.TupleType).getElements(),u=yield*l.all(a.map((h)=>l.suspend(()=>i({typeNode:h,optional:!1}))));return{kind:"TUPLE",optional:r,members:u}})),y.when(y.is(g.TypeReference),()=>l.gen(function*(){let t=s.asKindOrThrow(g.TypeReference),a=t.getTypeName().getText();if(a==="Date")return{kind:"DATE",optional:r};let u=t.getTypeArguments();if(a==="Record"){let[k,L]=u;if(!k||!L)return yield*new z({kind:m,raw:s.getText()});let ae=yield*l.suspend(()=>i({typeNode:k,optional:!1})),q=yield*l.suspend(()=>i({typeNode:L,optional:!1}));return{kind:"RECORD",keyType:ae,valueType:q,optional:r}}if(a==="Array")return{kind:"ARRAY",optional:r};if(["Pick","Omit","Partial","Required","Readonly","Extract","NonNullable"].includes(a))return yield*p({node:t,optional:r});let f=t.getType().getAliasSymbol();if(!f)return yield*p({node:t,optional:r});let x=f.getDeclarations();if(x&&x.length>1)return yield*new se;let[C]=x;if(!C)return yield*new ce;let w=f?.getJsDocTags().map((k)=>k.getName()).includes(o);if(!qe.isTypeAliasDeclaration(C))throw Error("TODO: for non-type-alias declarations (interfaces, etc.)");let T=C.getTypeNode();if(!T)return yield*new z({kind:m,raw:s.getText()});if(!w)return yield*l.suspend(()=>i({typeNode:T,optional:r}));return{kind:"BUILDER",name:C.getName(),optional:r}})),y.when(y.is(g.UnionType),()=>l.gen(function*(){let t=yield*l.all(s.asKindOrThrow(g.UnionType).getTypeNodes().map((a)=>l.suspend(()=>i({typeNode:a,optional:!1}))));return{kind:"UNION",optional:r,members:t}})),y.when(y.is(g.IntersectionType),()=>l.gen(function*(){let a=s.asKindOrThrow(g.IntersectionType).getTypeNodes(),u=[g.StringKeyword,g.NumberKeyword,g.BooleanKeyword],h=a.find((f)=>u.includes(f.getKind()));if(h&&a.length>1)return{kind:"TYPE_CAST",baseTypeMetadata:yield*l.suspend(()=>i({typeNode:h,optional:!1})),optional:r};throw Error("TODO: handle it")})),y.option);if(ke.isNone(n))return yield*new z({kind:m,raw:s.getText()});return yield*n.value});return{generateMetadata:i}})}){}class z extends K.TaggedError("UnsupportedSyntaxKindError"){}class se extends K.TaggedError("MultipleSymbolDeclarationsError"){}class ce extends K.TaggedError("MissingSymbolDeclarationError"){}class be extends K.TaggedError("CannotBuildTypeReferenceMetadata"){}class W extends E.Service()("@TSDataBuilders/Parser",{effect:E.gen(function*(){let o=yield*Be.FileSystem,p=yield*te,{jsdocTag:i}=yield*b;return{generateBuildersMetadata:E.fnUntraced(function*(e){let s=yield*o.readFileString(e),r=yield*E.try({try:()=>{return new He().createSourceFile(e,s,{overwrite:!0}).getTypeAliases().filter((u)=>u.getJsDocs().flatMap((h)=>h.getTags().flatMap((f)=>f.getTagName())).includes(i)).map((u)=>{let h=u.getName();if(!u.isExported())return V.left(new De({path:e,typeName:h}));let f=u.getTypeNode();if(!(f?.isKind(re.TypeLiteral)||f?.isKind(re.TypeReference)))return V.left(new Ne({path:e,typeName:u.getName()}));return V.right({name:u.getName(),node:f})}).filter(Boolean)},catch:(c)=>new xe({cause:c})}),m=yield*E.all(r.map((c)=>c));return yield*E.all(m.map(({name:c,node:t})=>p.generateMetadata({typeNode:t,optional:!1}).pipe(E.map((a)=>({name:c,shape:a,path:e})),E.catchTags({UnsupportedSyntaxKindError:(a)=>E.fail(new $e({kind:a.kind,raw:a.raw,path:e,typeName:c})),CannotBuildTypeReferenceMetadata:(a)=>E.fail(new we({kind:a.kind,raw:a.raw,path:e,typeName:c}))}))))},E.catchTags({ParserError:(e)=>E.die(e),UnexportedDatabuilderError:(e)=>E.dieMessage(`[Parser]: Unexported databuilder ${e.typeName} at ${e.path}`),RichUnsupportedSyntaxKindError:(e)=>E.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)=>E.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)=>E.dieMessage(`[Parser]: Unsupported builder type ${e.typeName} in file ${e.path}.`)}))}}),dependencies:[te.Default]}){}class xe extends v.TaggedError("ParserError"){}class De extends v.TaggedError("UnexportedDatabuilderError"){}class Ne extends v.TaggedError("UnsupportedBuilderTypeError"){}class $e extends v.TaggedError("RichUnsupportedSyntaxKindError"){}class we extends v.TaggedError("RichCannotBuildTypeReferenceMetadata"){}import*as Me from"effect/Chunk";import*as Y from"effect/Effect";import*as Ae from"effect/Function";var Fe=Y.gen(function*(){let o=yield*j,p=yield*W,i=yield*P,e=yield*o.find(),s=yield*Y.all(Me.map(e,(r)=>p.generateBuildersMetadata(r)),{concurrency:"unbounded"}).pipe(Y.map((r)=>r.flatMap(Ae.identity)));if(s.length===0)return;yield*i.create(s)});var Je=F.make("ts-databuilders",ye),Ie=Je.pipe(F.withHandler(()=>Fe),F.provide((o)=>G.mergeAll(j.Default,W.Default,P.Default,U.Default).pipe(G.provide(G.succeed(b,b.of(o))))),F.run({name:"Typescript Databuilders generator",version:"v0.0.1"}));Ie(process.argv).pipe(Qe.provide(Le.layer),Pe.runMain);