plantr 2.2.0 → 2.3.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/readme.md CHANGED
@@ -9,10 +9,10 @@ A TypeScript database seeder library for **Bun and Node.js (>= 22)** with built-
9
9
  - **End-to-end TypeScript** - Zero-boilerplate context inference, context-safe seeder registries, typed dependencies, typed `outputs`, discriminated-union `results`, compile-time missing dependency checks, and autocompleted `only`/`fresh`
10
10
  - **Automatic ordering & parallel DAG execution** - Runs in dependency order with critical-path scheduling across independent branches via `concurrency` / `--concurrency`
11
11
  - **Run a subset** - Run named seeders plus what they depend on (`--only`, `only`)
12
- - **Step workflow** - Organize seeders into sequential or `Promise.all` parallel steps with progress logging
12
+ - **Step workflow** - Organize seeders into sequential or `Promise.all` parallel steps with progress logging, and `mapWithLimit` for thousands of API calls a few at a time
13
13
  - **Step caching** - Skip steps that already ran, with explicit keys, canonical JSON versions, single-query `getAll` preloading, batched `setMany` writes, and a `--fresh` override
14
14
  - **Target guard** - Refuse to seed a database or emulator target that is not local unless asked to
15
- - **Lifecycle hooks** - `onBeforeAll` / `onAfterAll(ctx)` for setup and teardown
15
+ - **Setup and teardown** - `setup()` returns the run's resources (a connection, a signed-in client) for the context factory, and `teardown(resources)` always runs: after a failure, when the context factory throws, and on SIGINT or SIGTERM
16
16
  - **Continue on failure** - Keep seeding independent data when one seeder fails
17
17
  - **Dry run & list modes** - Preview execution order, target, and descriptions without running
18
18
 
@@ -33,18 +33,19 @@ pnpm add plantr
33
33
  ```typescript
34
34
  // src/seed.ts
35
35
  import { createSeederInstance } from 'plantr'
36
- import { prisma } from './prisma'
36
+ import { PrismaClient } from '@prisma/client'
37
37
 
38
38
  export const { defineSeeder, runSeeders, runSeedersCli } = createSeederInstance({
39
- // Optional: extra properties are merged onto { faker, step, expect } automatically
40
- context: () => ({ prisma }),
41
39
  target: () => process.env.DATABASE_URL,
42
- onBeforeAll: async () => {
40
+ // Optional: acquire what the run needs; teardown always gets it back
41
+ setup: async () => {
42
+ const prisma = new PrismaClient()
43
43
  await prisma.$connect()
44
+ return { prisma }
44
45
  },
45
- onAfterAll: async (ctx) => {
46
- await ctx?.prisma.$disconnect()
47
- },
46
+ teardown: ({ prisma }) => prisma.$disconnect(),
47
+ // Optional: extra properties are merged onto { faker, step, expect } automatically
48
+ context: (_base, { prisma }) => ({ prisma }),
48
49
  })
49
50
  ```
50
51
 
@@ -141,7 +142,7 @@ bun run src/seed.ts # Run every seeder
141
142
  bun run src/seed.ts postSeeder # Run postSeeder and the seeders it depends on
142
143
  bun run src/seed.ts --only a,b # Same as naming them
143
144
  bun run src/seed.ts postSeeder --fresh # Ignore and overwrite postSeeder's cached steps
144
- bun run src/seed.ts --fresh # Ignore and overwrite every cached step
145
+ bun run src/seed.ts --fresh # Run onFresh (see Fresh runs), then ignore and overwrite every cached step
145
146
  bun run src/seed.ts --concurrency 4 # Run up to 4 independent seeders in parallel (-c 4)
146
147
  bun run src/seed.ts --continue-on-failure # Keep running seeders that do not depend on a failed one
147
148
  bun run src/seed.ts --allow-remote # Seed a target that is not local (see Target guard)
@@ -159,12 +160,19 @@ An unknown flag, invalid `--concurrency`, or unknown seeder name prints the prob
159
160
 
