plantr 2.0.0 → 2.2.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 +31 -25
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1050 -251
- package/dist/src/cli.d.ts +13 -3
- package/dist/src/cli.d.ts.map +1 -0
- package/dist/src/create-seeder-instance.d.ts +64 -78
- package/dist/src/create-seeder-instance.d.ts.map +1 -0
- package/dist/src/define-seeder.d.ts +4 -3
- package/dist/src/define-seeder.d.ts.map +1 -0
- package/dist/src/dependency-resolver.d.ts +2 -1
- package/dist/src/dependency-resolver.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 +36 -14
- package/dist/src/formatting.d.ts.map +1 -0
- package/dist/src/lazy-faker.d.ts +12 -0
- package/dist/src/lazy-faker.d.ts.map +1 -0
- package/dist/src/run-seeders.d.ts +46 -26
- package/dist/src/run-seeders.d.ts.map +1 -0
- package/dist/src/seeding-state.d.ts +15 -4
- package/dist/src/seeding-state.d.ts.map +1 -0
- package/dist/src/step.d.ts +79 -22
- package/dist/src/step.d.ts.map +1 -0
- package/dist/src/types.d.ts +121 -38
- package/dist/src/types.d.ts.map +1 -0
- package/dist/state.d.ts +2 -1
- package/dist/state.d.ts.map +1 -0
- package/dist/state.js +10 -2
- package/index.ts +70 -28
- package/package.json +5 -2
- package/readme.md +102 -52
- package/src/cli.ts +155 -22
- package/src/create-seeder-instance.ts +252 -111
- package/src/define-seeder.ts +14 -7
- package/src/dependency-resolver.ts +17 -28
- package/src/expect.ts +502 -0
- package/src/formatting.ts +142 -37
- package/src/lazy-faker.ts +46 -0
- package/src/run-seeders.ts +352 -122
- package/src/seeding-state.ts +27 -5
- package/src/step.ts +208 -64
- package/src/types.ts +173 -41
- package/state.ts +1 -1
|
@@ -1,58 +1,101 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { runCli } from './cli'
|
|
4
|
-
import { createDefineSeeder } from './define-seeder'
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import type { Faker } from '@faker-js/faker'
|
|
3
|
+
import { type RunSeedersCliOptions, runCli } from './cli.js'
|
|
4
|
+
import { createDefineSeeder } from './define-seeder.js'
|
|
5
|
+
import { type AnyExpectFn, type ExpectFn, getDefaultExpect } from './expect.js'
|
|
6
|
+
import { getDefaultFaker, lazyFaker } from './lazy-faker.js'
|
|
7
|
+
import { runSeedersCore } from './run-seeders.js'
|
|
8
|
+
import { isSeedingActive } from './seeding-state.js'
|
|
9
|
+
import { createStepRunner, type SeederCache } from './step.js'
|
|
8
10
|
import type {
|
|
9
11
|
BaseSeederContext,
|
|
12
|
+
MaybePromise,
|
|
13
|
+
Prettify,
|
|
10
14
|
RunSeedersOptions,
|
|
15
|
+
RunSeedersResult,
|
|
11
16
|
Seeder,
|
|
12
|
-
SeederAny,
|
|
13
17
|
SeederConfig,
|
|
14
|
-
|
|
15
|
-
|
|
18
|
+
SeederName,
|
|
19
|
+
ValidateSeeders,
|
|
20
|
+
} from './types.js'
|
|
21
|
+
|
|
22
|
+
/** Resolve the effective `expect` type from an optional `config.expect` type parameter */
|
|
23
|
+
export type ResolvedExpect<TExpect> = [Exclude<TExpect, undefined>] extends [never]
|
|
24
|
+
? ExpectFn
|
|
25
|
+
: [AnyExpectFn] extends [Exclude<TExpect, undefined>]
|
|
26
|
+
? ExpectFn
|
|
27
|
+
: undefined extends TExpect
|
|
28
|
+
? Exclude<TExpect, undefined> | ExpectFn
|
|
29
|
+
: TExpect
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Full context type resolved from `BaseSeederContext` plus the extra properties
|
|
33
|
+
* returned by `config.context`. Any base key returned by `context` overrides the default.
|
|
34
|
+
*/
|
|
35
|
+
export type ResolvedContext<
|
|
36
|
+
TExtra extends object = Record<never, never>,
|
|
37
|
+
TExpect = ExpectFn,
|
|
38
|
+
> = Prettify<Omit<BaseSeederContext<ResolvedExpect<TExpect>>, keyof TExtra> & TExtra>
|
|
16
39
|
|
|
17
40
|
/**
|
|
18
41
|
* Configuration for creating a seeder instance.
|
|
19
|
-
*
|
|
42
|
+
* `context` is optional and its returned properties are automatically merged onto `BaseSeederContext`.
|
|
20
43
|
*/
|
|
21
|
-
export type SeederInstanceConfig<
|
|
44
|
+
export type SeederInstanceConfig<
|
|
45
|
+
TExtra extends object = Record<never, never>,
|
|
46
|
+
TExpect extends AnyExpectFn | undefined = ExpectFn,
|
|
47
|
+
> = {
|
|
22
48
|
/**
|
|
23
|
-
*
|
|
24
|
-
*
|
|
49
|
+
* Optional factory function that extends the base context (`faker`, `step`, `expect`).
|
|
50
|
+
* Returned properties are merged onto `base` automatically — no need to spread `...base`,
|
|
51
|
+
* though spreading or overriding keys (such as `faker`) also works.
|
|
52
|
+
* Called once per run, after `onBeforeAll`.
|
|
25
53
|
*
|
|
26
54
|
* @example
|
|
27
55
|
* ```typescript
|
|
28
|
-
* context: (
|
|
29
|
-
* ...base,
|
|
30
|
-
* prisma,
|
|
31
|
-
* myHelper: () => { ... }
|
|
32
|
-
* })
|
|
56
|
+
* context: () => ({ prisma })
|
|
33
57
|
* ```
|
|
34
58
|
*/
|
|
35
|
-
context
|
|
59
|
+
context?:
|
|
60
|
+
| ((base: NoInfer<BaseSeederContext<ResolvedExpect<TExpect>>>) => MaybePromise<TExtra>)
|
|
61
|
+
| undefined
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Optional: custom `expect` assertion function (for example Vitest's `expect`).
|
|
65
|
+
* Defaults to `bun:test`'s `expect` on Bun and a zero-dependency `node:assert/strict`
|
|
66
|
+
* implementation on Node.js.
|
|
67
|
+
*/
|
|
68
|
+
expect?: TExpect | undefined
|
|
36
69
|
|
|
37
70
|
/**
|
|
38
71
|
* Optional cache for step caching.
|
|
39
|
-
* Provide get/set
|
|
72
|
+
* Provide `get` / `set` (and optionally `getAll` for single-query preloading).
|
|
40
73
|
*
|
|
41
74
|
* @example
|
|
42
75
|
* ```typescript
|
|
43
76
|
* cache: {
|
|
44
|
-
* get: async (key) => {
|
|
45
|
-
* const cached = await prisma.seedCache.findUnique({ where: { key } })
|
|
46
|
-
* return cached?.output as T | undefined
|
|
47
|
-
* },
|
|
77
|
+
* get: async (key) => (await prisma.seedCache.findUnique({ where: { key } }))?.output,
|
|
48
78
|
* set: async (key, value) => {
|
|
49
79
|
* const output = value as Prisma.InputJsonValue
|
|
50
80
|
* await prisma.seedCache.upsert({ where: { key }, create: { key, output }, update: { output } })
|
|
51
|
-
* }
|
|
81
|
+
* },
|
|
52
82
|
* }
|
|
53
83
|
* ```
|
|
54
84
|
*/
|
|
55
|
-
cache?: SeederCache
|
|
85
|
+
cache?: SeederCache | undefined
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Optional: default maximum number of independent seeders to run concurrently (default: 1).
|
|
89
|
+
* Applies to both `runSeeders` and `runSeedersCli` unless overridden per run or via `--concurrency`.
|
|
90
|
+
* Set to a positive integer (e.g. `4`) or `Infinity` to run independent DAG branches in parallel.
|
|
91
|
+
*/
|
|
92
|
+
concurrency?: number | undefined
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Optional: custom `Faker` instance (e.g. a non-English locale like `fakerDE` or `fakerNB_NO`).
|
|
96
|
+
* Defaults to the lazy-loaded English locale (`@faker-js/faker/locale/en`).
|
|
97
|
+
*/
|
|
98
|
+
faker?: Faker | undefined
|
|
56
99
|
|
|
57
100
|
/**
|
|
58
101
|
* Optional: the database URL this instance writes to, e.g. `() => process.env.DATABASE_URL`.
|
|
@@ -60,14 +103,14 @@ export type SeederInstanceConfig<TContext extends BaseSeederContext> = {
|
|
|
60
103
|
* host that is not local unless it passes `allowRemote` (CLI: `--allow-remote`).
|
|
61
104
|
* Return undefined to skip the check.
|
|
62
105
|
*/
|
|
63
|
-
target?: () => string | undefined
|
|
106
|
+
target?: (() => string | undefined) | undefined
|
|
64
107
|
|
|
65
108
|
/**
|
|
66
109
|
* Optional: seed faker before each seeder with this number plus a hash of the
|
|
67
110
|
* seeder's name, so every run generates the same data and adding a seeder does
|
|
68
|
-
* not shift the others'.
|
|
111
|
+
* not shift the others'. Works safely with parallel `concurrency` via isolated Faker instances.
|
|
69
112
|
*/
|
|
70
|
-
fakerSeed?: number
|
|
113
|
+
fakerSeed?: number | undefined
|
|
71
114
|
|
|
72
115
|
/**
|
|
73
116
|
* Called before all seeders run, before the context factory.
|
|
@@ -80,11 +123,11 @@ export type SeederInstanceConfig<TContext extends BaseSeederContext> = {
|
|
|
80
123
|
* }
|
|
81
124
|
* ```
|
|
82
125
|
*/
|
|
83
|
-
onBeforeAll?: () => void |
|
|
126
|
+
onBeforeAll?: (() => MaybePromise<void>) | undefined
|
|
84
127
|
|
|
85
128
|
/**
|
|
86
129
|
* Called after all seeders complete (success or failure), also when the context
|
|
87
|
-
* factory throws.
|
|
130
|
+
* factory throws. Receives the created context (or `undefined` if the context factory threw).
|
|
88
131
|
* Use for cleanup like disconnecting from databases.
|
|
89
132
|
*
|
|
90
133
|
* @example
|
|
@@ -94,15 +137,18 @@ export type SeederInstanceConfig<TContext extends BaseSeederContext> = {
|
|
|
94
137
|
* }
|
|
95
138
|
* ```
|
|
96
139
|
*/
|
|
97
|
-
onAfterAll?:
|
|
140
|
+
onAfterAll?:
|
|
141
|
+
| ((ctx: NoInfer<ResolvedContext<TExtra, TExpect>> | undefined) => MaybePromise<void>)
|
|
142
|
+
| undefined
|
|
98
143
|
}
|
|
99
144
|
|
|
100
145
|
/**
|
|
101
146
|
* Result type for the seeder instance
|
|
102
147
|
*/
|
|
103
|
-
export type SeederInstance<TContext extends BaseSeederContext> = {
|
|
148
|
+
export type SeederInstance<TContext extends object = BaseSeederContext> = {
|
|
104
149
|
/**
|
|
105
|
-
* Define a new seeder with typed dependencies
|
|
150
|
+
* Define a new seeder with typed dependencies.
|
|
151
|
+
* `dependsOn` only accepts seeders whose context is compatible with this instance.
|
|
106
152
|
*
|
|
107
153
|
* @example
|
|
108
154
|
* ```typescript
|
|
@@ -120,31 +166,39 @@ export type SeederInstance<TContext extends BaseSeederContext> = {
|
|
|
120
166
|
defineSeeder: <
|
|
121
167
|
TName extends string,
|
|
122
168
|
TOutput,
|
|
123
|
-
const TDeps extends readonly
|
|
169
|
+
const TDeps extends readonly Seeder<TContext, string, unknown, string>[] = readonly [],
|
|
124
170
|
>(
|
|
125
171
|
config: SeederConfig<TContext, TName, TOutput, TDeps>,
|
|
126
|
-
) => Seeder<TContext, TName, TOutput
|
|
172
|
+
) => Seeder<TContext, TName, Awaited<TOutput>, SeederName<TDeps[number]>>
|
|
127
173
|
|
|
128
174
|
/**
|
|
129
175
|
* Run an array of seeders in dependency order.
|
|
130
176
|
* Automatically sets seeding state to active during execution.
|
|
131
177
|
*
|
|
178
|
+
* - Enforces context compatibility across seeders at compile time
|
|
179
|
+
* - Flags missing dependencies at compile time when passing known seeders
|
|
180
|
+
* - Autocompletes and checks `only` and `fresh` against the registered seeder names
|
|
181
|
+
* - Returns strongly typed `outputs` and discriminated-union `results`
|
|
182
|
+
*
|
|
132
183
|
* @param seeders - Array of seeders to run
|
|
133
184
|
* @param options - Optional runner options
|
|
134
|
-
* @returns Object containing results and
|
|
185
|
+
* @returns Object containing `success`, typed `results`, and typed `outputs`
|
|
135
186
|
* @throws Before anything runs, on an invalid registry (duplicate name, missing
|
|
136
|
-
* dependency, cycle), an unknown name in `only`/`fresh`, or a refused `target`
|
|
187
|
+
* dependency, cycle), an unknown name in `only`/`fresh`, invalid `concurrency`, or a refused `target`
|
|
137
188
|
*/
|
|
138
|
-
runSeeders:
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
189
|
+
runSeeders: <
|
|
190
|
+
const TSeeders extends readonly Seeder<TContext, string, unknown, string>[],
|
|
191
|
+
const TOptions extends RunSeedersOptions<SeederName<TSeeders[number]>> | undefined = undefined,
|
|
192
|
+
>(
|
|
193
|
+
seeders: TSeeders & ValidateSeeders<TSeeders>,
|
|
194
|
+
options?: TOptions,
|
|
195
|
+
) => Promise<RunSeedersResult<TSeeders, TOptions>>
|
|
142
196
|
|
|
143
197
|
/**
|
|
144
198
|
* Run seeders as a CLI command: parses the arguments, runs, and exits with 0 or 1.
|
|
145
199
|
* Seeder names (positional or `--only a,b`) select seeders plus their dependencies;
|
|
146
|
-
* `--fresh`, `--continue-on-failure`, `--allow-remote`, `--
|
|
147
|
-
* to the runner options. Unknown flags and names exit 1.
|
|
200
|
+
* `--fresh`, `--concurrency`, `--continue-on-failure`, `--allow-remote`, `--quiet`,
|
|
201
|
+
* `--dry-run`, `--list`, and `--help` map to the runner options. Unknown flags and names exit 1.
|
|
148
202
|
*
|
|
149
203
|
* @example
|
|
150
204
|
* ```typescript
|
|
@@ -154,13 +208,9 @@ export type SeederInstance<TContext extends BaseSeederContext> = {
|
|
|
154
208
|
* }
|
|
155
209
|
* ```
|
|
156
210
|
*/
|
|
157
|
-
runSeedersCli: (
|
|
158
|
-
seeders:
|
|
159
|
-
options?:
|
|
160
|
-
name?: string
|
|
161
|
-
/** Arguments to parse (default: `process.argv.slice(2)`) */
|
|
162
|
-
argv?: readonly string[]
|
|
163
|
-
},
|
|
211
|
+
runSeedersCli: <const TSeeders extends readonly Seeder<TContext, string, unknown, string>[]>(
|
|
212
|
+
seeders: TSeeders & ValidateSeeders<TSeeders>,
|
|
213
|
+
options?: RunSeedersCliOptions,
|
|
164
214
|
) => Promise<void>
|
|
165
215
|
|
|
166
216
|
/**
|
|
@@ -178,87 +228,178 @@ export type SeederInstance<TContext extends BaseSeederContext> = {
|
|
|
178
228
|
isSeedingActive: () => boolean
|
|
179
229
|
}
|
|
180
230
|
|
|
231
|
+
type FakerConstructor = new (options: { locale: Faker['rawDefinitions'] }) => Faker
|
|
232
|
+
|
|
233
|
+
/** Create an isolated Faker instance using the same locale definitions as `baseFaker` */
|
|
234
|
+
function cloneFaker(baseFaker: Faker): Faker {
|
|
235
|
+
const Ctor = baseFaker.constructor as FakerConstructor | undefined
|
|
236
|
+
if (typeof Ctor === 'function' && 'rawDefinitions' in baseFaker && baseFaker.rawDefinitions) {
|
|
237
|
+
return new Ctor({ locale: baseFaker.rawDefinitions })
|
|
238
|
+
}
|
|
239
|
+
return baseFaker
|
|
240
|
+
}
|
|
241
|
+
|
|
181
242
|
/**
|
|
182
|
-
* Create a seeder instance with
|
|
243
|
+
* Create a seeder instance with an optional custom context.
|
|
183
244
|
*
|
|
184
245
|
* This is the main entry point for the seeder library. The library provides
|
|
185
|
-
* a base context with faker
|
|
186
|
-
*
|
|
246
|
+
* a base context with `faker`, `step`, and `expect`. Consumers can extend it
|
|
247
|
+
* without needing explicit generics or manual `...base` spreads.
|
|
187
248
|
*
|
|
188
|
-
* The seeding state is automatically managed - set to active
|
|
189
|
-
*
|
|
249
|
+
* The seeding state is automatically managed - set to active after validation
|
|
250
|
+
* succeeds and cleared when the run completes.
|
|
190
251
|
*
|
|
191
252
|
* @example
|
|
192
253
|
* ```typescript
|
|
193
254
|
* import { createSeederInstance } from 'plantr'
|
|
194
255
|
*
|
|
195
|
-
*
|
|
196
|
-
*
|
|
197
|
-
* const { defineSeeder, runSeeders, isSeedingActive } = createSeederInstance<MyContext>({
|
|
198
|
-
* context: (base) => ({
|
|
199
|
-
* ...base,
|
|
200
|
-
* prisma,
|
|
201
|
-
* }),
|
|
256
|
+
* export const { defineSeeder, runSeeders, runSeedersCli } = createSeederInstance({
|
|
257
|
+
* context: () => ({ prisma }),
|
|
202
258
|
* target: () => process.env.DATABASE_URL,
|
|
203
259
|
* })
|
|
204
|
-
*
|
|
205
|
-
* export { defineSeeder, isSeedingActive }
|
|
206
|
-
*
|
|
207
|
-
* // In your message/queue system:
|
|
208
|
-
* if (isSeedingActive()) {
|
|
209
|
-
* console.log('Skipping side effect during seeding')
|
|
210
|
-
* return
|
|
211
|
-
* }
|
|
212
|
-
*
|
|
213
|
-
* // Later...
|
|
214
|
-
* await runSeeders([seeder1, seeder2])
|
|
215
260
|
* ```
|
|
216
261
|
*/
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
262
|
+
type FakerSlot = {
|
|
263
|
+
name: string
|
|
264
|
+
isolated: boolean
|
|
265
|
+
instance?: Faker
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export function createSeederInstance<
|
|
269
|
+
TExtra extends object = Record<never, never>,
|
|
270
|
+
TExpect extends AnyExpectFn | undefined = ExpectFn,
|
|
271
|
+
>(
|
|
272
|
+
config?: SeederInstanceConfig<TExtra, TExpect>,
|
|
273
|
+
): SeederInstance<ResolvedContext<TExtra, TExpect>> {
|
|
274
|
+
type TContext = ResolvedContext<TExtra, TExpect>
|
|
275
|
+
|
|
220
276
|
const defineSeeder = createDefineSeeder<TContext>()
|
|
277
|
+
const customFaker = config?.faker && config.faker !== lazyFaker ? config.faker : undefined
|
|
278
|
+
const resolveBaseFaker = (): Faker => customFaker ?? getDefaultFaker()
|
|
279
|
+
const customExpect = config?.expect
|
|
280
|
+
const fakerSeed = config?.fakerSeed
|
|
281
|
+
const defaultConcurrency = config?.concurrency
|
|
221
282
|
|
|
222
|
-
const
|
|
223
|
-
seeders: readonly
|
|
283
|
+
const runInternal = async (
|
|
284
|
+
seeders: readonly Seeder<TContext, string, unknown, string>[],
|
|
224
285
|
options?: RunSeedersOptions,
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
286
|
+
bannerName?: string,
|
|
287
|
+
) => {
|
|
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,
|
|
229
291
|
log: options?.verbose ?? true,
|
|
230
292
|
})
|
|
231
|
-
const
|
|
293
|
+
const fakerStorage = new AsyncLocalStorage<FakerSlot>()
|
|
294
|
+
const resolveActiveFaker = (): Faker => {
|
|
295
|
+
const slot = fakerStorage.getStore()
|
|
296
|
+
if (!slot) return resolveBaseFaker()
|
|
297
|
+
if (slot.instance) return slot.instance
|
|
298
|
+
const base = resolveBaseFaker()
|
|
299
|
+
if (!slot.isolated) {
|
|
300
|
+
slot.instance = base
|
|
301
|
+
return base
|
|
302
|
+
}
|
|
303
|
+
const cloned = cloneFaker(base)
|
|
304
|
+
if (fakerSeed !== undefined) {
|
|
305
|
+
cloned.seed(fakerSeed + hashName(slot.name))
|
|
306
|
+
}
|
|
307
|
+
slot.instance = cloned
|
|
308
|
+
return cloned
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// Lazy proxy: neither loads faker nor clones per-seeder Faker until a seeder accesses ctx.faker
|
|
312
|
+
const scopedFaker: Faker = new Proxy({} as Faker, {
|
|
313
|
+
get(_target, prop) {
|
|
314
|
+
const active = resolveActiveFaker()
|
|
315
|
+
const value = Reflect.get(active, prop, active)
|
|
316
|
+
return typeof value === 'function' && prop !== 'constructor' ? value.bind(active) : value
|
|
317
|
+
},
|
|
318
|
+
set(_target, prop, value) {
|
|
319
|
+
const active = resolveActiveFaker()
|
|
320
|
+
return Reflect.set(active, prop, value, active)
|
|
321
|
+
},
|
|
322
|
+
has(_target, prop) {
|
|
323
|
+
return Reflect.has(resolveActiveFaker(), prop)
|
|
324
|
+
},
|
|
325
|
+
ownKeys() {
|
|
326
|
+
return Reflect.ownKeys(resolveActiveFaker())
|
|
327
|
+
},
|
|
328
|
+
getOwnPropertyDescriptor(_target, prop) {
|
|
329
|
+
const desc = Reflect.getOwnPropertyDescriptor(resolveActiveFaker(), prop)
|
|
330
|
+
return desc ? { ...desc, configurable: true } : undefined
|
|
331
|
+
},
|
|
332
|
+
getPrototypeOf() {
|
|
333
|
+
return Reflect.getPrototypeOf(resolveActiveFaker())
|
|
334
|
+
},
|
|
335
|
+
})
|
|
232
336
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
337
|
+
const mergedOptions: RunSeedersOptions =
|
|
338
|
+
defaultConcurrency !== undefined && options?.concurrency === undefined
|
|
339
|
+
? { ...options, concurrency: defaultConcurrency }
|
|
340
|
+
: (options ?? {})
|
|
341
|
+
|
|
342
|
+
return runSeedersCore(
|
|
343
|
+
seeders,
|
|
344
|
+
{
|
|
345
|
+
context: async () => {
|
|
346
|
+
const base: BaseSeederContext<ResolvedExpect<TExpect>> = {
|
|
347
|
+
faker: scopedFaker,
|
|
348
|
+
step: stepRunner.step,
|
|
349
|
+
expect: (customExpect ?? getDefaultExpect()) as ResolvedExpect<TExpect>,
|
|
350
|
+
}
|
|
351
|
+
if (!config?.context) return base as unknown as TContext
|
|
352
|
+
const extra = await config.context(base)
|
|
353
|
+
return extra === base
|
|
354
|
+
? (base as unknown as TContext)
|
|
355
|
+
: ({ ...base, ...extra } as unknown as TContext)
|
|
246
356
|
},
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
357
|
+
preloadCache: config?.cache?.getAll ? () => stepRunner.preload() : undefined,
|
|
358
|
+
flushCache: config?.cache?.setMany ? () => stepRunner.flush() : undefined,
|
|
359
|
+
createSeederScope: ({ name, fresh, concurrent }) => {
|
|
360
|
+
const stepScope = stepRunner.createScope({
|
|
361
|
+
seederName: name,
|
|
362
|
+
fresh,
|
|
363
|
+
prefix: concurrent ? name : undefined,
|
|
364
|
+
})
|
|
365
|
+
const slot: FakerSlot = {
|
|
366
|
+
name,
|
|
367
|
+
isolated: fakerSeed !== undefined || concurrent,
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
return {
|
|
371
|
+
record: stepScope.record,
|
|
372
|
+
run: <T>(fn: () => Promise<T>) =>
|
|
373
|
+
stepRunner.runWithScope(stepScope, () => fakerStorage.run(slot, fn)),
|
|
374
|
+
}
|
|
375
|
+
},
|
|
376
|
+
bannerName,
|
|
377
|
+
target: config?.target,
|
|
378
|
+
onBeforeAll: config?.onBeforeAll,
|
|
379
|
+
onAfterAll: config?.onAfterAll,
|
|
380
|
+
},
|
|
381
|
+
mergedOptions,
|
|
382
|
+
)
|
|
252
383
|
}
|
|
253
384
|
|
|
254
|
-
const
|
|
255
|
-
seeders: readonly
|
|
256
|
-
options?:
|
|
257
|
-
)
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
385
|
+
const runSeeders = ((
|
|
386
|
+
seeders: readonly Seeder<TContext, string, unknown, string>[],
|
|
387
|
+
options?: RunSeedersOptions,
|
|
388
|
+
) => runInternal(seeders, options)) as SeederInstance<TContext>['runSeeders']
|
|
389
|
+
|
|
390
|
+
const runSeedersCli: SeederInstance<TContext>['runSeedersCli'] = async (seeders, options) => {
|
|
391
|
+
const bannerName = options?.name ?? 'Seeders'
|
|
392
|
+
const code = await runCli(
|
|
393
|
+
seeders,
|
|
394
|
+
(s, opts) =>
|
|
395
|
+
runInternal(s as readonly Seeder<TContext, string, unknown, string>[], opts, bannerName),
|
|
396
|
+
{
|
|
397
|
+
name: bannerName,
|
|
398
|
+
argv: options?.argv ?? process.argv.slice(2),
|
|
399
|
+
target: config?.target,
|
|
400
|
+
defaultConcurrency,
|
|
401
|
+
},
|
|
402
|
+
)
|
|
262
403
|
process.exit(code)
|
|
263
404
|
}
|
|
264
405
|
|
package/src/define-seeder.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { MaybePromise, Seeder, SeederConfig, SeederName } from './types.js'
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* Create a typed seeder definition
|
|
4
|
+
* Create a typed seeder definition factory bound to `TContext`.
|
|
5
5
|
*
|
|
6
6
|
* This is the core factory that creates a seeder from a configuration.
|
|
7
7
|
* The seeder can then be passed to `runSeeders` for execution.
|
|
@@ -30,17 +30,24 @@ export function createDefineSeeder<TContext>() {
|
|
|
30
30
|
return function defineSeeder<
|
|
31
31
|
TName extends string,
|
|
32
32
|
TOutput,
|
|
33
|
-
const TDeps extends readonly
|
|
34
|
-
>(
|
|
35
|
-
|
|
36
|
-
|
|
33
|
+
const TDeps extends readonly Seeder<TContext, string, unknown, string>[] = readonly [],
|
|
34
|
+
>(
|
|
35
|
+
config: SeederConfig<TContext, TName, TOutput, TDeps>,
|
|
36
|
+
): Seeder<TContext, TName, Awaited<TOutput>, SeederName<TDeps[number]>> {
|
|
37
|
+
// Extract and deduplicate names from seeder objects at runtime
|
|
38
|
+
const dependsOnNames = [
|
|
39
|
+
...new Set((config.dependsOn ?? []).map((seeder) => seeder.name)),
|
|
40
|
+
] as SeederName<TDeps[number]>[]
|
|
37
41
|
|
|
38
42
|
return {
|
|
39
43
|
name: config.name,
|
|
40
44
|
description: config.description,
|
|
41
45
|
dependsOn: dependsOnNames,
|
|
42
46
|
// Cast is safe because the deps object will have the correct shape at runtime
|
|
43
|
-
run: config.run as (
|
|
47
|
+
run: config.run as (
|
|
48
|
+
ctx: TContext,
|
|
49
|
+
deps: Record<string, unknown>,
|
|
50
|
+
) => MaybePromise<Awaited<TOutput>>,
|
|
44
51
|
}
|
|
45
52
|
}
|
|
46
53
|
}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import type { SeederAny } from './types'
|
|
1
|
+
import type { SeederAny } from './types.js'
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Error thrown when circular dependencies are detected in seeders
|
|
5
5
|
*/
|
|
6
6
|
export class CircularDependencyError extends Error {
|
|
7
7
|
constructor(cycle: string[]) {
|
|
8
|
-
super(`Circular dependency detected in seeders: ${cycle.join(' -> ')} -> ${cycle[0]}`)
|
|
8
|
+
super(`Circular dependency detected in seeders: ${cycle.join(' -> ')} -> ${cycle[0] ?? ''}`)
|
|
9
9
|
this.name = 'CircularDependencyError'
|
|
10
10
|
}
|
|
11
11
|
}
|
|
@@ -63,33 +63,24 @@ export function resolveDependencyOrder(
|
|
|
63
63
|
seederMap.set(seeder.name, seeder)
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
-
//
|
|
67
|
-
for (const seeder of seeders) {
|
|
68
|
-
for (const dep of seeder.dependsOn) {
|
|
69
|
-
if (!seederMap.has(dep)) {
|
|
70
|
-
throw new MissingDependencyError(seeder.name, dep)
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
// Build adjacency list and in-degree count
|
|
66
|
+
// Build adjacency list and in-degree count (deduplicating repeated deps per seeder)
|
|
76
67
|
const inDegree = new Map<string, number>()
|
|
77
68
|
const dependents = new Map<string, string[]>()
|
|
78
69
|
|
|
79
|
-
// Initialize
|
|
80
70
|
for (const seeder of seeders) {
|
|
81
71
|
inDegree.set(seeder.name, 0)
|
|
82
72
|
dependents.set(seeder.name, [])
|
|
83
73
|
}
|
|
84
74
|
|
|
85
|
-
// Build the graph
|
|
86
75
|
for (const seeder of seeders) {
|
|
87
|
-
|
|
88
|
-
|
|
76
|
+
const uniqueDeps = new Set(seeder.dependsOn)
|
|
77
|
+
inDegree.set(seeder.name, uniqueDeps.size)
|
|
78
|
+
for (const dep of uniqueDeps) {
|
|
89
79
|
const deps = dependents.get(dep)
|
|
90
|
-
if (deps) {
|
|
91
|
-
|
|
80
|
+
if (!deps) {
|
|
81
|
+
throw new MissingDependencyError(seeder.name, dep)
|
|
92
82
|
}
|
|
83
|
+
deps.push(seeder.name)
|
|
93
84
|
}
|
|
94
85
|
}
|
|
95
86
|
|
|
@@ -101,14 +92,15 @@ export function resolveDependencyOrder(
|
|
|
101
92
|
}
|
|
102
93
|
}
|
|
103
94
|
|
|
104
|
-
// Process the queue
|
|
95
|
+
// Process the queue with an index pointer (O(V + E))
|
|
105
96
|
const result: string[] = []
|
|
106
|
-
|
|
107
|
-
|
|
97
|
+
let head = 0
|
|
98
|
+
while (head < queue.length) {
|
|
99
|
+
const current = queue[head++]!
|
|
108
100
|
result.push(current)
|
|
109
101
|
|
|
110
|
-
|
|
111
|
-
|
|
102
|
+
const deps = dependents.get(current)
|
|
103
|
+
if (!deps) continue
|
|
112
104
|
for (const dependent of deps) {
|
|
113
105
|
const newDegree = (inDegree.get(dependent) ?? 0) - 1
|
|
114
106
|
inDegree.set(dependent, newDegree)
|
|
@@ -120,8 +112,8 @@ export function resolveDependencyOrder(
|
|
|
120
112
|
|
|
121
113
|
// Check for circular dependencies
|
|
122
114
|
if (result.length !== seeders.length) {
|
|
123
|
-
|
|
124
|
-
const remaining = seeders.filter((s) => !
|
|
115
|
+
const resolved = new Set(result)
|
|
116
|
+
const remaining = seeders.filter((s) => !resolved.has(s.name))
|
|
125
117
|
const cycle = findCycle(remaining, seederMap)
|
|
126
118
|
throw new CircularDependencyError(cycle)
|
|
127
119
|
}
|
|
@@ -154,7 +146,6 @@ function findCycle(remaining: readonly SeederAny[], seederMap: Map<string, Seede
|
|
|
154
146
|
function dfs(name: string): boolean {
|
|
155
147
|
const existingIndex = path.indexOf(name)
|
|
156
148
|
if (existingIndex !== -1) {
|
|
157
|
-
// Found cycle - record where it starts
|
|
158
149
|
cycleStart = existingIndex
|
|
159
150
|
return true
|
|
160
151
|
}
|
|
@@ -182,11 +173,9 @@ function findCycle(remaining: readonly SeederAny[], seederMap: Map<string, Seede
|
|
|
182
173
|
path.length = 0
|
|
183
174
|
cycleStart = -1
|
|
184
175
|
if (dfs(seeder.name)) {
|
|
185
|
-
// Return only the cycle portion of the path
|
|
186
176
|
return cycleStart >= 0 ? path.slice(cycleStart) : path
|
|
187
177
|
}
|
|
188
178
|
}
|
|
189
179
|
|
|
190
|
-
// Fallback: just return the names of remaining seeders
|
|
191
180
|
return remaining.map((s) => s.name)
|
|
192
181
|
}
|