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
package/src/formatting.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { SeederResult } from './types'
1
+ import type { SeederResult } from './types.js'
2
2
 
3
3
  /**
4
4
  * ANSI color codes for terminal output
@@ -15,13 +15,21 @@ const colors = {
15
15
  gray: '\x1b[90m',
16
16
  } as const
17
17
 
18
- type ColorName = 'red' | 'green' | 'yellow' | 'cyan' | 'white' | 'gray' | 'dim'
19
- type StyleName = 'bold' | 'dim'
18
+ export type ColorName = 'red' | 'green' | 'yellow' | 'cyan' | 'white' | 'gray' | 'dim'
19
+ export type StyleName = 'bold' | 'dim'
20
+
21
+ function supportsColor(): boolean {
22
+ if (process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== '') return false
23
+ if (process.env.FORCE_COLOR !== undefined && process.env.FORCE_COLOR !== '0') return true
24
+ return Boolean(process.stdout.isTTY)
25
+ }
20
26
 
21
27
  /**
22
- * Simple colorize function for terminal output
28
+ * Simple colorize function for terminal output.
29
+ * Respects `NO_COLOR`, `FORCE_COLOR`, and stdout TTY state.
23
30
  */
24
31
  export function colorize(text: string, color: ColorName, style?: StyleName): string {
32
+ if (!supportsColor()) return text
25
33
  let result = ''
26
34
  if (style === 'bold') result += colors.bold
27
35
  if (style === 'dim') result += colors.dim
@@ -33,7 +41,7 @@ export function colorize(text: string, color: ColorName, style?: StyleName): str
33
41
  * Format duration in a human-readable way
34
42
  */
35
43
  export function formatDuration(ms: number): string {
36
- if (ms < 1000) return `${ms}ms`
44
+ if (ms < 1000) return `${Math.round(ms)}ms`
37
45
  if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`
38
46
  return `${(ms / 60000).toFixed(1)}m`
39
47
  }
@@ -41,13 +49,12 @@ export function formatDuration(ms: number): string {
41
49
  /**
42
50
  * Print a formatted table of seeder results
43
51
  */
44
- export function printResultsTable(results: SeederResult[]): void {
52
+ export function printResultsTable(results: readonly SeederResult[]): void {
45
53
  if (results.length === 0) {
46
54
  console.log('No seeders registered')
47
55
  return
48
56
  }
49
57
 
50
- // Calculate column widths
51
58
  const nameHeader = 'Seeder'
52
59
  const statusHeader = 'Status'
53
60
  const durationHeader = 'Duration'
@@ -55,11 +62,16 @@ export function printResultsTable(results: SeederResult[]): void {
55
62
  const maxNameLen = Math.max(nameHeader.length, ...results.map((r) => r.name.length))
56
63
  const maxStatusLen = Math.max(
57
64
  statusHeader.length,
58
- 10, // "✗ Failed" is the longest status
65
+ 10, // "⊘ Skipped" / "○ Pending" fit with padding
59
66
  )
60
67
  const maxDurationLen = Math.max(
61
68
  durationHeader.length,
62
- ...results.map((r) => formatDuration(r.durationMs ?? 0).length),
69
+ ...results.map((r) => {
70
+ if (r.status === 'completed' || r.status === 'failed') {
71
+ return formatDuration(r.durationMs).length
72
+ }
73
+ return 1 // "-"
74
+ }),
63
75
  )
64
76
 
65
77
  const topBorder = `┌${'─'.repeat(maxNameLen + 2)}┬${'─'.repeat(maxStatusLen + 2)}┬${'─'.repeat(maxDurationLen + 2)}┐`
@@ -76,31 +88,29 @@ export function printResultsTable(results: SeederResult[]): void {
76
88
  for (const result of results) {
77
89
  let statusDisplay: string
78
90
  let statusColor: ColorName
91
+ let duration = '-'
79
92
 
80
93
  switch (result.status) {
81
94
  case 'completed':
82
95
  statusDisplay = '✓ Done'
83
96
  statusColor = 'green'
97
+ duration = formatDuration(result.durationMs)
84
98
  break
85
99
  case 'failed':
86
100
  statusDisplay = '✗ Failed'
87
101
  statusColor = 'red'
102
+ duration = formatDuration(result.durationMs)
88
103
  break
89
104
  case 'skipped':
90
105
  statusDisplay = '⊘ Skipped'
91
106
  statusColor = 'yellow'
92
107
  break
93
- case 'running':
94
- statusDisplay = '⟳ Running'
95
- statusColor = 'yellow'
96
- break
97
- default:
108
+ case 'pending':
98
109
  statusDisplay = '○ Pending'
99
110
  statusColor = 'gray'
111
+ break
100
112
  }
101
113
 
102
- const duration = result.durationMs !== undefined ? formatDuration(result.durationMs) : '-'
103
-
104
114
  console.log(
105
115
  `│ ${result.name.padEnd(maxNameLen)} │ ${colorize(statusDisplay.padEnd(maxStatusLen), statusColor)} │ ${colorize(duration.padEnd(maxDurationLen), 'dim')} │`,
106
116
  )
@@ -118,21 +128,18 @@ const escapeAnnotation = (text: string) =>
118
128
  * stack, cause and own fields via Bun.inspect) and a hint when cached steps ran first.
119
129
  * Under GitHub Actions, also prints one `::error` annotation per failed seeder.
120
130
  */
121
- export function printErrors(results: SeederResult[]): void {
131
+ export function printErrors(results: readonly SeederResult[]): void {
122
132
  const failed = results.filter((r) => r.status === 'failed')
123
133
 
124
134
  for (const result of failed) {
125
135
  const where = result.failedStep ? ` in step "${result.failedStep}"` : ''
126
136
  console.log(colorize(`❌ Seeder "${result.name}" failed${where}:`, 'red'))
127
- if (result.error) {
128
- const details = Bun.inspect(result.error, { colors: Boolean(process.stdout.isTTY) })
129
- for (const line of details.split('\n')) console.log(` ${line}`)
130
- }
131
- const cached = result.cachedSteps ?? []
132
- if (cached.length > 0) {
137
+ const details = Bun.inspect(result.error, { colors: supportsColor() })
138
+ for (const line of details.split('\n')) console.log(` ${line}`)
139
+ if (result.cachedSteps.length > 0) {
133
140
  console.log(
134
141
  colorize(
135
- ` ${cached.length} earlier step(s) came from the cache: ${cached.join(', ')}. If they are stale, run this seeder fresh (CLI: --only ${result.name} --fresh).`,
142
+ ` ${result.cachedSteps.length} earlier step(s) came from the cache: ${result.cachedSteps.join(', ')}. If they are stale, run this seeder fresh (CLI: --only ${result.name} --fresh).`,
136
143
  'yellow',
137
144
  ),
138
145
  )
@@ -140,7 +147,7 @@ export function printErrors(results: SeederResult[]): void {
140
147
  if (process.env.GITHUB_ACTIONS === 'true') {
141
148
  const title = `Seeder ${result.name} failed${where}`.replace(/[:,]/g, ' ')
142
149
  console.log(
143
- `::error title=${escapeAnnotation(title)}::${escapeAnnotation(result.error?.message ?? 'failed')}`,
150
+ `::error title=${escapeAnnotation(title)}::${escapeAnnotation(result.error.message || 'failed')}`,
144
151
  )
145
152
  }
146
153
  console.log('')
@@ -166,7 +173,7 @@ export function printSeederHeader(
166
173
  }
167
174
 
168
175
  /**
169
- * Print completion status after a seeder runs
176
+ * Print completion status after a seeder runs (sequential mode)
170
177
  */
171
178
  export function printSeederComplete(durationMs: number, success: boolean): void {
172
179
  console.log('')
@@ -178,20 +185,57 @@ export function printSeederComplete(durationMs: number, success: boolean): void
178
185
  console.log('')
179
186
  }
180
187
 
188
+ /**
189
+ * Print compact prefixed completion status (concurrent mode)
190
+ */
191
+ export function printConcurrentComplete(
192
+ seederName: string,
193
+ durationMs: number,
194
+ success: boolean,
195
+ ): void {
196
+ const tag = colorize(`[${seederName}]`, 'cyan', 'bold')
197
+ if (success) {
198
+ console.log(` ${tag} ${colorize(`✓ Completed in ${formatDuration(durationMs)}`, 'green')}`)
199
+ } else {
200
+ console.log(` ${tag} ${colorize(`✗ Failed after ${formatDuration(durationMs)}`, 'red')}`)
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Print compact prefixed skip status (concurrent mode)
206
+ */
207
+ export function printConcurrentSkipped(seederName: string, failedDeps: readonly string[]): void {
208
+ const tag = colorize(`[${seederName}]`, 'cyan', 'bold')
209
+ console.log(
210
+ ` ${tag} ${colorize(`⊘ Skipped (depends on failed: ${failedDeps.join(', ')})`, 'yellow')}`,
211
+ )
212
+ }
213
+
181
214
  /**
182
215
  * Print the initial banner when seeding starts
183
216
  */
184
- export function printStartBanner(target?: { label: string; local: boolean }): void {
217
+ export function printStartBanner(options?: {
218
+ name?: string | undefined
219
+ count?: number | undefined
220
+ target?: { label: string; local: boolean } | undefined
221
+ concurrency?: number | undefined
222
+ }): void {
223
+ const name = options?.name ?? 'Seeders'
224
+ const countText =
225
+ options?.count !== undefined
226
+ ? ` ${colorize(`(${options.count} ${options.count === 1 ? 'seeder' : 'seeders'}${options.concurrency && options.concurrency > 1 ? `, concurrency: ${options.concurrency === Number.POSITIVE_INFINITY ? '∞' : options.concurrency}` : ''})`, 'dim')}`
227
+ : ''
228
+ const target = options?.target
185
229
  const targetText = target
186
230
  ? ` ${colorize(`→ ${target.label}`, 'dim')}${target.local ? '' : ` ${colorize('(remote, allowed)', 'yellow')}`}`
187
231
  : ''
188
- console.log(`\n${colorize('🌱 Running Seeders', 'cyan', 'bold')}${targetText}\n`)
232
+ console.log(`\n${colorize(`🌱 Running ${name}`, 'cyan', 'bold')}${countText}${targetText}\n`)
189
233
  }
190
234
 
191
235
  /**
192
236
  * Print message when a seeder is skipped due to failed dependencies
193
237
  */
194
- export function printSeederSkipped(failedDeps: string[]): void {
238
+ export function printSeederSkipped(failedDeps: readonly string[]): void {
195
239
  console.log('')
196
240
  console.log(colorize(` ⊘ Skipped (depends on failed: ${failedDeps.join(', ')})`, 'yellow'))
197
241
  console.log('')
@@ -200,21 +244,62 @@ export function printSeederSkipped(failedDeps: string[]): void {
200
244
  /**
201
245
  * Print the final summary after all seeders complete
202
246
  */
203
- export function printSummary(results: SeederResult[]): void {
204
- const completed = results.filter((r) => r.status === 'completed').length
205
- const failed = results.filter((r) => r.status === 'failed').length
206
- const skipped = results.filter((r) => r.status === 'skipped').length
207
- const pending = results.filter((r) => r.status === 'pending').length
247
+ export function printSummary(
248
+ results: readonly SeederResult[],
249
+ totalDurationMs?: number,
250
+ concurrency = 1,
251
+ ): void {
252
+ let completed = 0
253
+ let failed = 0
254
+ let skipped = 0
255
+ let pending = 0
256
+ let cachedCount = 0
257
+ let totalWorkMs = 0
258
+
259
+ for (const r of results) {
260
+ switch (r.status) {
261
+ case 'completed':
262
+ completed++
263
+ cachedCount += r.cachedSteps.length
264
+ totalWorkMs += r.durationMs
265
+ break
266
+ case 'failed':
267
+ failed++
268
+ cachedCount += r.cachedSteps.length
269
+ totalWorkMs += r.durationMs
270
+ break
271
+ case 'skipped':
272
+ skipped++
273
+ break
274
+ case 'pending':
275
+ pending++
276
+ break
277
+ }
278
+ }
279
+
280
+ const durationSuffix =
281
+ totalDurationMs !== undefined ? ` in ${formatDuration(totalDurationMs)}` : ''
282
+ const speedupSuffix =
283
+ concurrency > 1 &&
284
+ totalDurationMs !== undefined &&
285
+ totalDurationMs > 0 &&
286
+ totalWorkMs > totalDurationMs * 1.1
287
+ ? ` ${colorize(`(${formatDuration(totalWorkMs)} work, ${(totalWorkMs / totalDurationMs).toFixed(1)}× faster)`, 'dim')}`
288
+ : ''
289
+ const cacheSuffix =
290
+ cachedCount > 0
291
+ ? ` ${colorize(`(${cachedCount} cached ${cachedCount === 1 ? 'step' : 'steps'})`, 'cyan')}`
292
+ : ''
208
293
 
209
294
  if (failed > 0 || skipped > 0) {
210
295
  const parts = [`${completed} completed`]
211
296
  if (failed > 0) parts.push(`${failed} failed`)
212
297
  if (skipped > 0) parts.push(`${skipped} skipped`)
213
298
  if (pending > 0) parts.push(`${pending} pending`)
214
- console.log(colorize(`Seeding failed: ${parts.join(', ')}`, 'red'))
299
+ console.log(colorize(`Seeding failed: ${parts.join(', ')}${durationSuffix}`, 'red'))
215
300
  } else {
216
301
  console.log(
217
- `${colorize('✓ Seeding complete:', 'green')} ${completed} seeders executed successfully\n`,
302
+ `${colorize('✓ Seeding complete:', 'green')} ${completed} ${completed === 1 ? 'seeder' : 'seeders'} executed successfully${durationSuffix}${speedupSuffix}${cacheSuffix}\n`,
218
303
  )
219
304
  }
220
305
  }
@@ -0,0 +1,46 @@
1
+ import { createRequire } from 'node:module'
2
+ import type { Faker } from '@faker-js/faker'
3
+
4
+ let loadedFaker: Faker | undefined
5
+
6
+ /**
7
+ * Synchronously load the default English Faker instance on first access.
8
+ * Defers the ~35ms locale initialization cost until a seeder actually uses `faker`.
9
+ */
10
+ export function getDefaultFaker(): Faker {
11
+ if (!loadedFaker) {
12
+ const req = createRequire(import.meta.url)
13
+ const mod = req('@faker-js/faker/locale/en') as { faker: Faker }
14
+ loadedFaker = mod.faker
15
+ }
16
+ return loadedFaker
17
+ }
18
+
19
+ /**
20
+ * Lazy proxy for the default English Faker instance.
21
+ * Importing `plantr` does not pay the faker load cost until a property is accessed.
22
+ */
23
+ export const lazyFaker: Faker = new Proxy({} as Faker, {
24
+ get(_target, prop) {
25
+ const instance = getDefaultFaker()
26
+ const value = Reflect.get(instance, prop, instance)
27
+ return typeof value === 'function' && prop !== 'constructor' ? value.bind(instance) : value
28
+ },
29
+ set(_target, prop, value) {
30
+ const instance = getDefaultFaker()
31
+ return Reflect.set(instance, prop, value, instance)
32
+ },
33
+ has(_target, prop) {
34
+ return Reflect.has(getDefaultFaker(), prop)
35
+ },
36
+ ownKeys() {
37
+ return Reflect.ownKeys(getDefaultFaker())
38
+ },
39
+ getOwnPropertyDescriptor(_target, prop) {
40
+ const desc = Reflect.getOwnPropertyDescriptor(getDefaultFaker(), prop)
41
+ return desc ? { ...desc, configurable: true } : undefined
42
+ },
43
+ getPrototypeOf() {
44
+ return Reflect.getPrototypeOf(getDefaultFaker())
45
+ },
46
+ })