160
161
  ```typescript
161
162
  createSeederInstance({
163
+ // Optional: acquire the run's resources (see Setup and teardown); throw to refuse the run
164
+ setup: async ({ defer }) => ({ prisma: await connect() }),
165
+
166
+ // Optional: release them; runs whenever setup returned, also on failure and SIGINT/SIGTERM
167
+ teardown: async ({ prisma }) => { await prisma.$disconnect() },
168
+
162
169
  // Optional: factory returning extra properties to merge onto { faker, step, expect }.
163
- // Receives `base` if you want to build helpers around faker/step/expect or override a base key.
164
- // Called once per run, after onBeforeAll. Omit to use BaseSeederContext directly.
165
- context: (base) => ({ prisma }),
170
+ // Receives `base` if you want to build helpers around faker/step/expect or override a base key,
171
+ // and the resources setup returned. Called once per run, after setup. Omit to use BaseSeederContext directly.
172
+ context: (base, { prisma }) => ({ prisma }),
166
173
 
167
- // Optional: cache for step caching (see Step Caching)
174
+ // Optional: cache for step caching (see Step Caching), or a function of setup's
175
+ // resources returning one: cache: ({ db }) => createCache(db)
168
176
  cache: {
169
177
  get: async (key) => { /* return the stored value, or undefined / null */ },
170
178
  set: async (key, value) => { /* store value, overwriting */ },
@@ -172,6 +180,9 @@ createSeederInstance({
172
180
  setMany: async (entries) => { /* optional: flush all writes in one batch at end of run */ },
173
181
  },
174
182
 
183
+ // Optional: reset the target before a fresh run (see Fresh runs)
184
+ onFresh: async ({ resources, seeders, all }) => { if (all) await resources.db.wipe() },
185
+
175
186
  // Optional: default parallel concurrency for independent seeders (default: 1; e.g. 4 or Infinity)
176
187
  concurrency: 4,
177
188
 
@@ -189,9 +200,12 @@ createSeederInstance({
189
200
  // so every run generates the same data even when running concurrently
190
201
  fakerSeed: 1,
191
202
 
192
- // Optional: lifecycle hooks
193
- onBeforeAll: async () => { /* setup; throw to refuse the run */ },
194
- onAfterAll: async (ctx) => { /* teardown; receives ctx (or undefined if context() threw) */ },
203
+ // Optional, with fakerSeed: also seed each step's faker from its key (see Deterministic data)
204
+ fakerSeedScope: 'step', // default: 'seeder'
205
+
206
+ // Deprecated: use setup and teardown (see Migrating from onBeforeAll and onAfterAll)
207
+ onBeforeAll: async () => { /* runs before setup; throw to refuse the run */ },
208
+ onAfterAll: async (ctx) => { /* runs before teardown; ctx is undefined if context() threw */ },
195
209
  })
196
210
  ```
197
211
 
@@ -223,6 +237,7 @@ const run = await runSeeders(seeders, {
223
237
  fresh: ['postSeeder'], // Ignore cached steps: true for all, or checked seeder names
224
238
  allowRemote: false, // Seed a non-local target (default: false)
225
239
  concurrency: 1, // Max independent seeders running in parallel (default: 1; supports Infinity)
240
+ handleSignals: true, // Tear down and exit on SIGINT/SIGTERM while running (default: true)
226
241
  })
227
242
  ```
228
243
 
@@ -239,6 +254,60 @@ When `concurrency > 1` (configured on `createSeederInstance`, per `runSeeders` c
239
254
 
240
255
  `runSeeders` **throws**, before any hook or seeder runs (and before setting the seeding flag), when the input is invalid: `DuplicateSeederError`, `MissingDependencyError`, `CircularDependencyError`, `UnknownSeederError` (a name in `only` or `fresh`), `RangeError` (invalid `concurrency`), or `SeedTargetError`.
241
256
 
257
+ ### Setup and teardown
258
+
259
+ `setup` acquires what the run needs and returns it; the context factory, a `cache` factory and `teardown` receive what it returned. A run goes:
260
+
261
+ 1. Validate the registry and options, then the target guard (both throw before anything else).
262
+ 2. `onBeforeAll` (deprecated), then `setup`.
263
+ 3. The `cache` factory, `onFresh` on a fresh run, the cache preload.
264
+ 4. The context factory, the seeders, the results table.
265
+ 5. Cleanup: flush the step cache, `onAfterAll(ctx)` (deprecated), `teardown(resources)`, then the deferred cleanups, last registered first.
266
+
267
+ Each cleanup step runs whenever the step it undoes completed, whatever failed after it:
268
+
269
+ - **A seeder fails**: the run finishes as usual (`success: false`) and tears down.
270
+ - **The context factory or the `cache` factory throws**: `teardown` gets the resources, then the run rethrows the error.
271
+ - **`setup` throws after acquiring part of its resources**: `teardown` does not run, because `setup` returned nothing to pass it. Register each resource's cleanup with `defer` as soon as you acquire it; deferred cleanups run when `setup` throws later, and after `teardown` on a run that got that far.
272
+ - **SIGINT or SIGTERM** (Ctrl+C, `docker stop`, CI cancel): no further seeder starts, the cleanup above runs once, and the process exits with 130 or 143. Seeders already running are not awaited. A second signal exits at once. Pass `handleSignals: false` to `runSeeders` to keep your own signal handlers in charge.
273
+ - **A cleanup step throws**: the rest still run. The run rethrows the first error (the one that stopped the run, if any) and prints the others to stderr.
274
+
275
+ ```typescript
276
+ createSeederInstance({
277
+ setup: async ({ defer }) => {
278
+ const db = await connectDb()
279
+ defer(() => db.close()) // runs even if signing in below throws
280
+ const api = await signIn(db, credentials)
281
+ return { db, api }
282
+ },
283
+ teardown: async ({ api }) => {
284
+ await api.signOut() // then the deferred db.close()
285
+ },
286
+ context: (_base, { db, api }) => ({ db, api }),
287
+ })
288
+ ```
289
+
290
+ #### Migrating from `onBeforeAll` and `onAfterAll`
291
+
292
+ Both still run (`onBeforeAll` before `setup`, `onAfterAll` before `teardown`) and are deprecated. Move a connection opened in `onBeforeAll` and closed in `onAfterAll` into `setup` and `teardown`, and drop the module-level variable that carried it between them:
293
+
294
+ ```typescript
295
+ // Before
296
+ let db: Db | undefined
297
+ createSeederInstance({
298
+ onBeforeAll: async () => { assertLocal(); db = await connectDb() },
299
+ context: () => ({ db: db! }),
300
+ onAfterAll: async () => { await db?.close() },
301
+ })
302
+
303
+ // After
304
+ createSeederInstance({
305
+ setup: async () => { assertLocal(); return { db: await connectDb() } },
306
+ context: (_base, { db }) => ({ db }),
307
+ teardown: ({ db }) => db.close(),
308
+ })
309
+ ```
310
+
242
311
  ### Step Function
243
312
 
244
313
  ```typescript
