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