plantr 1.0.1

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 ADDED
@@ -0,0 +1,230 @@
1
+ # plantr
2
+
3
+ A Bun-first database seeder library with built-in faker, step workflow, and type-safe dependencies.
4
+
5
+ ## Features
6
+
7
+ - **Built-in utilities** - `faker`, `step`, and `expect` available in every seeder
8
+ - **Type-safe dependencies** - Seeder outputs are fully typed when used as dependencies
9
+ - **Automatic ordering** - Seeders run in correct order based on dependencies
10
+ - **Step workflow** - Organize seeders into steps with progress logging
11
+ - **Step caching** - Cache expensive operations across runs
12
+ - **Lifecycle hooks** - `onBeforeAll` / `onAfterAll` for setup and teardown
13
+ - **Continue on failure** - Keep seeding independent data when one seeder fails
14
+ - **Dry run mode** - Preview execution order without running
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ bun add plantr
20
+ ```
21
+
22
+ > **Note:** This library requires Bun as it uses `bun:test` for assertions.
23
+
24
+ ## Quick Start
25
+
26
+ ### 1. Create a Seeder Instance
27
+
28
+ ```typescript
29
+ // src/seed.ts
30
+ import { createSeederInstance, type BaseSeederContext } from 'plantr'
31
+ import { prisma } from './prisma'
32
+
33
+ type MyContext = BaseSeederContext & {
34
+ prisma: typeof prisma
35
+ }
36
+
37
+ export const { defineSeeder, runSeeders, runSeedersCli } = createSeederInstance<MyContext>({
38
+ context: (base) => ({
39
+ ...base,
40
+ prisma,
41
+ }),
42
+ onBeforeAll: async () => {
43
+ await prisma.$connect()
44
+ },
45
+ onAfterAll: async () => {
46
+ await prisma.$disconnect()
47
+ },
48
+ })
49
+ ```
50
+
51
+ ### 2. Define Seeders
52
+
53
+ ```typescript
54
+ // src/seeders/userSeeder.ts
55
+ import { defineSeeder } from '../seed'
56
+
57
+ export const userSeeder = defineSeeder({
58
+ name: 'userSeeder',
59
+ description: 'Creates test users',
60
+ run: async ({ prisma, faker, step, expect }) => {
61
+ const user = await step('Create admin user', async () => {
62
+ return prisma.user.create({
63
+ data: {
64
+ name: faker.person.fullName(),
65
+ email: faker.internet.email(),
66
+ role: 'admin',
67
+ },
68
+ })
69
+ })
70
+
71
+ expect(user.id).toBeDefined()
72
+
73
+ return { userId: user.id }
74
+ },
75
+ })
76
+ ```
77
+
78
+ ### 3. Define Seeders with Dependencies
79
+
80
+ ```typescript
81
+ // src/seeders/postSeeder.ts
82
+ import { defineSeeder } from '../seed'
83
+ import { userSeeder } from './userSeeder'
84
+
85
+ export const postSeeder = defineSeeder({
86
+ name: 'postSeeder',
87
+ description: 'Creates posts for users',
88
+ dependsOn: [userSeeder],
89
+ run: async ({ prisma, faker, step }, deps) => {
90
+ // deps.userSeeder is fully typed!
91
+ const { userId } = deps.userSeeder
92
+
93
+ const post = await step('Create post', async () => {
94
+ return prisma.post.create({
95
+ data: {
96
+ title: faker.lorem.sentence(),
97
+ authorId: userId,
98
+ },
99
+ })
100
+ })
101
+
102
+ return { postId: post.id }
103
+ },
104
+ })
105
+ ```
106
+
107
+ ### 4. Run Seeders
108
+
109
+ ```typescript
110
+ // src/seed.ts (continued)
111
+ import { userSeeder } from './seeders/userSeeder'
112
+ import { postSeeder } from './seeders/postSeeder'
113
+
114
+ const seeders = [userSeeder, postSeeder] as const
115
+
116
+ if (import.meta.main) {
117
+ runSeedersCli(seeders)
118
+ }
119
+ ```
120
+
121
+ Run with:
122
+ ```bash
123
+ bun run src/seed.ts
124
+ ```
125
+
126
+ ## CLI Options
127
+
128
+ ```bash
129
+ bun run src/seed.ts --help # Show help
130
+ bun run src/seed.ts --dry-run # Show execution order without running
131
+ ```
132
+
133
+ ## API
134
+
135
+ ### `createSeederInstance(config)`
136
+
137
+ ```typescript
138
+ createSeederInstance({
139
+ // Required: factory that receives base context and returns your context
140
+ context: (base) => ({ ...base, prisma }),
141
+
142
+ // Optional: cache for step caching
143
+ cache: {
144
+ get: async (key) => { /* return cached value */ },
145
+ set: async (key, value) => { /* store value */ },
146
+ },
147
+
148
+ // Optional: lifecycle hooks
149
+ onBeforeAll: async () => { /* setup */ },
150
+ onAfterAll: async () => { /* teardown */ },
151
+ })
152
+ ```
153
+
154
+ Returns `{ defineSeeder, runSeeders, runSeedersCli, isSeedingActive }`.
155
+
156
+ ### `defineSeeder(config)`
157
+
158
+ ```typescript
159
+ defineSeeder({
160
+ name: 'seederName', // Unique name
161
+ description: 'What it does', // Optional
162
+ dependsOn: [otherSeeder], // Optional dependencies
163
+ run: async (ctx, deps) => {
164
+ // ctx has faker, step, expect, and your custom context
165
+ // deps has typed outputs from dependsOn seeders
166
+ return { /* output available to dependents */ }
167
+ },
168
+ })
169
+ ```
170
+
171
+ ### `runSeeders(seeders, options?)`
172
+
173
+ ```typescript
174
+ await runSeeders(seeders, {
175
+ printResults: true, // Print results table (default: true)
176
+ verbose: true, // Print progress (default: true)
177
+ continueOnFailure: false // Continue after failures (default: false)
178
+ })
179
+ ```
180
+
181
+ ### Step Function
182
+
183
+ ```typescript
184
+ run: async ({ step }) => {
185
+ // Basic step
186
+ const result = await step('Create user', async () => {
187
+ return prisma.user.create({ ... })
188
+ })
189
+
190
+ // Cached step (requires cache config)
191
+ const cached = await step('Expensive operation', async () => {
192
+ return computeExpensiveValue()
193
+ }, { useCache: true })
194
+ }
195
+ ```
196
+
197
+ ## Seeding State
198
+
199
+ Check if seeding is active to skip side effects:
200
+
201
+ ```typescript
202
+ import { isSeedingActive } from './seed'
203
+
204
+ // In your event handlers, webhooks, etc.
205
+ if (isSeedingActive()) {
206
+ console.log('Skipping notification during seeding')
207
+ return
208
+ }
209
+ ```
210
+
211
+ ## Error Handling
212
+
213
+ ```typescript
214
+ import { CircularDependencyError, MissingDependencyError } from 'plantr'
215
+
216
+ try {
217
+ await runSeeders(seeders)
218
+ } catch (error) {
219
+ if (error instanceof CircularDependencyError) {
220
+ console.error('Circular dependency detected')
221
+ }
222
+ if (error instanceof MissingDependencyError) {
223
+ console.error('Missing dependency')
224
+ }
225
+ }
226
+ ```
227
+
228
+ ## License
229
+
230
+ MIT
@@ -0,0 +1,315 @@
1
+ import { expect } from 'bun:test'
2
+ import { faker } from '@faker-js/faker'
3
+ import { createDefineSeeder } from './define-seeder'
4
+ import { resolveDependencyOrder } from './dependency-resolver'
5
+ import { colorize } from './formatting'
6
+ import { runSeedersCore } from './run-seeders'
7
+ import { isSeedingActive, setSeedingActive } from './seeding-state'
8
+ import { createStepRunner, type SeederCache } from './step'
9
+ import type {
10
+ BaseSeederContext,
11
+ RunSeedersOptions,
12
+ Seeder,
13
+ SeederAny,
14
+ SeederConfig,
15
+ SeederResult,
16
+ } from './types'
17
+
18
+ /**
19
+ * Configuration for creating a seeder instance.
20
+ * The context factory receives the base context (faker, step, expect) and can extend it.
21
+ */
22
+ export type SeederInstanceConfig<TContext extends BaseSeederContext> = {
23
+ /**
24
+ * Factory function that creates the context for each seeder.
25
+ * Receives the base context (faker, step, expect) and should return the full context.
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * context: (base) => ({
30
+ * ...base,
31
+ * prisma,
32
+ * myHelper: () => { ... }
33
+ * })
34
+ * ```
35
+ */
36
+ context: (base: BaseSeederContext) => TContext | Promise<TContext>
37
+
38
+ /**
39
+ * Optional cache for step caching.
40
+ * Provide get/set functions to enable caching in the step runner.
41
+ *
42
+ * @example
43
+ * ```typescript
44
+ * cache: {
45
+ * get: async (key) => {
46
+ * const cached = await prisma.seedCache.findUnique({ where: { key } })
47
+ * return cached?.output as T | undefined
48
+ * },
49
+ * set: async (key, value) => {
50
+ * await prisma.seedCache.create({ data: { key, output: value } })
51
+ * }
52
+ * }
53
+ * ```
54
+ */
55
+ cache?: SeederCache
56
+
57
+ /**
58
+ * Called before all seeders run.
59
+ * Use for setup like connecting to databases.
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * onBeforeAll: async () => {
64
+ * await prisma.$connect()
65
+ * }
66
+ * ```
67
+ */
68
+ onBeforeAll?: () => void | Promise<void>
69
+
70
+ /**
71
+ * Called after all seeders complete (success or failure).
72
+ * Use for cleanup like disconnecting from databases.
73
+ *
74
+ * @example
75
+ * ```typescript
76
+ * onAfterAll: async () => {
77
+ * await prisma.$disconnect()
78
+ * }
79
+ * ```
80
+ */
81
+ onAfterAll?: () => void | Promise<void>
82
+ }
83
+
84
+ /**
85
+ * Result type for the seeder instance
86
+ */
87
+ export type SeederInstance<TContext extends BaseSeederContext> = {
88
+ /**
89
+ * Define a new seeder with typed dependencies
90
+ *
91
+ * @example
92
+ * ```typescript
93
+ * const userSeeder = defineSeeder({
94
+ * name: 'userSeeder',
95
+ * dependsOn: [orgSeeder],
96
+ * run: async (ctx, deps) => {
97
+ * const { orgId } = deps.orgSeeder
98
+ * // ctx.faker, ctx.step, ctx.expect are always available
99
+ * return { userId: 'user-1' }
100
+ * }
101
+ * })
102
+ * ```
103
+ */
104
+ defineSeeder: <
105
+ TName extends string,
106
+ TOutput,
107
+ const TDeps extends readonly SeederAny[] = readonly [],
108
+ >(
109
+ config: SeederConfig<TContext, TName, TOutput, TDeps>,
110
+ ) => Seeder<TContext, TName, TOutput>
111
+
112
+ /**
113
+ * Run an array of seeders in dependency order.
114
+ * Automatically sets seeding state to active during execution.
115
+ *
116
+ * @param seeders - Array of seeders to run
117
+ * @param options - Optional runner options
118
+ * @returns Object containing results and success status
119
+ */
120
+ runSeeders: (
121
+ seeders: readonly SeederAny[],
122
+ options?: RunSeedersOptions,
123
+ ) => Promise<{ results: SeederResult[]; success: boolean }>
124
+
125
+ /**
126
+ * Run seeders as a CLI command.
127
+ * Handles help flag, prints banner, runs seeders, and exits with proper code.
128
+ *
129
+ * @example
130
+ * ```typescript
131
+ * // At the bottom of your seed registry file:
132
+ * if (import.meta.main) {
133
+ * runSeedersCli(seeders)
134
+ * }
135
+ * ```
136
+ */
137
+ runSeedersCli: (seeders: readonly SeederAny[], options?: { name?: string }) => Promise<void>
138
+
139
+ /**
140
+ * Check if seeding is currently active.
141
+ * Use this in your application to skip side effects during seeding.
142
+ *
143
+ * @example
144
+ * ```typescript
145
+ * if (isSeedingActive()) {
146
+ * console.log('Skipping notification during seeding')
147
+ * return
148
+ * }
149
+ * ```
150
+ */
151
+ isSeedingActive: () => boolean
152
+ }
153
+
154
+ /**
155
+ * Create a seeder instance with a custom context
156
+ *
157
+ * This is the main entry point for the seeder library. The library provides
158
+ * a base context with faker, step, and expect. Consumers extend this with
159
+ * their own context (e.g. prisma, custom helpers).
160
+ *
161
+ * The seeding state is automatically managed - set to active when runSeeders
162
+ * starts and set to inactive when it completes.
163
+ *
164
+ * @example
165
+ * ```typescript
166
+ * import { createSeederInstance } from 'plantr'
167
+ *
168
+ * type MyContext = BaseSeederContext & { prisma: typeof prisma }
169
+ *
170
+ * const { defineSeeder, runSeeders, isSeedingActive } = createSeederInstance<MyContext>({
171
+ * context: (base) => ({
172
+ * ...base,
173
+ * prisma,
174
+ * }),
175
+ * cache: {
176
+ * get: async (key) => {
177
+ * const cached = await prisma.seedCache.findUnique({ where: { key } })
178
+ * return cached?.output
179
+ * },
180
+ * set: async (key, value) => {
181
+ * await prisma.seedCache.create({ data: { key, output: value } })
182
+ * }
183
+ * },
184
+ * })
185
+ *
186
+ * export { defineSeeder, isSeedingActive }
187
+ *
188
+ * // In your message/queue system:
189
+ * if (isSeedingActive()) {
190
+ * console.log('Skipping side effect during seeding')
191
+ * return
192
+ * }
193
+ *
194
+ * // Later...
195
+ * await runSeeders([seeder1, seeder2])
196
+ * ```
197
+ */
198
+ export function createSeederInstance<TContext extends BaseSeederContext = BaseSeederContext>(
199
+ config: SeederInstanceConfig<TContext>,
200
+ ): SeederInstance<TContext> {
201
+ const defineSeeder = createDefineSeeder<TContext>()
202
+
203
+ const runSeeders = async (
204
+ seeders: readonly SeederAny[],
205
+ options?: RunSeedersOptions,
206
+ ): Promise<{ results: SeederResult[]; success: boolean }> => {
207
+ // Create context once per run (not per seeder)
208
+ const { step, setSeederName } = createStepRunner({ cache: config.cache })
209
+ const baseContext: BaseSeederContext = {
210
+ faker,
211
+ step,
212
+ expect,
213
+ }
214
+ const ctx = await config.context(baseContext)
215
+
216
+ // Internal config for the runner
217
+ const internalConfig = {
218
+ context: (): TContext => ctx,
219
+ setSeederName,
220
+ // Automatically manage seeding state
221
+ onBeforeAll: async () => {
222
+ setSeedingActive(true)
223
+ if (config.onBeforeAll) {
224
+ await config.onBeforeAll()
225
+ }
226
+ },
227
+ onAfterAll: async () => {
228
+ setSeedingActive(false)
229
+ if (config.onAfterAll) {
230
+ await config.onAfterAll()
231
+ }
232
+ },
233
+ }
234
+
235
+ return runSeedersCore(seeders, internalConfig, options)
236
+ }
237
+
238
+ /**
239
+ * Run seeders as a CLI command.
240
+ * Handles help flag, dry-run flag, prints banner with seeder count, runs seeders, and exits with proper code.
241
+ *
242
+ * @param seeders - Array of seeders to run
243
+ * @param options - Optional CLI options
244
+ */
245
+ const runSeedersCli = async (
246
+ seeders: readonly SeederAny[],
247
+ options?: { name?: string },
248
+ ): Promise<void> => {
249
+ const args = process.argv.slice(2)
250
+ const name = options?.name ?? 'Seeders'
251
+
252
+ // Show help if requested
253
+ if (args.includes('--help') || args.includes('-h')) {
254
+ console.log(`
255
+ ${colorize('Usage:', 'cyan', 'bold')} bun run seed [options]
256
+
257
+ ${colorize('Options:', 'white', 'bold')}
258
+ --help, -h Show this help message
259
+ --dry-run Show execution order without running seeders
260
+
261
+ Runs all ${seeders.length} seeders in dependency order.
262
+ `)
263
+ process.exit(0)
264
+ }
265
+
266
+ // Dry run: show execution order without running
267
+ if (args.includes('--dry-run')) {
268
+ console.log(
269
+ `\n${colorize('🌱 Dry Run', 'cyan', 'bold')} ${colorize(`(${seeders.length} seeders)`, 'dim')}\n`,
270
+ )
271
+
272
+ // Create a map for quick seeder lookup
273
+ const seederMap = new Map<string, SeederAny>()
274
+ for (const seeder of seeders) {
275
+ seederMap.set(seeder.name, seeder)
276
+ }
277
+
278
+ try {
279
+ const order = resolveDependencyOrder(seeders)
280
+ console.log(colorize('Execution order:', 'white', 'bold'))
281
+ for (let i = 0; i < order.length; i++) {
282
+ const seederName = order[i]
283
+ if (!seederName) continue
284
+ const seeder = seederMap.get(seederName)
285
+ const deps = seeder?.dependsOn ?? []
286
+ const depsStr =
287
+ deps.length > 0 ? ` ${colorize(`(depends on: ${deps.join(', ')})`, 'dim')}` : ''
288
+ console.log(` ${i + 1}. ${seederName}${depsStr}`)
289
+ }
290
+ console.log('')
291
+ process.exit(0)
292
+ } catch (error) {
293
+ console.error(colorize('Failed to resolve dependencies:', 'red'))
294
+ console.error(` ${error instanceof Error ? error.message : String(error)}`)
295
+ process.exit(1)
296
+ }
297
+ }
298
+
299
+ console.log(
300
+ `\n${colorize(`🌱 Running ${name}`, 'cyan', 'bold')} ${colorize(`(${seeders.length} seeders)`, 'dim')}\n`,
301
+ )
302
+ const { success } = await runSeeders(seeders, {
303
+ printResults: true,
304
+ verbose: true,
305
+ })
306
+ process.exit(success ? 0 : 1)
307
+ }
308
+
309
+ return {
310
+ defineSeeder,
311
+ runSeeders,
312
+ runSeedersCli,
313
+ isSeedingActive,
314
+ }
315
+ }
@@ -0,0 +1,46 @@
1
+ import type { Seeder, SeederAny, SeederConfig } from './types'
2
+
3
+ /**
4
+ * Create a typed seeder definition
5
+ *
6
+ * This is the core factory that creates a seeder from a configuration.
7
+ * The seeder can then be passed to `runSeeders` for execution.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { defineSeeder } from './registries/seed'
12
+ *
13
+ * export default defineSeeder({
14
+ * name: 'createUsers',
15
+ * description: 'Seeds user data',
16
+ * dependsOn: [organizationSeeder],
17
+ * run: async (ctx, deps) => {
18
+ * // ctx contains whatever the consumer configured
19
+ * // deps.organizationSeeder is fully typed with the output of organizationSeeder
20
+ * const { organizationId } = deps.organizationSeeder
21
+ *
22
+ * // ... create users
23
+ *
24
+ * return { userIds: [...] }
25
+ * }
26
+ * })
27
+ * ```
28
+ */
29
+ export function createDefineSeeder<TContext>() {
30
+ return function defineSeeder<
31
+ TName extends string,
32
+ TOutput,
33
+ const TDeps extends readonly SeederAny[] = readonly [],
34
+ >(config: SeederConfig<TContext, TName, TOutput, TDeps>): Seeder<TContext, TName, TOutput> {
35
+ // Extract names from seeder objects at runtime
36
+ const dependsOnNames = (config.dependsOn ?? []).map((seeder) => seeder.name)
37
+
38
+ return {
39
+ name: config.name,
40
+ description: config.description,
41
+ dependsOn: dependsOnNames,
42
+ // Cast is safe because the deps object will have the correct shape at runtime
43
+ run: config.run as (ctx: TContext, deps: Record<string, unknown>) => Promise<TOutput>,
44
+ }
45
+ }
46
+ }