@@ -262,6 +331,22 @@ run: async ({ step }) => {
262
331
  }
263
332
  ```
264
333
 
334
+ ### `mapWithLimit(items, limit, fn)`
335
+
336
+ Runs `fn(item, index)` over `items` (any iterable) with at most `limit` calls in flight, for example thousands of API calls eight at a time, and resolves to the results in the order of `items`, whatever order the calls finish in. `limit` is a positive integer or `Infinity`; anything else throws `RangeError`.
337
+
338
+ ```typescript
339
+ import { mapWithLimit } from 'plantr'
340
+
341
+ await step('Create products', () =>
342
+ mapWithLimit(products, 8, (product) => api.post('/products', product)),
343
+ )
344
+ ```
345
+
346
+ It fails fast: once a call throws or rejects, no further item starts, and it rejects with that first error after the calls already in flight have settled. Nothing it started is still running when the step fails and the run tears down.
347
+
348
+ Calls in one step share its faker, and later items start as earlier ones finish, so faker draws inside `fn` come out in a different order on each run. Build the items with faker first and keep `fn` to sending them.
349
+
265
350
  ## Step Caching
266
351
 
267
352
  A cached step stores its output under the key `<seederName>:<key or slugified description>` and returns the stored output on later runs instead of running again.
@@ -271,12 +356,13 @@ A cached step stores its output under the key `<seederName>:<key or slugified de
271
356
  - **The value passes through your store.** With a JSON column, a `Date` comes back as a string and a `Map` as `{}` on the next run, so return plain JSON (ids) from cached steps.
272
357
  - **Every step must be safe to run again**: a version change, `fresh`, or a cleared cache reruns it against existing data.
273
358
  - plantr stores an envelope, `{ __plantr: 1, version?, value }`, so a step that returns `undefined` or `null` is cached too, while `undefined` or `null` returned bare from `cache.get` is treated as a cache miss. Non-null values written bare by plantr 1.x are still read as hits (when the step has no `version`).
359
+ - Pass `cache` as a function to build it from the resources `setup` returned: `cache: ({ db }) => createCache(db)`. It runs once per run, after `setup` and before the preload, so a cache stored in the seeded database needs no connection of its own. Return `undefined` to run without a cache.
274
360
  - Provide `getAll` on `cache` to preload the entire table in a single query at the start of each run instead of issuing one `get` query per cached step, and `setMany` to flush new/updated entries in one batch write before `onAfterAll` (even if a later seeder fails).
275
361
 
276
- A Prisma store:
362
+ A Prisma store, with the client from `setup`:
277
363
 
278
364
  ```typescript
279
- cache: {
365
+ cache: ({ prisma }) => ({
280
366
  get: async (key) => {
281
367
  const row = await prisma.seedCache.findUnique({ where: { key } })
282
368
  return row?.output
@@ -297,14 +383,53 @@ cache: {
297
383
  }),
298
384
  )
299
385
  },
300
- }
386
+ })
387
+ ```
388
+
389
+ ### Fresh runs
390
+
391
+ `fresh` (CLI `--fresh`) makes cached steps run again and overwrite their entries. When a step creates records whose ids the target picks, running it again creates them a second time. `onFresh` lets the project reset the target first:
392
+
393
+ ```typescript
394
+ createSeederInstance({
395
+ setup: async () => ({ db: await connectEmulator() }),
396
+ onFresh: async ({ resources: { db }, seeders, all }) => {
397
+ if (!all) {
398
+ throw new SeedUsageError(`Run --fresh without seeder names to reset the emulator (asked: ${seeders.join(', ')})`)
399
+ }
400
+ await db.wipe()
401
+ },
402
+ })
301
403
  ```
