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