plantr 2.1.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/dist/index.d.ts +13 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +694 -232
- package/dist/src/cli.d.ts.map +1 -1
- package/dist/src/create-seeder-instance.d.ts +87 -12
- package/dist/src/create-seeder-instance.d.ts.map +1 -1
- package/dist/src/dependency-resolver.d.ts +5 -4
- package/dist/src/dependency-resolver.d.ts.map +1 -1
- package/dist/src/errors.d.ts +18 -0
- package/dist/src/errors.d.ts.map +1 -0
- package/dist/src/expect.d.ts +41 -0
- package/dist/src/expect.d.ts.map +1 -0
- package/dist/src/formatting.d.ts +25 -1
- package/dist/src/formatting.d.ts.map +1 -1
- package/dist/src/map-with-limit.d.ts +19 -0
- package/dist/src/map-with-limit.d.ts.map +1 -0
- package/dist/src/run-seeders.d.ts +46 -12
- package/dist/src/run-seeders.d.ts.map +1 -1
- package/dist/src/signals.d.ts +9 -0
- package/dist/src/signals.d.ts.map +1 -0
- package/dist/src/step.d.ts +15 -0
- package/dist/src/step.d.ts.map +1 -1
- package/dist/src/types.d.ts +11 -4
- package/dist/src/types.d.ts.map +1 -1
- package/index.ts +20 -6
- package/package.json +4 -2
- package/readme.md +178 -29
- package/src/cli.ts +4 -13
- package/src/create-seeder-instance.ts +156 -32
- package/src/dependency-resolver.ts +5 -4
- package/src/errors.ts +29 -0
- package/src/expect.ts +502 -0
- package/src/formatting.ts +53 -2
- package/src/map-with-limit.ts +48 -0
- package/src/run-seeders.ts +320 -212
- package/src/signals.ts +54 -0
- package/src/step.ts +30 -4
- package/src/types.ts +11 -4
package/index.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* plantr - Generic seeder library with built-in faker, step, and expect
|
|
3
3
|
*
|
|
4
|
-
* A
|
|
5
|
-
* The library provides a base context with faker,
|
|
6
|
-
* extend this with their own context (e.g. prisma, custom helpers).
|
|
4
|
+
* A TypeScript library for Bun and Node.js (>= 22) for creating type-safe database
|
|
5
|
+
* seeders with dependency resolution. The library provides a base context with faker,
|
|
6
|
+
* step, and expect. Consumers extend this with their own context (e.g. prisma, custom helpers).
|
|
7
7
|
*
|
|
8
|
-
*
|
|
8
|
+
* On Bun, `expect` defaults to `bun:test`. On Node.js, `expect` uses a zero-dependency
|
|
9
|
+
* `node:assert/strict` fallback, or you can pass a custom `expect` (e.g. Vitest's) to
|
|
10
|
+
* `createSeederInstance({ expect })`.
|
|
9
11
|
*
|
|
10
12
|
* @example
|
|
11
13
|
* ```typescript
|
|
@@ -34,14 +36,14 @@
|
|
|
34
36
|
* ```
|
|
35
37
|
*/
|
|
36
38
|
|
|
37
|
-
// Re-export lazy-loaded English faker (0ms until first access) and expect
|
|
38
|
-
export { expect } from 'bun:test'
|
|
39
|
+
// Re-export lazy-loaded English faker (0ms until first access) and runtime-safe expect
|
|
39
40
|
export type { Faker } from '@faker-js/faker'
|
|
40
41
|
// CLI types
|
|
41
42
|
export type { RunSeedersCliOptions } from './src/cli.js'
|
|
42
43
|
// Main API
|
|
43
44
|
export type {
|
|
44
45
|
ResolvedContext,
|
|
46
|
+
ResolvedExpect,
|
|
45
47
|
SeederInstance,
|
|
46
48
|
SeederInstanceConfig,
|
|
47
49
|
} from './src/create-seeder-instance.js'
|
|
@@ -55,12 +57,23 @@ export {
|
|
|
55
57
|
resolveDependencyOrder,
|
|
56
58
|
UnknownSeederError,
|
|
57
59
|
} from './src/dependency-resolver.js'
|
|
60
|
+
export { isSeedUsageError, SeedUsageError, usageErrorSymbol } from './src/errors.js'
|
|
61
|
+
export type {
|
|
62
|
+
AnyExpectFn,
|
|
63
|
+
ErrorConstructor,
|
|
64
|
+
ExpectFn,
|
|
65
|
+
ExpectMatchers,
|
|
66
|
+
} from './src/expect.js'
|
|
67
|
+
export { expect } from './src/expect.js'
|
|
58
68
|
export type { ColorName, StyleName } from './src/formatting.js'
|
|
59
69
|
export { colorize, formatDuration } from './src/formatting.js'
|
|
60
70
|
export { lazyFaker as faker } from './src/lazy-faker.js'
|
|
71
|
+
export { mapWithLimit } from './src/map-with-limit.js'
|
|
61
72
|
export type {
|
|
73
|
+
FreshRun,
|
|
62
74
|
InternalSeederConfig,
|
|
63
75
|
SeederScopeHandle,
|
|
76
|
+
SetupHelpers,
|
|
64
77
|
TargetDescription,
|
|
65
78
|
} from './src/run-seeders.js'
|
|
66
79
|
export { describeTarget, runSeedersCore, SeedTargetError } from './src/run-seeders.js'
|
|
@@ -75,6 +88,7 @@ export type {
|
|
|
75
88
|
CacheWrite,
|
|
76
89
|
SeederCache,
|
|
77
90
|
StepFn,
|
|
91
|
+
StepIdentity,
|
|
78
92
|
StepOptions,
|
|
79
93
|
StepRecord,
|
|
80
94
|
StepRunner,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "plantr",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"description": "A generic seeder library with built-in faker, step, and expect support for type-safe database seeding",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
"author": "Kristoffer Hansen",
|
|
16
16
|
"keywords": [
|
|
17
17
|
"bun",
|
|
18
|
+
"node",
|
|
18
19
|
"seeder",
|
|
19
20
|
"database",
|
|
20
21
|
"faker",
|
|
@@ -25,7 +26,8 @@
|
|
|
25
26
|
"dependency-injection"
|
|
26
27
|
],
|
|
27
28
|
"engines": {
|
|
28
|
-
"bun": ">=1.0.0"
|
|
29
|
+
"bun": ">=1.0.0",
|
|
30
|
+
"node": ">=22.0.0"
|
|
29
31
|
},
|
|
30
32
|
"files": [
|
|
31
33
|
"index.ts",
|
package/readme.md
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
# plantr
|
|
2
2
|
|
|
3
|
-
A
|
|
3
|
+
A TypeScript database seeder library for **Bun and Node.js (>= 22)** with built-in faker, step workflow, parallel DAG execution, and end-to-end TypeScript inference.
|
|
4
4
|
|
|
5
5
|
## Features
|
|
6
6
|
|
|
7
|
-
- **
|
|
7
|
+
- **Bun & Node.js (>= 22)** - Runs natively on both Bun and Node.js (`node`, `tsx`, `ts-node`, `vitest`) with zero extra dependencies
|
|
8
|
+
- **Built-in utilities** - `faker`, `step`, and `expect` available in every seeder (`faker` is lazy-loaded on first access, English locale only by default; `expect` uses `bun:test` on Bun, a built-in `node:assert/strict` implementation on Node.js, or your own `expect` such as Vitest's)
|
|
8
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`
|
|
9
10
|
- **Automatic ordering & parallel DAG execution** - Runs in dependency order with critical-path scheduling across independent branches via `concurrency` / `--concurrency`
|
|
10
11
|
- **Run a subset** - Run named seeders plus what they depend on (`--only`, `only`)
|
|
11
|
-
- **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
|
|
12
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
|
|
13
|
-
- **Target guard** - Refuse to seed a database that is not local unless asked to
|
|
14
|
-
- **
|
|
14
|
+
- **Target guard** - Refuse to seed a database or emulator target that is not local unless asked to
|
|
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
|
|
15
16
|
- **Continue on failure** - Keep seeding independent data when one seeder fails
|
|
16
17
|
- **Dry run & list modes** - Preview execution order, target, and descriptions without running
|
|
17
18
|
|
|
@@ -19,9 +20,11 @@ A Bun-first database seeder library with built-in faker, step workflow, parallel
|
|
|
19
20
|
|
|
20
21
|
```bash
|
|
21
22
|
bun add plantr
|
|
23
|
+
# or with pnpm / npm on Node.js >= 22
|
|
24
|
+
pnpm add plantr
|
|
22
25
|
```
|
|
23
26
|
|
|
24
|
-
> **
|
|
27
|
+
> **Runtime support:** Works on **Bun >= 1.0** and **Node.js >= 22**. On Bun, `expect` delegates to `bun:test`. On Node.js, `expect` uses a zero-dependency fallback backed by `node:assert/strict` (covering `toBe`, `toEqual`, `toStrictEqual`, `toBeDefined`, `toBeUndefined`, `toBeNull`, `toBeTruthy`, `toBeFalsy`, `toContain`, `toHaveLength`, `toMatch`, `toBeGreaterThan`, `toBeGreaterThanOrEqual`, `toBeLessThan`, `toBeLessThanOrEqual`, `toThrow`, and `.not.*`), or pass your own `expect` (for example Vitest's `expect`) via `createSeederInstance({ expect })`.
|
|
25
28
|
|
|
26
29
|
## Quick Start
|
|
27
30
|
|
|
@@ -30,18 +33,19 @@ bun add plantr
|
|
|
30
33
|
```typescript
|
|
31
34
|
// src/seed.ts
|
|
32
35
|
import { createSeederInstance } from 'plantr'
|
|
33
|
-
import {
|
|
36
|
+
import { PrismaClient } from '@prisma/client'
|
|
34
37
|
|
|
35
38
|
export const { defineSeeder, runSeeders, runSeedersCli } = createSeederInstance({
|
|
36
|
-
// Optional: extra properties are merged onto { faker, step, expect } automatically
|
|
37
|
-
context: () => ({ prisma }),
|
|
38
39
|
target: () => process.env.DATABASE_URL,
|
|
39
|
-
|
|
40
|
+
// Optional: acquire what the run needs; teardown always gets it back
|
|
41
|
+
setup: async () => {
|
|
42
|
+
const prisma = new PrismaClient()
|
|
40
43
|
await prisma.$connect()
|
|
44
|
+
return { prisma }
|
|
41
45
|
},
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
},
|
|
46
|
+
teardown: ({ prisma }) => prisma.$disconnect(),
|
|
47
|
+
// Optional: extra properties are merged onto { faker, step, expect } automatically
|
|
48
|
+
context: (_base, { prisma }) => ({ prisma }),
|
|
45
49
|
})
|
|
46
50
|
```
|
|
47
51
|
|
|
@@ -118,6 +122,8 @@ if (import.meta.main) {
|
|
|
118
122
|
Run with:
|
|
119
123
|
```bash
|
|
120
124
|
bun run src/seed.ts
|
|
125
|
+
# or on Node.js:
|
|
126
|
+
npx tsx src/seed.ts
|
|
121
127
|
```
|
|
122
128
|
|
|
123
129
|
Or programmatically (e.g. in tests) with fully typed `outputs`:
|
|
@@ -136,7 +142,7 @@ bun run src/seed.ts # Run every seeder
|
|
|
136
142
|
bun run src/seed.ts postSeeder # Run postSeeder and the seeders it depends on
|
|
137
143
|
bun run src/seed.ts --only a,b # Same as naming them
|
|
138
144
|
bun run src/seed.ts postSeeder --fresh # Ignore and overwrite postSeeder's cached steps
|
|
139
|
-
bun run src/seed.ts --fresh #
|
|
145
|
+
bun run src/seed.ts --fresh # Run onFresh (see Fresh runs), then ignore and overwrite every cached step
|
|
140
146
|
bun run src/seed.ts --concurrency 4 # Run up to 4 independent seeders in parallel (-c 4)
|
|
141
147
|
bun run src/seed.ts --continue-on-failure # Keep running seeders that do not depend on a failed one
|
|
142
148
|
bun run src/seed.ts --allow-remote # Seed a target that is not local (see Target guard)
|
|
@@ -154,12 +160,19 @@ An unknown flag, invalid `--concurrency`, or unknown seeder name prints the prob
|
|
|
154
160
|
|
|
155
161
|
```typescript
|
|
156
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
|
+
|
|
157
169
|
// Optional: factory returning extra properties to merge onto { faker, step, expect }.
|
|
158
|
-
// Receives `base` if you want to build helpers around faker/step/expect or override a base key
|
|
159
|
-
// Called once per run, after
|
|
160
|
-
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 }),
|
|
161
173
|
|
|
162
|
-
// 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)
|
|
163
176
|
cache: {
|
|
164
177
|
get: async (key) => { /* return the stored value, or undefined / null */ },
|
|
165
178
|
set: async (key, value) => { /* store value, overwriting */ },
|
|
@@ -167,22 +180,32 @@ createSeederInstance({
|
|
|
167
180
|
setMany: async (entries) => { /* optional: flush all writes in one batch at end of run */ },
|
|
168
181
|
},
|
|
169
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
|
+
|
|
170
186
|
// Optional: default parallel concurrency for independent seeders (default: 1; e.g. 4 or Infinity)
|
|
171
187
|
concurrency: 4,
|
|
172
188
|
|
|
173
189
|
// Optional: custom Faker locale instance (default: lazy-loaded @faker-js/faker/locale/en)
|
|
174
190
|
faker: fakerDE,
|
|
175
191
|
|
|
176
|
-
// Optional:
|
|
192
|
+
// Optional: custom `expect` implementation (e.g. Vitest's `expect`).
|
|
193
|
+
// Defaults to `bun:test` on Bun and a built-in `node:assert/strict` fallback on Node.js.
|
|
194
|
+
expect: vitestExpect,
|
|
195
|
+
|
|
196
|
+
// Optional: the database or emulator URL the run writes to (see Target guard)
|
|
177
197
|
target: () => process.env.DATABASE_URL,
|
|
178
198
|
|
|
179
199
|
// Optional: seed faker per seeder (fakerSeed + hash of the seeder name),
|
|
180
200
|
// so every run generates the same data even when running concurrently
|
|
181
201
|
fakerSeed: 1,
|
|
182
202
|
|
|
183
|
-
// Optional:
|
|
184
|
-
|
|
185
|
-
|
|
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 */ },
|
|
186
209
|
})
|
|
187
210
|
```
|
|
188
211
|
|
|
@@ -214,6 +237,7 @@ const run = await runSeeders(seeders, {
|
|
|
214
237
|
fresh: ['postSeeder'], // Ignore cached steps: true for all, or checked seeder names
|
|
215
238
|
allowRemote: false, // Seed a non-local target (default: false)
|
|
216
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)
|
|
217
241
|
})
|
|
218
242
|
```
|
|
219
243
|
|
|
@@ -230,6 +254,60 @@ When `concurrency > 1` (configured on `createSeederInstance`, per `runSeeders` c
|
|
|
230
254
|
|
|
231
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`.
|
|
232
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
|
+
|
|
233
311
|
### Step Function
|
|
234
312
|
|
|
235
313
|
```typescript
|
|
@@ -253,6 +331,22 @@ run: async ({ step }) => {
|
|
|
253
331
|
}
|
|
254
332
|
```
|
|
255
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
|
+
|
|
256
350
|
## Step Caching
|
|
257
351
|
|
|
258
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.
|
|
@@ -262,12 +356,13 @@ A cached step stores its output under the key `<seederName>:<key or slugified de
|
|
|
262
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.
|
|
263
357
|
- **Every step must be safe to run again**: a version change, `fresh`, or a cleared cache reruns it against existing data.
|
|
264
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.
|
|
265
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).
|
|
266
361
|
|
|
267
|
-
A Prisma store
|
|
362
|
+
A Prisma store, with the client from `setup`:
|
|
268
363
|
|
|
269
364
|
```typescript
|
|
270
|
-
cache: {
|
|
365
|
+
cache: ({ prisma }) => ({
|
|
271
366
|
get: async (key) => {
|
|
272
367
|
const row = await prisma.seedCache.findUnique({ where: { key } })
|
|
273
368
|
return row?.output
|
|
@@ -288,18 +383,57 @@ cache: {
|
|
|
288
383
|
}),
|
|
289
384
|
)
|
|
290
385
|
},
|
|
291
|
-
}
|
|
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
|
+
})
|
|
292
403
|
```
|
|
293
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
|
+
|
|
294
428
|
## Target guard
|
|
295
429
|
|
|
296
|
-
Set `target` to the database URL the instance writes to. The banner then shows its host and
|
|
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.
|
|
297
431
|
|
|
298
|
-
Without `target` there is no check. For other rules (an environment variable, a list of allowed hosts), throw from `
|
|
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.
|
|
299
433
|
|
|
300
434
|
## Seeding State
|
|
301
435
|
|
|
302
|
-
Check if seeding is active to skip side effects. Runtime code (job queues, mailers, the API) should import it from `plantr/state`, which does not load faker
|
|
436
|
+
Check if seeding is active to skip side effects. Runtime code (job queues, mailers, the API) should import it from `plantr/state`, which does not load faker, `bun:test`, or assertion helpers:
|
|
303
437
|
|
|
304
438
|
```typescript
|
|
305
439
|
import { isSeedingActive } from 'plantr/state'
|
|
@@ -319,8 +453,10 @@ The flag is set after validation succeeds and cleared when the run finishes, als
|
|
|
319
453
|
import {
|
|
320
454
|
CircularDependencyError,
|
|
321
455
|
DuplicateSeederError,
|
|
456
|
+
isSeedUsageError,
|
|
322
457
|
MissingDependencyError,
|
|
323
458
|
SeedTargetError,
|
|
459
|
+
SeedUsageError,
|
|
324
460
|
UnknownSeederError,
|
|
325
461
|
} from 'plantr'
|
|
326
462
|
|
|
@@ -339,7 +475,20 @@ try {
|
|
|
339
475
|
}
|
|
340
476
|
```
|
|
341
477
|
|
|
342
|
-
|
|
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
|
+
|
|
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.
|
|
343
492
|
|
|
344
493
|
## License
|
|
345
494
|
|
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 } 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
|
-
|
|
229
|
-
console.error(colorize(usage ? (error as Error).message : Bun.inspect(error), 'red'))
|
|
220
|
+
console.error(colorize(formatError(error), 'red'))
|
|
230
221
|
return 1
|
|
231
222
|
}
|
|
232
223
|
}
|