302
404
 
405
+ - It runs after `setup` and the `cache` factory and before the cache preload and the context factory, so it may wipe a cache stored in the target too.
406
+ - It runs only when at least one seeder of the run is fresh. `seeders` names them, in run order.
407
+ - `all` is true only when every registered seeder runs, and runs fresh: `fresh: true` without `only`, or `--fresh` without seeder names. With `--fresh` plus names (`seed post --fresh`), only the named seeders run fresh: the seeders they depend on still replay cached ids of records a wipe would delete. So wipe only when `all` is true, and either do nothing or refuse (as above) otherwise.
408
+ - If it throws, nothing is seeded and the run tears down.
409
+
410
+ ## Deterministic data
411
+
412
+ With `fakerSeed`, `ctx.faker` is seeded per seeder from `fakerSeed` and the seeder's name, so every run generates the same data and adding a seeder does not shift the others.
413
+
414
+ A cached step skips its function, and with it the faker draws inside. With the default `fakerSeedScope: 'seeder'`, everything the seeder draws after that step comes out different on a run where the step was cached than on one where it ran. Either make every draw before the first step, or set `fakerSeedScope: 'step'`:
415
+
416
+ ```typescript
417
+ createSeederInstance({ fakerSeed: 1, fakerSeedScope: 'step' })
418
+ ```
419
+
420
+ Each step's function then gets its own faker, seeded from `fakerSeed`, the seeder's name and the step's `key` (or its description when it has none). A key used again in the same seeder (a step in a loop) gets a counter, so each iteration draws different data, in call order. The seeder's own faker never sees a step's draws, so:
421
+
422
+ - draws inside a step, and draws after it, are the same whether earlier steps ran or came from the cache;
423
+ - steps started together with `Promise.all` each draw their own sequence, whichever finishes first;
424
+ - renaming a step without a `key` changes what it generates, as it changes its cache key.
425
+
426
+ `'seeder'` stays the default because switching changes the data steps generate once. Seeders that draw nothing inside steps generate the same data under both. Without `fakerSeed`, `fakerSeedScope` has no effect.
427
+
303
428
  ## Target guard
304
429
 
