plantr 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.d.ts +17 -0
- package/dist/cli.js +59 -0
- package/dist/index-a1s5r901.js +4 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.js +517 -0
- package/dist/src/create-seeder-instance.d.ts +171 -0
- package/dist/src/define-seeder.d.ts +28 -0
- package/dist/src/dependency-resolver.d.ts +23 -0
- package/dist/src/formatting.d.ts +40 -0
- package/dist/src/run-seeders.d.ts +27 -0
- package/dist/src/seeding-state.d.ts +18 -0
- package/dist/src/step.d.ts +30 -0
- package/dist/src/types.d.ts +77 -0
- package/index.ts +76 -0
- package/package.json +66 -0
- package/readme.md +230 -0
- package/src/create-seeder-instance.ts +315 -0
- package/src/define-seeder.ts +46 -0
- package/src/dependency-resolver.ts +152 -0
- package/src/formatting.ts +202 -0
- package/src/run-seeders.ts +182 -0
- package/src/seeding-state.ts +26 -0
- package/src/step.ts +99 -0
- package/src/types.ts +99 -0
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import type { SeederAny } from './types'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Error thrown when circular dependencies are detected in seeders
|
|
5
|
+
*/
|
|
6
|
+
export class CircularDependencyError extends Error {
|
|
7
|
+
constructor(cycle: string[]) {
|
|
8
|
+
super(`Circular dependency detected in seeders: ${cycle.join(' -> ')} -> ${cycle[0]}`)
|
|
9
|
+
this.name = 'CircularDependencyError'
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Error thrown when a seeder depends on a non-existent seeder
|
|
15
|
+
*/
|
|
16
|
+
export class MissingDependencyError extends Error {
|
|
17
|
+
constructor(seeder: string, missingDep: string) {
|
|
18
|
+
super(`Seeder "${seeder}" depends on "${missingDep}" which does not exist`)
|
|
19
|
+
this.name = 'MissingDependencyError'
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Resolves the execution order of seeders based on their dependencies
|
|
25
|
+
* using Kahn's algorithm (topological sort)
|
|
26
|
+
*
|
|
27
|
+
* @param seeders - Array of seeders to sort
|
|
28
|
+
* @returns Array of seeder names in execution order
|
|
29
|
+
* @throws {CircularDependencyError} If circular dependencies are detected
|
|
30
|
+
* @throws {MissingDependencyError} If a seeder depends on a non-existent seeder
|
|
31
|
+
*/
|
|
32
|
+
export function resolveDependencyOrder(seeders: readonly SeederAny[]): string[] {
|
|
33
|
+
// Build a map of seeder names for quick lookup
|
|
34
|
+
const seederMap = new Map<string, SeederAny>()
|
|
35
|
+
for (const seeder of seeders) {
|
|
36
|
+
seederMap.set(seeder.name, seeder)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Validate all dependencies exist
|
|
40
|
+
for (const seeder of seeders) {
|
|
41
|
+
for (const dep of seeder.dependsOn) {
|
|
42
|
+
if (!seederMap.has(dep)) {
|
|
43
|
+
throw new MissingDependencyError(seeder.name, dep)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Build adjacency list and in-degree count
|
|
49
|
+
const inDegree = new Map<string, number>()
|
|
50
|
+
const dependents = new Map<string, string[]>()
|
|
51
|
+
|
|
52
|
+
// Initialize
|
|
53
|
+
for (const seeder of seeders) {
|
|
54
|
+
inDegree.set(seeder.name, 0)
|
|
55
|
+
dependents.set(seeder.name, [])
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Build the graph
|
|
59
|
+
for (const seeder of seeders) {
|
|
60
|
+
inDegree.set(seeder.name, seeder.dependsOn.length)
|
|
61
|
+
for (const dep of seeder.dependsOn) {
|
|
62
|
+
const deps = dependents.get(dep)
|
|
63
|
+
if (deps) {
|
|
64
|
+
deps.push(seeder.name)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Find all seeders with no dependencies (in-degree 0)
|
|
70
|
+
const queue: string[] = []
|
|
71
|
+
for (const [name, degree] of inDegree) {
|
|
72
|
+
if (degree === 0) {
|
|
73
|
+
queue.push(name)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Process the queue
|
|
78
|
+
const result: string[] = []
|
|
79
|
+
while (queue.length > 0) {
|
|
80
|
+
const current = queue.shift()!
|
|
81
|
+
result.push(current)
|
|
82
|
+
|
|
83
|
+
// Reduce in-degree for all dependents
|
|
84
|
+
const deps = dependents.get(current) ?? []
|
|
85
|
+
for (const dependent of deps) {
|
|
86
|
+
const newDegree = (inDegree.get(dependent) ?? 0) - 1
|
|
87
|
+
inDegree.set(dependent, newDegree)
|
|
88
|
+
if (newDegree === 0) {
|
|
89
|
+
queue.push(dependent)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Check for circular dependencies
|
|
95
|
+
if (result.length !== seeders.length) {
|
|
96
|
+
// Find the cycle for a better error message
|
|
97
|
+
const remaining = seeders.filter((s) => !result.includes(s.name))
|
|
98
|
+
const cycle = findCycle(remaining, seederMap)
|
|
99
|
+
throw new CircularDependencyError(cycle)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return result
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Find a cycle in the remaining seeders for error reporting.
|
|
107
|
+
* Returns the nodes that form the cycle.
|
|
108
|
+
*/
|
|
109
|
+
function findCycle(remaining: readonly SeederAny[], seederMap: Map<string, SeederAny>): string[] {
|
|
110
|
+
const visited = new Set<string>()
|
|
111
|
+
const path: string[] = []
|
|
112
|
+
let cycleStart = -1
|
|
113
|
+
|
|
114
|
+
function dfs(name: string): boolean {
|
|
115
|
+
const existingIndex = path.indexOf(name)
|
|
116
|
+
if (existingIndex !== -1) {
|
|
117
|
+
// Found cycle - record where it starts
|
|
118
|
+
cycleStart = existingIndex
|
|
119
|
+
return true
|
|
120
|
+
}
|
|
121
|
+
if (visited.has(name)) {
|
|
122
|
+
return false
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
visited.add(name)
|
|
126
|
+
path.push(name)
|
|
127
|
+
|
|
128
|
+
const seeder = seederMap.get(name)
|
|
129
|
+
if (seeder) {
|
|
130
|
+
for (const dep of seeder.dependsOn) {
|
|
131
|
+
if (dfs(dep)) {
|
|
132
|
+
return true
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
path.pop()
|
|
138
|
+
return false
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
for (const seeder of remaining) {
|
|
142
|
+
path.length = 0
|
|
143
|
+
cycleStart = -1
|
|
144
|
+
if (dfs(seeder.name)) {
|
|
145
|
+
// Return only the cycle portion of the path
|
|
146
|
+
return cycleStart >= 0 ? path.slice(cycleStart) : path
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Fallback: just return the names of remaining seeders
|
|
151
|
+
return remaining.map((s) => s.name)
|
|
152
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import type { SeederResult } from './types'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* ANSI color codes for terminal output
|
|
5
|
+
*/
|
|
6
|
+
const colors = {
|
|
7
|
+
reset: '\x1b[0m',
|
|
8
|
+
bold: '\x1b[1m',
|
|
9
|
+
dim: '\x1b[2m',
|
|
10
|
+
red: '\x1b[31m',
|
|
11
|
+
green: '\x1b[32m',
|
|
12
|
+
yellow: '\x1b[33m',
|
|
13
|
+
cyan: '\x1b[36m',
|
|
14
|
+
white: '\x1b[37m',
|
|
15
|
+
gray: '\x1b[90m',
|
|
16
|
+
} as const
|
|
17
|
+
|
|
18
|
+
type ColorName = 'red' | 'green' | 'yellow' | 'cyan' | 'white' | 'gray' | 'dim'
|
|
19
|
+
type StyleName = 'bold' | 'dim'
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Simple colorize function for terminal output
|
|
23
|
+
*/
|
|
24
|
+
export function colorize(text: string, color: ColorName, style?: StyleName): string {
|
|
25
|
+
let result = ''
|
|
26
|
+
if (style === 'bold') result += colors.bold
|
|
27
|
+
if (style === 'dim') result += colors.dim
|
|
28
|
+
result += colors[color] + text + colors.reset
|
|
29
|
+
return result
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Format duration in a human-readable way
|
|
34
|
+
*/
|
|
35
|
+
export function formatDuration(ms: number): string {
|
|
36
|
+
if (ms < 1000) return `${ms}ms`
|
|
37
|
+
if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`
|
|
38
|
+
return `${(ms / 60000).toFixed(1)}m`
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Print a formatted table of seeder results
|
|
43
|
+
*/
|
|
44
|
+
export function printResultsTable(results: SeederResult[]): void {
|
|
45
|
+
if (results.length === 0) {
|
|
46
|
+
console.log('No seeders registered')
|
|
47
|
+
return
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Calculate column widths
|
|
51
|
+
const nameHeader = 'Seeder'
|
|
52
|
+
const statusHeader = 'Status'
|
|
53
|
+
const durationHeader = 'Duration'
|
|
54
|
+
|
|
55
|
+
const maxNameLen = Math.max(nameHeader.length, ...results.map((r) => r.name.length))
|
|
56
|
+
const maxStatusLen = Math.max(
|
|
57
|
+
statusHeader.length,
|
|
58
|
+
10, // "✗ Failed" is the longest status
|
|
59
|
+
)
|
|
60
|
+
const maxDurationLen = Math.max(
|
|
61
|
+
durationHeader.length,
|
|
62
|
+
...results.map((r) => formatDuration(r.durationMs ?? 0).length),
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
const topBorder = `┌${'─'.repeat(maxNameLen + 2)}┬${'─'.repeat(maxStatusLen + 2)}┬${'─'.repeat(maxDurationLen + 2)}┐`
|
|
66
|
+
const divider = `├${'─'.repeat(maxNameLen + 2)}┼${'─'.repeat(maxStatusLen + 2)}┼${'─'.repeat(maxDurationLen + 2)}┤`
|
|
67
|
+
const bottomBorder = `└${'─'.repeat(maxNameLen + 2)}┴${'─'.repeat(maxStatusLen + 2)}┴${'─'.repeat(maxDurationLen + 2)}┘`
|
|
68
|
+
|
|
69
|
+
console.log('')
|
|
70
|
+
console.log(topBorder)
|
|
71
|
+
console.log(
|
|
72
|
+
`│ ${colorize(nameHeader.padEnd(maxNameLen), 'white', 'bold')} │ ${colorize(statusHeader.padEnd(maxStatusLen), 'white', 'bold')} │ ${colorize(durationHeader.padEnd(maxDurationLen), 'white', 'bold')} │`,
|
|
73
|
+
)
|
|
74
|
+
console.log(divider)
|
|
75
|
+
|
|
76
|
+
for (const result of results) {
|
|
77
|
+
let statusDisplay: string
|
|
78
|
+
let statusColor: ColorName
|
|
79
|
+
|
|
80
|
+
switch (result.status) {
|
|
81
|
+
case 'completed':
|
|
82
|
+
statusDisplay = '✓ Done'
|
|
83
|
+
statusColor = 'green'
|
|
84
|
+
break
|
|
85
|
+
case 'failed':
|
|
86
|
+
statusDisplay = '✗ Failed'
|
|
87
|
+
statusColor = 'red'
|
|
88
|
+
break
|
|
89
|
+
case 'skipped':
|
|
90
|
+
statusDisplay = '⊘ Skipped'
|
|
91
|
+
statusColor = 'yellow'
|
|
92
|
+
break
|
|
93
|
+
case 'running':
|
|
94
|
+
statusDisplay = '⟳ Running'
|
|
95
|
+
statusColor = 'yellow'
|
|
96
|
+
break
|
|
97
|
+
default:
|
|
98
|
+
statusDisplay = '○ Pending'
|
|
99
|
+
statusColor = 'gray'
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const duration = result.durationMs !== undefined ? formatDuration(result.durationMs) : '-'
|
|
103
|
+
|
|
104
|
+
console.log(
|
|
105
|
+
`│ ${result.name.padEnd(maxNameLen)} │ ${colorize(statusDisplay.padEnd(maxStatusLen), statusColor)} │ ${colorize(duration.padEnd(maxDurationLen), 'dim')} │`,
|
|
106
|
+
)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
console.log(bottomBorder)
|
|
110
|
+
console.log('')
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Print error details for failed seeders
|
|
115
|
+
*/
|
|
116
|
+
export function printErrors(results: SeederResult[]): void {
|
|
117
|
+
const failed = results.filter((r) => r.status === 'failed')
|
|
118
|
+
|
|
119
|
+
for (const result of failed) {
|
|
120
|
+
console.log(colorize(`❌ Seeder "${result.name}" failed:`, 'red'))
|
|
121
|
+
if (result.error) {
|
|
122
|
+
console.log(` ${colorize(result.error.message, 'dim')}`)
|
|
123
|
+
if (result.error.stack) {
|
|
124
|
+
const stackLines = result.error.stack.split('\n').slice(1, 4)
|
|
125
|
+
for (const line of stackLines) {
|
|
126
|
+
console.log(` ${colorize(line.trim(), 'gray')}`)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
console.log('')
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Print seeder header before execution
|
|
136
|
+
*/
|
|
137
|
+
export function printSeederHeader(
|
|
138
|
+
name: string,
|
|
139
|
+
index: number,
|
|
140
|
+
total: number,
|
|
141
|
+
description?: string,
|
|
142
|
+
): void {
|
|
143
|
+
const seederIndex = `[${index + 1}/${total}]`
|
|
144
|
+
const headerLine = `━━━ ${seederIndex} ${name} ${'━'.repeat(Math.max(0, 50 - name.length - seederIndex.length))}`
|
|
145
|
+
console.log(colorize(headerLine, 'cyan', 'bold'))
|
|
146
|
+
if (description) {
|
|
147
|
+
console.log(colorize(` ${description}`, 'dim'))
|
|
148
|
+
}
|
|
149
|
+
console.log('')
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Print completion status after a seeder runs
|
|
154
|
+
*/
|
|
155
|
+
export function printSeederComplete(durationMs: number, success: boolean): void {
|
|
156
|
+
console.log('')
|
|
157
|
+
if (success) {
|
|
158
|
+
console.log(colorize(` ✓ Completed in ${formatDuration(durationMs)}`, 'green'))
|
|
159
|
+
} else {
|
|
160
|
+
console.log(colorize(` ✗ Failed after ${formatDuration(durationMs)}`, 'red'))
|
|
161
|
+
}
|
|
162
|
+
console.log('')
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Print the initial banner when seeding starts
|
|
167
|
+
*/
|
|
168
|
+
export function printStartBanner(label?: string): void {
|
|
169
|
+
const labelText = label ? ` ${colorize(`(${label})`, 'dim')}` : ''
|
|
170
|
+
console.log(`\n${colorize('🌱 Running Seeders', 'cyan', 'bold')}${labelText}\n`)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Print message when a seeder is skipped due to failed dependencies
|
|
175
|
+
*/
|
|
176
|
+
export function printSeederSkipped(failedDeps: string[]): void {
|
|
177
|
+
console.log('')
|
|
178
|
+
console.log(colorize(` ⊘ Skipped (depends on failed: ${failedDeps.join(', ')})`, 'yellow'))
|
|
179
|
+
console.log('')
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Print the final summary after all seeders complete
|
|
184
|
+
*/
|
|
185
|
+
export function printSummary(results: SeederResult[]): void {
|
|
186
|
+
const completed = results.filter((r) => r.status === 'completed').length
|
|
187
|
+
const failed = results.filter((r) => r.status === 'failed').length
|
|
188
|
+
const skipped = results.filter((r) => r.status === 'skipped').length
|
|
189
|
+
const pending = results.filter((r) => r.status === 'pending').length
|
|
190
|
+
|
|
191
|
+
if (failed > 0 || skipped > 0) {
|
|
192
|
+
const parts = [`${completed} completed`]
|
|
193
|
+
if (failed > 0) parts.push(`${failed} failed`)
|
|
194
|
+
if (skipped > 0) parts.push(`${skipped} skipped`)
|
|
195
|
+
if (pending > 0) parts.push(`${pending} pending`)
|
|
196
|
+
console.log(colorize(`Seeding failed: ${parts.join(', ')}`, 'red'))
|
|
197
|
+
} else {
|
|
198
|
+
console.log(
|
|
199
|
+
`${colorize('✓ Seeding complete:', 'green')} ${completed} seeders executed successfully\n`,
|
|
200
|
+
)
|
|
201
|
+
}
|
|
202
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { resolveDependencyOrder } from './dependency-resolver'
|
|
2
|
+
import {
|
|
3
|
+
printErrors,
|
|
4
|
+
printResultsTable,
|
|
5
|
+
printSeederComplete,
|
|
6
|
+
printSeederHeader,
|
|
7
|
+
printSeederSkipped,
|
|
8
|
+
printStartBanner,
|
|
9
|
+
printSummary,
|
|
10
|
+
} from './formatting'
|
|
11
|
+
import type { RunSeedersOptions, SeederAny, SeederResult } from './types'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Internal configuration used by the runner.
|
|
15
|
+
* This is created by createSeederInstance and includes the wrapped context factory.
|
|
16
|
+
*/
|
|
17
|
+
export type InternalSeederConfig<TContext> = {
|
|
18
|
+
/** Factory function that creates the full context (already includes base context) */
|
|
19
|
+
context: () => TContext | Promise<TContext>
|
|
20
|
+
/** Called before each seeder to set the current seeder name (for cache key scoping) */
|
|
21
|
+
setSeederName?: (name: string) => void
|
|
22
|
+
/** Called before all seeders run */
|
|
23
|
+
onBeforeAll?: () => void | Promise<void>
|
|
24
|
+
/** Called after all seeders complete */
|
|
25
|
+
onAfterAll?: () => void | Promise<void>
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Core seeder runner - executes seeders in dependency order
|
|
30
|
+
*
|
|
31
|
+
* @param seeders - Array of seeders to run
|
|
32
|
+
* @param config - Instance configuration (context factory, lifecycle hooks)
|
|
33
|
+
* @param options - Runner options (verbose output, etc.)
|
|
34
|
+
* @returns Object containing results and success status
|
|
35
|
+
*/
|
|
36
|
+
export async function runSeedersCore<TContext>(
|
|
37
|
+
seeders: readonly SeederAny[],
|
|
38
|
+
config: InternalSeederConfig<TContext>,
|
|
39
|
+
options: RunSeedersOptions = {},
|
|
40
|
+
): Promise<{
|
|
41
|
+
results: SeederResult[]
|
|
42
|
+
success: boolean
|
|
43
|
+
}> {
|
|
44
|
+
const { printResults = true, verbose = true, continueOnFailure = false } = options
|
|
45
|
+
|
|
46
|
+
// Call onBeforeAll hook
|
|
47
|
+
if (config.onBeforeAll) {
|
|
48
|
+
await config.onBeforeAll()
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (verbose) {
|
|
52
|
+
printStartBanner()
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Resolve execution order based on dependencies
|
|
56
|
+
let orderedNames: string[]
|
|
57
|
+
try {
|
|
58
|
+
orderedNames = resolveDependencyOrder(seeders)
|
|
59
|
+
} catch (error) {
|
|
60
|
+
console.error('Failed to resolve seeder dependencies:')
|
|
61
|
+
console.error(` ${error instanceof Error ? error.message : String(error)}`)
|
|
62
|
+
if (config.onAfterAll) {
|
|
63
|
+
await config.onAfterAll()
|
|
64
|
+
}
|
|
65
|
+
return { results: [], success: false }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Create a map for quick seeder lookup
|
|
69
|
+
const seederMap = new Map<string, SeederAny>()
|
|
70
|
+
for (const seeder of seeders) {
|
|
71
|
+
seederMap.set(seeder.name, seeder)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Initialize results
|
|
75
|
+
const results: SeederResult[] = orderedNames.map((name) => ({
|
|
76
|
+
name,
|
|
77
|
+
status: 'pending',
|
|
78
|
+
}))
|
|
79
|
+
|
|
80
|
+
// Store outputs for dependency injection
|
|
81
|
+
const outputs: Record<string, unknown> = {}
|
|
82
|
+
|
|
83
|
+
// Track failed seeders to skip their dependents
|
|
84
|
+
const failedSeeders = new Set<string>()
|
|
85
|
+
|
|
86
|
+
// Create context once for all seeders
|
|
87
|
+
const ctx = await config.context()
|
|
88
|
+
|
|
89
|
+
// Execute seeders in order
|
|
90
|
+
for (let i = 0; i < orderedNames.length; i++) {
|
|
91
|
+
const name = orderedNames[i]
|
|
92
|
+
const result = results[i]
|
|
93
|
+
|
|
94
|
+
// TypeScript safety - should never happen since we iterate within bounds
|
|
95
|
+
if (!name || !result) continue
|
|
96
|
+
|
|
97
|
+
const seeder = seederMap.get(name)
|
|
98
|
+
if (!seeder) continue
|
|
99
|
+
|
|
100
|
+
// Check if any dependencies have failed (only relevant when continueOnFailure is true)
|
|
101
|
+
if (continueOnFailure) {
|
|
102
|
+
const hasFailedDep = seeder.dependsOn.some((dep) => failedSeeders.has(dep))
|
|
103
|
+
if (hasFailedDep) {
|
|
104
|
+
result.status = 'skipped'
|
|
105
|
+
failedSeeders.add(name) // Treat skipped as failed for dependency chain
|
|
106
|
+
if (verbose) {
|
|
107
|
+
printSeederHeader(name, i, orderedNames.length, seeder.description)
|
|
108
|
+
printSeederSkipped(seeder.dependsOn.filter((d) => failedSeeders.has(d)))
|
|
109
|
+
}
|
|
110
|
+
continue
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Print seeder header
|
|
115
|
+
if (verbose) {
|
|
116
|
+
printSeederHeader(name, i, orderedNames.length, seeder.description)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Update status to running
|
|
120
|
+
result.status = 'running'
|
|
121
|
+
|
|
122
|
+
// Set current seeder name for cache key scoping
|
|
123
|
+
if (config.setSeederName) {
|
|
124
|
+
config.setSeederName(name)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Build dependency outputs for this seeder
|
|
128
|
+
const deps: Record<string, unknown> = {}
|
|
129
|
+
for (const depName of seeder.dependsOn) {
|
|
130
|
+
deps[depName] = outputs[depName]
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const startTime = Date.now()
|
|
134
|
+
|
|
135
|
+
try {
|
|
136
|
+
// Run the seeder
|
|
137
|
+
const output = await seeder.run(ctx, deps)
|
|
138
|
+
|
|
139
|
+
// Store output for dependents
|
|
140
|
+
outputs[name] = output
|
|
141
|
+
|
|
142
|
+
// Update result
|
|
143
|
+
result.status = 'completed'
|
|
144
|
+
result.durationMs = Date.now() - startTime
|
|
145
|
+
result.output = output
|
|
146
|
+
|
|
147
|
+
if (verbose) {
|
|
148
|
+
printSeederComplete(result.durationMs, true)
|
|
149
|
+
}
|
|
150
|
+
} catch (error) {
|
|
151
|
+
// Update result with error
|
|
152
|
+
result.status = 'failed'
|
|
153
|
+
result.durationMs = Date.now() - startTime
|
|
154
|
+
result.error = error instanceof Error ? error : new Error(String(error))
|
|
155
|
+
failedSeeders.add(name)
|
|
156
|
+
|
|
157
|
+
if (verbose) {
|
|
158
|
+
printSeederComplete(result.durationMs, false)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Stop execution on failure unless continueOnFailure is true
|
|
162
|
+
if (!continueOnFailure) {
|
|
163
|
+
break
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Print results table
|
|
169
|
+
if (printResults) {
|
|
170
|
+
printResultsTable(results)
|
|
171
|
+
printErrors(results)
|
|
172
|
+
printSummary(results)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Call onAfterAll hook
|
|
176
|
+
if (config.onAfterAll) {
|
|
177
|
+
await config.onAfterAll()
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const failed = results.filter((r) => r.status === 'failed').length
|
|
181
|
+
return { results, success: failed === 0 }
|
|
182
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Global seeding state to disable side effects during seeding.
|
|
3
|
+
*
|
|
4
|
+
* When seeding is active, consumers can check this state to skip
|
|
5
|
+
* side effects like:
|
|
6
|
+
* - Sending notifications (email, Slack, push)
|
|
7
|
+
* - Creating background jobs
|
|
8
|
+
* - Syncing to external services
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
let isSeeding = false
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Check if seeding is currently active
|
|
15
|
+
*/
|
|
16
|
+
export function isSeedingActive(): boolean {
|
|
17
|
+
return isSeeding
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Set the seeding state.
|
|
22
|
+
* Called automatically by the seeder runner's onBeforeAll/onAfterAll hooks.
|
|
23
|
+
*/
|
|
24
|
+
export function setSeedingActive(active: boolean): void {
|
|
25
|
+
isSeeding = active
|
|
26
|
+
}
|
package/src/step.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { colorize } from './formatting'
|
|
2
|
+
|
|
3
|
+
export type StepOptions = {
|
|
4
|
+
/** Enable caching for this step */
|
|
5
|
+
useCache?: boolean
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export type StepFn = <T>(
|
|
9
|
+
description: string,
|
|
10
|
+
fn: () => T | Promise<T>,
|
|
11
|
+
options?: StepOptions,
|
|
12
|
+
) => Promise<T>
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Cache interface for step caching.
|
|
16
|
+
* Provide get/set functions to enable caching in the step runner.
|
|
17
|
+
*/
|
|
18
|
+
export type SeederCache = {
|
|
19
|
+
/** Get a cached value by key. Returns undefined if not found. */
|
|
20
|
+
get: <T>(key: string) => Promise<T | undefined>
|
|
21
|
+
/** Set a cached value by key. */
|
|
22
|
+
set: <T>(key: string, value: T) => Promise<void>
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
type StepRunnerConfig = {
|
|
26
|
+
cache?: SeederCache
|
|
27
|
+
/** Seeder name for scoping cache keys */
|
|
28
|
+
seederName?: string
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Create a step runner for organizing seeder workflow.
|
|
33
|
+
* Optionally provide a cache for step caching support.
|
|
34
|
+
*/
|
|
35
|
+
export function createStepRunner(config?: StepRunnerConfig): {
|
|
36
|
+
step: StepFn
|
|
37
|
+
/** Set the current seeder name for cache key scoping */
|
|
38
|
+
setSeederName: (name: string) => void
|
|
39
|
+
} {
|
|
40
|
+
const { cache } = config ?? {}
|
|
41
|
+
let currentSeederName = config?.seederName ?? ''
|
|
42
|
+
|
|
43
|
+
const setSeederName = (name: string): void => {
|
|
44
|
+
currentSeederName = name
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const step: StepFn = async <T>(
|
|
48
|
+
description: string,
|
|
49
|
+
fn: () => T | Promise<T>,
|
|
50
|
+
options?: StepOptions,
|
|
51
|
+
): Promise<T> => {
|
|
52
|
+
const { useCache = false } = options ?? {}
|
|
53
|
+
|
|
54
|
+
// Generate cache key from seeder name + description (scoped to avoid collisions)
|
|
55
|
+
const slugifiedDescription = description
|
|
56
|
+
.toLowerCase()
|
|
57
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
58
|
+
.replace(/^-|-$/g, '')
|
|
59
|
+
const cacheKey = currentSeederName
|
|
60
|
+
? `${currentSeederName}:${slugifiedDescription}`
|
|
61
|
+
: slugifiedDescription
|
|
62
|
+
|
|
63
|
+
try {
|
|
64
|
+
let result: T
|
|
65
|
+
let wasCached = false
|
|
66
|
+
|
|
67
|
+
if (useCache && cache) {
|
|
68
|
+
// Try to get from cache
|
|
69
|
+
const cached = await cache.get<T>(cacheKey)
|
|
70
|
+
if (cached !== undefined) {
|
|
71
|
+
result = cached
|
|
72
|
+
wasCached = true
|
|
73
|
+
} else {
|
|
74
|
+
// Execute and cache
|
|
75
|
+
result = await fn()
|
|
76
|
+
await cache.set(cacheKey, result)
|
|
77
|
+
}
|
|
78
|
+
} else if (useCache && !cache) {
|
|
79
|
+
// Warn if caching requested but no cache configured
|
|
80
|
+
console.log(colorize(` ⚠ Cache not configured, running without cache`, 'yellow'))
|
|
81
|
+
result = await fn()
|
|
82
|
+
} else {
|
|
83
|
+
result = await fn()
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const cacheIndicator = wasCached ? ` ${colorize('(cached)', 'cyan')}` : ''
|
|
87
|
+
console.log(` ${colorize('✓', 'green')} ${description}${cacheIndicator}`)
|
|
88
|
+
return result
|
|
89
|
+
} catch (error) {
|
|
90
|
+
console.log(` ${colorize('✗', 'red')} ${description}`)
|
|
91
|
+
if (error instanceof Error) {
|
|
92
|
+
console.log(` ${colorize(error.message, 'dim')}`)
|
|
93
|
+
}
|
|
94
|
+
throw error
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return { step, setSeederName }
|
|
99
|
+
}
|