305
430
  Set `target` to the database or emulator URL the instance writes to (for example `process.env.DATABASE_URL`, `http://127.0.0.1:8080`, or `firestore://127.0.0.1:8080/demo-app`). The banner then shows its host and path, never credentials (`🌱 Running Seeders (2 seeders) → localhost:5432/app`), and a run refuses with `SeedTargetError` before `onBeforeAll` when the target is not local. Local means every host the URL names (several hosts, or a `host=` parameter, which overrides the URL's host) is loopback (`localhost`, `127.*`, `::1`, `0.0.0.0`), `*.localhost`, `host.docker.internal`, a socket directory or `file:` path, or a single-label hostname with an explicit port such as a compose service (`postgres:5432`). A bare name without a port (such as a cloud project URL like `firestore://my-prod-project`) or a target without a `scheme://` is refused. Seed anything else on purpose with `allowRemote: true` or `--allow-remote`, for example in a staging pre-deploy command.
306
431
 
307
- Without `target` there is no check. For other rules (an environment variable, a list of allowed hosts), throw from `onBeforeAll`.
432
+ Without `target` there is no check. For other rules (an environment variable, a list of allowed hosts), throw a `SeedUsageError` from `setup` before it connects; the CLI prints its message without a stack trace.
308
433
 
309
434
  ## Seeding State
310
435
 
@@ -328,8 +453,10 @@ The flag is set after validation succeeds and cleared when the run finishes, als
328
453
  import {
329
454
  CircularDependencyError,
330
455
  DuplicateSeederError,
456
+ isSeedUsageError,
331
457
  MissingDependencyError,
332
458
  SeedTargetError,
459
+ SeedUsageError,
333
460
  UnknownSeederError,
334
461
  } from 'plantr'
335
462
 
@@ -348,6 +475,19 @@ try {
348
475
  }
349
476
  ```
350
477
 
478
+ ### Usage errors
479
+
480
+ Throw `SeedUsageError` for a problem the person running the seed fixes by changing how they run it: a refused target, a missing environment variable, a bad option. `runSeedersCli` prints only its message, in red, and exits 1; a seeder that fails with one is reported by its message, without a stack trace. Every other error keeps its stack.
481
+
482
+ ```typescript
483
+ setup: async () => {
484
+ if (!process.env.SEED_ADMIN_URL) throw new SeedUsageError('Set SEED_ADMIN_URL to the Admin these emulators serve')
485
+ return { db: await connect() }
486
+ },
487
+ ```
488
+
489
+ plantr's own validation errors (`SeedTargetError`, `UnknownSeederError`, `DuplicateSeederError`, `MissingDependencyError`, `CircularDependencyError`) extend `SeedUsageError`. To mark an error class of your own without extending it, set the registered symbol `usageErrorSymbol` (`Symbol.for('plantr.usageError')`) to `true` on it; `isSeedUsageError(error)` checks for either.
490
+
351
491
  When a seeder fails, the summary names the failing step and prints the whole error (`Bun.inspect` on Bun or `util.inspect` on Node.js: message, stack, `cause` and extra fields). Under GitHub Actions it also prints an `::error` annotation. Terminal colors respect `NO_COLOR`, `FORCE_COLOR`, and stdout TTY state.
352
492
 
353
493
  ## License
package/src/cli.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { parseArgs } from 'node:util'
2
2
  import { resolveDependencyOrder } from './dependency-resolver.js'
3
- import { colorize, inspectValue } from './formatting.js'
3
+ import { colorize, formatError } from './formatting.js'
4
4
  import { describeTarget } from './run-seeders.js'
5
5
  import type { RunSeedersOptions, SeederAny } from './types.js'
6
6
 
@@ -17,15 +17,6 @@ type CliRunner = (
17
17
  options?: RunSeedersOptions,
18
18
  ) => Promise<{ success: boolean }>
19
19
 
20
- /** Errors whose message says everything; others are printed with their stack */
21
- const USAGE_ERRORS = new Set([
22
- 'CircularDependencyError',
23
- 'MissingDependencyError',
24
- 'DuplicateSeederError',
25
- 'UnknownSeederError',
26
- 'SeedTargetError',
27
- ])
28
-
29
20
  function formatSeedersList(seeders: readonly SeederAny[]): string {
30
21
  if (seeders.length === 0) return 'No seeders registered.'
31
22
  const maxLen = Math.max(...seeders.map((s) => s.name.length))
@@ -45,7 +36,8 @@ ${colorize('Arguments:', 'white', 'bold')}
45
36
  ${colorize('Options:', 'white', 'bold')}
46
37
  --only a,b Same as naming the seeders
47
38
  --fresh Ignore and overwrite cached steps of the named seeders
48
- (of every seeder when none are named)
39
+ (of every seeder when none are named), after the
40
+ instance's onFresh hook, if any, resets the target
49
41
  --concurrency, -c <n> Run up to <n> independent seeders in parallel (default: 1)
50
42
  --continue-on-failure Keep running seeders that do not depend on a failed one
51
43
  --allow-remote Seed a database that is not local
@@ -225,8 +217,7 @@ export async function runCli(
225
217
  })
226
218
  return success ? 0 : 1
227
219
  } catch (error) {
228
- const usage = error instanceof Error && USAGE_ERRORS.has(error.name)
229
- console.error(colorize(usage ? (error as Error).message : inspectValue(error), 'red'))
220
+ console.error(colorize(formatError(error), 'red'))
230
221
  return 1
231
222
  }
232
223
  }
@@ -4,9 +4,9 @@ import { type RunSeedersCliOptions, runCli } from './cli.js'
4
4
  import { createDefineSeeder } from './define-seeder.js'
5
5
  import { type AnyExpectFn, type ExpectFn, getDefaultExpect } from './expect.js'
6
6
  import { getDefaultFaker, lazyFaker } from './lazy-faker.js'
7
- import { runSeedersCore } from './run-seeders.js'
7
+ import { type FreshRun, runSeedersCore, type SetupHelpers } from './run-seeders.js'
8
8
  import { isSeedingActive } from './seeding-state.js'
9
- import { createStepRunner, type SeederCache } from './step.js'
9
+ import { createStepRunner, type SeederCache, type StepRunner } from './step.js'
10
10
  import type {
11
11
  BaseSeederContext,
12
12
  MaybePromise,
@@ -44,20 +44,51 @@ export type ResolvedContext<
44
44
  export type SeederInstanceConfig<
45
45
  TExtra extends object = Record<never, never>,
46
46
  TExpect extends AnyExpectFn | undefined = ExpectFn,
47
+ TResources = undefined,
47
48
  > = {
49
+ /**
50
+ * Optional: acquire what the run needs (a database connection, an authenticated client)
51
+ * and return it. Runs once per run, after the target guard, before the cache and the
52
+ * context factory, which both receive the returned resources. Throw to refuse the run.
53
+ *
54
+ * Register the cleanup for each resource with `defer` right after acquiring it when
55
+ * `setup` acquires several: if `setup` throws later, the deferred cleanups still run
56
+ * (last registered first), while `teardown` does not, as there are no resources to pass it.
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * setup: async () => {
61
+ * const db = await connect(process.env.DATABASE_URL)
62
+ * return { db }
63
+ * },
64
+ * teardown: ({ db }) => db.close(),
65
+ * ```
66
+ */
67
+ setup?: ((helpers: SetupHelpers) => MaybePromise<TResources>) | undefined
68
+
69
+ /**
70
+ * Optional: release what `setup` returned. Runs once whenever `setup` returned: after
71
+ * the seeders (also when one fails), when the cache or context factory throws, and on
72
+ * SIGINT or SIGTERM before the process exits. Deferred cleanups run after it.
73
+ */
74
+ teardown?: ((resources: NoInfer<TResources>) => MaybePromise<void>) | undefined
75
+
48
76
  /**
49
77
  * Optional factory function that extends the base context (`faker`, `step`, `expect`).
50
78
  * Returned properties are merged onto `base` automatically — no need to spread `...base`,
51
79
  * though spreading or overriding keys (such as `faker`) also works.
52
- * Called once per run, after `onBeforeAll`.
80
+ * Called once per run, after `setup`, with the resources it returned.
53
81
  *
54
82
  * @example
55
83
  * ```typescript
56
- * context: () => ({ prisma })
84
+ * context: (base, { db }) => ({ db })
57
85
  * ```
58
86
  */
59
87
  context?:
60
- | ((base: NoInfer<BaseSeederContext<ResolvedExpect<TExpect>>>) => MaybePromise<TExtra>)
88
+ | ((
89
+ base: NoInfer<BaseSeederContext<ResolvedExpect<TExpect>>>,
90
+ resources: NoInfer<TResources>,
91
+ ) => MaybePromise<TExtra>)
61
92
  | undefined
62
93
 
63
94
  /**
@@ -69,7 +100,10 @@ export type SeederInstanceConfig<
69
100
 
70
101
  /**
71
102
  * Optional cache for step caching.
72
- * Provide `get` / `set` (and optionally `getAll` for single-query preloading).
103
+ * Provide `get` / `set` (and optionally `getAll` for single-query preloading), or a
104
+ * function that builds the cache from the resources `setup` returned. The function runs
105
+ * once per run, after `setup` and before the cache preload; return `undefined` to run
106
+ * without a cache.
73
107
  *
74
108
  * @example
75
109
  * ```typescript
@@ -80,9 +114,32 @@ export type SeederInstanceConfig<
80
114
  * await prisma.seedCache.upsert({ where: { key }, create: { key, output }, update: { output } })
81
115
  * },
82
116
  * }
117
+ * // or, from setup's resources:
118
+ * cache: ({ db }) => db.seedCache,
83
119
  * ```
84
120
  */
85
- cache?: SeederCache | undefined
121
+ cache?:
122
+ | SeederCache
123
+ | ((resources: NoInfer<TResources>) => MaybePromise<SeederCache | undefined>)
124
+ | undefined
125
+
126
+ /**
127
+ * Optional: reset the target before a fresh run (CLI `--fresh`, or the `fresh` option),
128
+ * for example wipe a local emulator, so steps that create records with ids the target
129
+ * chooses do not create them a second time. Runs after `setup` and the cache factory,
130
+ * before the cache preload and the context factory, and only when at least one seeder of
131
+ * the run is fresh. `all` is true only when every registered seeder runs fresh: with
132
+ * `--fresh` plus seeder names, the seeders they depend on still replay their cache, so
133
+ * wipe only when `all` is true (or throw to refuse a partial fresh run).
134
+ *
135
+ * @example
136
+ * ```typescript
137
+ * onFresh: async ({ resources: { db }, all }) => {
138
+ * if (all) await db.wipe()
139
+ * }
140
+ * ```
141
+ */
142
+ onFresh?: ((run: FreshRun<NoInfer<TResources>>) => MaybePromise<void>) | undefined
86
143
 
87
144
  /**
88
145
  * Optional: default maximum number of independent seeders to run concurrently (default: 1).
@@ -113,8 +170,25 @@ export type SeederInstanceConfig<
113
170
  fakerSeed?: number | undefined
114
171
 
115
172
  /**
116
- * Called before all seeders run, before the context factory.
117
- * Use for setup like connecting to databases, or to refuse a run.
173
+ * Optional, with `fakerSeed`: how finely faker is seeded (default: `'seeder'`).
174
+ *
175
+ * - `'seeder'`: one faker per seeder, seeded from `fakerSeed` and the seeder's name. A
176
+ * cached step skips its function, and with it the faker draws in it, so everything the
177
+ * seeder draws after that step shifts between a cached and an uncached run.
178
+ * - `'step'`: each step's function also gets its own faker, seeded from `fakerSeed`, the
179
+ * seeder's name and the step's `key` (or description), plus a counter when a key repeats.
180
+ * Draws inside a step and draws after it are the same whether earlier steps ran or came
181
+ * from the cache, and parallel steps no longer share one sequence.
182
+ *
183
+ * Switching to `'step'` changes the data steps generate once, which is why it is not the default.
184
+ */
185
+ fakerSeedScope?: 'seeder' | 'step' | undefined
186
+
187
+ /**
188
+ * Called before all seeders run, before `setup` and the context factory.
189
+ *
190
+ * @deprecated Use `setup`: throw from it to refuse a run, and return what it connects
191
+ * so `teardown`, `context` and a `cache` factory receive it. Still called, before `setup`.
118
192
  *
119
193
  * @example
120
194
  * ```typescript
@@ -128,7 +202,9 @@ export type SeederInstanceConfig<
128
202
  /**
129
203
  * Called after all seeders complete (success or failure), also when the context
130
204
  * factory throws. Receives the created context (or `undefined` if the context factory threw).
131
- * Use for cleanup like disconnecting from databases.
205
+ *
206
+ * @deprecated Use `teardown`, which receives the resources `setup` returned even when
207
+ * no context exists. Still called, before `teardown`.
132
208
  *
133
209
  * @example
134
210
  * ```typescript
@@ -268,8 +344,9 @@ type FakerSlot = {
268
344
  export function createSeederInstance<
269
345
  TExtra extends object = Record<never, never>,
270
346
  TExpect extends AnyExpectFn | undefined = ExpectFn,
347
+ TResources = undefined,
271
348
  >(
272
- config?: SeederInstanceConfig<TExtra, TExpect>,
349
+ config?: SeederInstanceConfig<TExtra, TExpect, TResources>,
273
350
  ): SeederInstance<ResolvedContext<TExtra, TExpect>> {
274
351
  type TContext = ResolvedContext<TExtra, TExpect>
275
352
 
@@ -278,6 +355,7 @@ export function createSeederInstance<
278
355
  const resolveBaseFaker = (): Faker => customFaker ?? getDefaultFaker()
279
356
  const customExpect = config?.expect
280
357
  const fakerSeed = config?.fakerSeed
358
+ const seedPerStep = fakerSeed !== undefined && config?.fakerSeedScope === 'step'
281
359
  const defaultConcurrency = config?.concurrency
282
360
 
283
361
  const runInternal = async (
@@ -285,11 +363,13 @@ export function createSeederInstance<
285
363
  options?: RunSeedersOptions,
286
364
  bannerName?: string,
287
365
  ) => {
288
- // One step runner and faker storage per run, so cache keys, duplicate checks, and scopes are isolated
289
- const stepRunner = createStepRunner({
290
- cache: config?.cache,
291
- log: options?.verbose ?? true,
292
- })
366
+ // One step runner and faker storage per run, so cache keys, duplicate checks, and scopes are
367
+ // isolated. The runner is built after setup, since the cache may come from its resources.
368
+ let stepRunner: StepRunner | undefined
369
+ const requireStepRunner = (): StepRunner => {
370
+ if (!stepRunner) throw new Error('plantr: the step runner is used before setup finished')
371
+ return stepRunner
372
+ }
293
373
  const fakerStorage = new AsyncLocalStorage<FakerSlot>()
294
374
  const resolveActiveFaker = (): Faker => {
295
375
  const slot = fakerStorage.getStore()
@@ -342,21 +422,36 @@ export function createSeederInstance<
342
422
  return runSeedersCore(
343
423
  seeders,
344
424
  {
345
- context: async () => {
425
+ prepare: async (resources) => {
426
+ const cache =
427
+ typeof config?.cache === 'function' ? await config.cache(resources) : config?.cache
428
+ stepRunner = createStepRunner({
429
+ cache,
430
+ log: options?.verbose ?? true,
431
+ aroundStep: seedPerStep
432
+ ? ({ seederName, key, occurrence }, run) => {
433
+ const name = `${seederName}:${key}${occurrence > 0 ? `#${occurrence}` : ''}`
434
+ return fakerStorage.run({ name, isolated: true }, run)
435
+ }
436
+ : undefined,
437
+ })
438
+ },
439
+ preloadCache: () => stepRunner?.preload(),
440
+ flushCache: () => stepRunner?.flush(),
441
+ context: async (resources) => {
346
442
  const base: BaseSeederContext<ResolvedExpect<TExpect>> = {
347
443
  faker: scopedFaker,
348
- step: stepRunner.step,
444
+ step: requireStepRunner().step,
349
445
  expect: (customExpect ?? getDefaultExpect()) as ResolvedExpect<TExpect>,
350
446
  }
351
447
  if (!config?.context) return base as unknown as TContext
352
- const extra = await config.context(base)
448
+ const extra = await config.context(base, resources)
353
449
  return extra === base
354
450
  ? (base as unknown as TContext)
355
451
  : ({ ...base, ...extra } as unknown as TContext)
356
452
  },
357
- preloadCache: config?.cache?.getAll ? () => stepRunner.preload() : undefined,
358
- flushCache: config?.cache?.setMany ? () => stepRunner.flush() : undefined,
359
453
  createSeederScope: ({ name, fresh, concurrent }) => {
454
+ const stepRunner = requireStepRunner()
360
455
  const stepScope = stepRunner.createScope({
361
456
  seederName: name,
362
457
  fresh,
@@ -375,6 +470,9 @@ export function createSeederInstance<
375
470
  },
376
471
  bannerName,
377
472
  target: config?.target,
473
+ setup: config?.setup,
474
+ onFresh: config?.onFresh,
475
+ teardown: config?.teardown,
378
476
  onBeforeAll: config?.onBeforeAll,
379
477
  onAfterAll: config?.onAfterAll,
380
478
  },
@@ -1,9 +1,10 @@
1
+ import { SeedUsageError } from './errors.js'
1
2
  import type { SeederAny } from './types.js'
2
3
 
3
4
  /**
4
5
  * Error thrown when circular dependencies are detected in seeders
5
6
  */
6
- export class CircularDependencyError extends Error {
7
+ export class CircularDependencyError extends SeedUsageError {
7
8
  constructor(cycle: string[]) {
8
9
  super(`Circular dependency detected in seeders: ${cycle.join(' -> ')} -> ${cycle[0] ?? ''}`)
9
10
  this.name = 'CircularDependencyError'
@@ -13,7 +14,7 @@ export class CircularDependencyError extends Error {
13
14
  /**
14
15
  * Error thrown when a seeder depends on a non-existent seeder
15
16
  */
16
- export class MissingDependencyError extends Error {
17
+ export class MissingDependencyError extends SeedUsageError {
17
18
  constructor(seeder: string, missingDep: string) {
18
19
  super(`Seeder "${seeder}" depends on "${missingDep}" which does not exist`)
19
20
  this.name = 'MissingDependencyError'
@@ -23,7 +24,7 @@ export class MissingDependencyError extends Error {
23
24
  /**
24
25
  * Error thrown when two seeders share a name
25
26
  */
26
- export class DuplicateSeederError extends Error {
27
+ export class DuplicateSeederError extends SeedUsageError {
27
28
  constructor(name: string) {
28
29
  super(`Two seeders are named "${name}"; seeder names must be unique`)
29
30
  this.name = 'DuplicateSeederError'
@@ -33,7 +34,7 @@ export class DuplicateSeederError extends Error {
33
34
  /**
34
35
  * Error thrown when a seeder is selected by a name that is not registered
35
36
  */
36
- export class UnknownSeederError extends Error {
37
+ export class UnknownSeederError extends SeedUsageError {
37
38
  constructor(name: string, known: readonly string[]) {
38
39
  super(`Unknown seeder "${name}". Registered seeders: ${known.join(', ') || '(none)'}`)
39
40
  this.name = 'UnknownSeederError'
package/src/errors.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Marks an error as a usage or configuration problem. Set it to `true` on any error (or
3
+ * throw `SeedUsageError`) and `runSeedersCli` prints only the message and exits 1, and a
4
+ * seeder failing with it is reported without a stack trace. A registered symbol, so it also
5
+ * works across copies of plantr and on errors from your own classes.
6
+ */
7
+ export const usageErrorSymbol: unique symbol = Symbol.for('plantr.usageError')
8
+
9
+ /**
10
+ * A usage or configuration error: a refused target, a missing environment variable, a bad
11
+ * argument. The message should say what to do; the CLI prints only it, without a stack trace.
12
+ */
13
+ export class SeedUsageError extends Error {
14
+ readonly [usageErrorSymbol] = true
15
+
16
+ constructor(message: string, options?: ErrorOptions) {
17
+ super(message, options)
18
+ this.name = 'SeedUsageError'
19
+ }
20
+ }
21
+
22
+ /** Whether `error` is marked as a usage error (`SeedUsageError`, or `usageErrorSymbol` set to true) */
23
+ export function isSeedUsageError(error: unknown): error is Error {
24
+ return (
25
+ typeof error === 'object' &&
26
+ error !== null &&
27
+ (error as { [usageErrorSymbol]?: unknown })[usageErrorSymbol] === true
28
+ )
29
+ }