plantr 1.0.1 → 2.0.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/LICENSE +21 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +365 -193
- package/dist/src/cli.d.ts +13 -0
- package/dist/src/create-seeder-instance.d.ts +29 -16
- package/dist/src/dependency-resolver.d.ts +16 -1
- package/dist/src/formatting.d.ts +7 -2
- package/dist/src/run-seeders.d.ts +28 -5
- package/dist/src/seeding-state.d.ts +5 -1
- package/dist/src/step.d.ts +27 -2
- package/dist/src/types.d.ts +20 -0
- package/dist/state.d.ts +11 -0
- package/dist/state.js +12 -0
- package/index.ts +6 -3
- package/package.json +19 -10
- package/readme.md +105 -26
- package/src/cli.ts +118 -0
- package/src/create-seeder-instance.ts +77 -111
- package/src/dependency-resolver.ts +42 -2
- package/src/formatting.ts +30 -12
- package/src/run-seeders.ts +172 -103
- package/src/seeding-state.ts +9 -4
- package/src/step.ts +73 -16
- package/src/types.ts +20 -0
- package/state.ts +11 -0
- package/dist/cli.d.ts +0 -17
- package/dist/cli.js +0 -59
- package/dist/index-a1s5r901.js +0 -4
package/src/run-seeders.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { resolveDependencyOrder } from './dependency-resolver'
|
|
1
|
+
import { resolveDependencyOrder, UnknownSeederError } from './dependency-resolver'
|
|
2
2
|
import {
|
|
3
3
|
printErrors,
|
|
4
4
|
printResultsTable,
|
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
printStartBanner,
|
|
9
9
|
printSummary,
|
|
10
10
|
} from './formatting'
|
|
11
|
+
import type { StepRecord } from './step'
|
|
11
12
|
import type { RunSeedersOptions, SeederAny, SeederResult } from './types'
|
|
12
13
|
|
|
13
14
|
/**
|
|
@@ -15,16 +16,72 @@ import type { RunSeedersOptions, SeederAny, SeederResult } from './types'
|
|
|
15
16
|
* This is created by createSeederInstance and includes the wrapped context factory.
|
|
16
17
|
*/
|
|
17
18
|
export type InternalSeederConfig<TContext> = {
|
|
18
|
-
/** Factory function that creates the full context
|
|
19
|
+
/** Factory function that creates the full context; called once, after onBeforeAll */
|
|
19
20
|
context: () => TContext | Promise<TContext>
|
|
20
|
-
/** Called before each seeder
|
|
21
|
-
|
|
22
|
-
/**
|
|
21
|
+
/** Called before each seeder runs (cache scoping); may return the record its steps fill */
|
|
22
|
+
beforeSeeder?: (name: string, options: { fresh: boolean }) => StepRecord | undefined
|
|
23
|
+
/** Database URL the run writes to; non-local hosts are refused unless allowRemote */
|
|
24
|
+
target?: () => string | undefined
|
|
25
|
+
/** Called before the context is created */
|
|
23
26
|
onBeforeAll?: () => void | Promise<void>
|
|
24
|
-
/** Called after all seeders complete */
|
|
27
|
+
/** Called after all seeders complete, also when a seeder or the context factory throws */
|
|
25
28
|
onAfterAll?: () => void | Promise<void>
|
|
26
29
|
}
|
|
27
30
|
|
|
31
|
+
/**
|
|
32
|
+
* Error thrown when a run would write to a database that is not local
|
|
33
|
+
*/
|
|
34
|
+
export class SeedTargetError extends Error {
|
|
35
|
+
constructor(label: string) {
|
|
36
|
+
super(
|
|
37
|
+
`Refusing to seed ${label}: it is not a local database. Pass allowRemote (CLI: --allow-remote) to seed it on purpose.`,
|
|
38
|
+
)
|
|
39
|
+
this.name = 'SeedTargetError'
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const isLocalHost = (hostPort: string): boolean => {
|
|
44
|
+
if (hostPort.startsWith('/')) return true // socket directory
|
|
45
|
+
const lower = hostPort.toLowerCase()
|
|
46
|
+
const bracketed = /^\[([^\]]*)\]/.exec(lower)
|
|
47
|
+
const host = bracketed ? (bracketed[1] ?? '') : lower.replace(/:\d+$/, '')
|
|
48
|
+
return (
|
|
49
|
+
host === '::1' ||
|
|
50
|
+
host === '0.0.0.0' ||
|
|
51
|
+
host === 'host.docker.internal' ||
|
|
52
|
+
host.endsWith('.localhost') ||
|
|
53
|
+
/^127\./.test(host) ||
|
|
54
|
+
!/[.:]/.test(host)
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Describe a database URL without its credentials and say whether every host it names
|
|
60
|
+
* is local: loopback, `*.localhost`, `host.docker.internal`, a socket or `file:` path,
|
|
61
|
+
* or a name without a dot (a compose service). A `host=` parameter overrides the
|
|
62
|
+
* URL's host, as libpq does. Hand-parsed so driver formats `URL` rejects still work
|
|
63
|
+
* (several hosts, `sqlserver://host;key=value`, sockets with credentials).
|
|
64
|
+
*/
|
|
65
|
+
export function describeTarget(target: string): { label: string; local: boolean } {
|
|
66
|
+
if (/^file:/i.test(target)) return { label: target.replace(/[?#].*$/, ''), local: true }
|
|
67
|
+
const scheme = /^[a-z][\w+.-]*:\/\//i.exec(target)
|
|
68
|
+
if (!scheme) return { label: 'a target that is not a URL', local: false }
|
|
69
|
+
|
|
70
|
+
const rest = target.slice(scheme[0].length)
|
|
71
|
+
const queryStart = rest.search(/[?#]/)
|
|
72
|
+
const beforeQuery = queryStart === -1 ? rest : rest.slice(0, queryStart)
|
|
73
|
+
const query = queryStart === -1 ? '' : rest.slice(queryStart)
|
|
74
|
+
// Drop credentials: everything up to the last @ before the query
|
|
75
|
+
const authorityAndPath = beforeQuery.slice(beforeQuery.lastIndexOf('@') + 1)
|
|
76
|
+
const [authority = '', path = ''] = authorityAndPath.split(/(?=[/;])/, 2)
|
|
77
|
+
let hosts = authority.split(',').filter(Boolean)
|
|
78
|
+
const hostParam = /[?&;]host=([^&;#]*)/i.exec(`${query}${path.startsWith(';') ? path : ''}`)?.[1]
|
|
79
|
+
if (hostParam) hosts = decodeURIComponent(hostParam).split(',').filter(Boolean)
|
|
80
|
+
|
|
81
|
+
const label = `${hosts.join(',') || 'local socket'}${path.startsWith('/') ? path : ''}`
|
|
82
|
+
return { label, local: hosts.every(isLocalHost) }
|
|
83
|
+
}
|
|
84
|
+
|
|
28
85
|
/**
|
|
29
86
|
* Core seeder runner - executes seeders in dependency order
|
|
30
87
|
*
|
|
@@ -32,6 +89,7 @@ export type InternalSeederConfig<TContext> = {
|
|
|
32
89
|
* @param config - Instance configuration (context factory, lifecycle hooks)
|
|
33
90
|
* @param options - Runner options (verbose output, etc.)
|
|
34
91
|
* @returns Object containing results and success status
|
|
92
|
+
* @throws Dependency errors, `UnknownSeederError` and `SeedTargetError`, before any hook runs
|
|
35
93
|
*/
|
|
36
94
|
export async function runSeedersCore<TContext>(
|
|
37
95
|
seeders: readonly SeederAny[],
|
|
@@ -41,34 +99,36 @@ export async function runSeedersCore<TContext>(
|
|
|
41
99
|
results: SeederResult[]
|
|
42
100
|
success: boolean
|
|
43
101
|
}> {
|
|
44
|
-
const {
|
|
102
|
+
const {
|
|
103
|
+
printResults = true,
|
|
104
|
+
verbose = true,
|
|
105
|
+
continueOnFailure = false,
|
|
106
|
+
only,
|
|
107
|
+
fresh = false,
|
|
108
|
+
allowRemote = false,
|
|
109
|
+
} = options
|
|
110
|
+
|
|
111
|
+
// Validate everything before touching the database
|
|
112
|
+
const orderedNames = resolveDependencyOrder(seeders, only)
|
|
45
113
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
114
|
+
const seederMap = new Map<string, SeederAny>()
|
|
115
|
+
for (const seeder of seeders) {
|
|
116
|
+
seederMap.set(seeder.name, seeder)
|
|
49
117
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
118
|
+
if (Array.isArray(fresh)) {
|
|
119
|
+
for (const name of fresh) {
|
|
120
|
+
if (!seederMap.has(name)) throw new UnknownSeederError(name, [...seederMap.keys()])
|
|
121
|
+
}
|
|
53
122
|
}
|
|
54
123
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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 }
|
|
124
|
+
const targetUrl = config.target?.()
|
|
125
|
+
const target = targetUrl ? describeTarget(targetUrl) : undefined
|
|
126
|
+
if (target && !target.local && !allowRemote) {
|
|
127
|
+
throw new SeedTargetError(target.label)
|
|
66
128
|
}
|
|
67
129
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
for (const seeder of seeders) {
|
|
71
|
-
seederMap.set(seeder.name, seeder)
|
|
130
|
+
if (verbose) {
|
|
131
|
+
printStartBanner(target)
|
|
72
132
|
}
|
|
73
133
|
|
|
74
134
|
// Initialize results
|
|
@@ -83,98 +143,107 @@ export async function runSeedersCore<TContext>(
|
|
|
83
143
|
// Track failed seeders to skip their dependents
|
|
84
144
|
const failedSeeders = new Set<string>()
|
|
85
145
|
|
|
86
|
-
|
|
87
|
-
|
|
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
|
|
146
|
+
if (config.onBeforeAll) {
|
|
147
|
+
await config.onBeforeAll()
|
|
148
|
+
}
|
|
99
149
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
150
|
+
try {
|
|
151
|
+
// Create context once for all seeders
|
|
152
|
+
const ctx = await config.context()
|
|
153
|
+
|
|
154
|
+
// Execute seeders in order
|
|
155
|
+
for (let i = 0; i < orderedNames.length; i++) {
|
|
156
|
+
const name = orderedNames[i]
|
|
157
|
+
const result = results[i]
|
|
158
|
+
|
|
159
|
+
// TypeScript safety - should never happen since we iterate within bounds
|
|
160
|
+
if (!name || !result) continue
|
|
161
|
+
|
|
162
|
+
const seeder = seederMap.get(name)
|
|
163
|
+
if (!seeder) continue
|
|
164
|
+
|
|
165
|
+
// Check if any dependencies have failed (only relevant when continueOnFailure is true)
|
|
166
|
+
if (continueOnFailure) {
|
|
167
|
+
const hasFailedDep = seeder.dependsOn.some((dep) => failedSeeders.has(dep))
|
|
168
|
+
if (hasFailedDep) {
|
|
169
|
+
result.status = 'skipped'
|
|
170
|
+
failedSeeders.add(name) // Treat skipped as failed for dependency chain
|
|
171
|
+
if (verbose) {
|
|
172
|
+
printSeederHeader(name, i, orderedNames.length, seeder.description)
|
|
173
|
+
printSeederSkipped(seeder.dependsOn.filter((d) => failedSeeders.has(d)))
|
|
174
|
+
}
|
|
175
|
+
continue
|
|
109
176
|
}
|
|
110
|
-
continue
|
|
111
177
|
}
|
|
112
|
-
}
|
|
113
178
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
179
|
+
// Print seeder header
|
|
180
|
+
if (verbose) {
|
|
181
|
+
printSeederHeader(name, i, orderedNames.length, seeder.description)
|
|
182
|
+
}
|
|
118
183
|
|
|
119
|
-
|
|
120
|
-
|
|
184
|
+
// Update status to running
|
|
185
|
+
result.status = 'running'
|
|
121
186
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
}
|
|
187
|
+
const record = config.beforeSeeder?.(name, {
|
|
188
|
+
fresh: fresh === true || (Array.isArray(fresh) && fresh.includes(name)),
|
|
189
|
+
})
|
|
126
190
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
191
|
+
// Build dependency outputs for this seeder
|
|
192
|
+
const deps: Record<string, unknown> = {}
|
|
193
|
+
for (const depName of seeder.dependsOn) {
|
|
194
|
+
deps[depName] = outputs[depName]
|
|
195
|
+
}
|
|
132
196
|
|
|
133
|
-
|
|
197
|
+
const startTime = Date.now()
|
|
134
198
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
199
|
+
try {
|
|
200
|
+
// Run the seeder
|
|
201
|
+
const output = await seeder.run(ctx, deps)
|
|
138
202
|
|
|
139
|
-
|
|
140
|
-
|
|
203
|
+
// Store output for dependents
|
|
204
|
+
outputs[name] = output
|
|
141
205
|
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
206
|
+
// Update result
|
|
207
|
+
result.status = 'completed'
|
|
208
|
+
result.durationMs = Date.now() - startTime
|
|
209
|
+
result.output = output
|
|
210
|
+
if (record) result.cachedSteps = record.cachedSteps
|
|
146
211
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
212
|
+
if (verbose) {
|
|
213
|
+
printSeederComplete(result.durationMs, true)
|
|
214
|
+
}
|
|
215
|
+
} catch (error) {
|
|
216
|
+
// Update result with error
|
|
217
|
+
result.status = 'failed'
|
|
218
|
+
result.durationMs = Date.now() - startTime
|
|
219
|
+
result.error = error instanceof Error ? error : new Error(String(error))
|
|
220
|
+
if (record) {
|
|
221
|
+
result.cachedSteps = record.cachedSteps
|
|
222
|
+
if (record.failed && record.failed.error === error) result.failedStep = record.failed.step
|
|
223
|
+
}
|
|
224
|
+
failedSeeders.add(name)
|
|
156
225
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
226
|
+
if (verbose) {
|
|
227
|
+
printSeederComplete(result.durationMs, false)
|
|
228
|
+
}
|
|
160
229
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
230
|
+
// Stop execution on failure unless continueOnFailure is true
|
|
231
|
+
if (!continueOnFailure) {
|
|
232
|
+
break
|
|
233
|
+
}
|
|
164
234
|
}
|
|
165
235
|
}
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
// Print results table
|
|
169
|
-
if (printResults) {
|
|
170
|
-
printResultsTable(results)
|
|
171
|
-
printErrors(results)
|
|
172
|
-
printSummary(results)
|
|
173
|
-
}
|
|
174
236
|
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
237
|
+
// Print results table
|
|
238
|
+
if (printResults) {
|
|
239
|
+
printResultsTable(results)
|
|
240
|
+
printErrors(results)
|
|
241
|
+
printSummary(results)
|
|
242
|
+
}
|
|
243
|
+
} finally {
|
|
244
|
+
if (config.onAfterAll) {
|
|
245
|
+
await config.onAfterAll()
|
|
246
|
+
}
|
|
178
247
|
}
|
|
179
248
|
|
|
180
249
|
const failed = results.filter((r) => r.status === 'failed').length
|
package/src/seeding-state.ts
CHANGED
|
@@ -6,21 +6,26 @@
|
|
|
6
6
|
* - Sending notifications (email, Slack, push)
|
|
7
7
|
* - Creating background jobs
|
|
8
8
|
* - Syncing to external services
|
|
9
|
+
*
|
|
10
|
+
* The flag lives on `globalThis`, so `plantr` and `plantr/state` share it even when
|
|
11
|
+
* they are loaded as separate bundles. It is one flag per process, shared by every
|
|
12
|
+
* seeder instance.
|
|
9
13
|
*/
|
|
10
14
|
|
|
11
|
-
|
|
15
|
+
const key = Symbol.for('plantr.seedingActive')
|
|
16
|
+
const state = globalThis as { [key]?: boolean }
|
|
12
17
|
|
|
13
18
|
/**
|
|
14
19
|
* Check if seeding is currently active
|
|
15
20
|
*/
|
|
16
21
|
export function isSeedingActive(): boolean {
|
|
17
|
-
return
|
|
22
|
+
return state[key] === true
|
|
18
23
|
}
|
|
19
24
|
|
|
20
25
|
/**
|
|
21
26
|
* Set the seeding state.
|
|
22
|
-
* Called automatically by
|
|
27
|
+
* Called automatically by `runSeeders` around a run.
|
|
23
28
|
*/
|
|
24
29
|
export function setSeedingActive(active: boolean): void {
|
|
25
|
-
|
|
30
|
+
state[key] = active
|
|
26
31
|
}
|
package/src/step.ts
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
|
-
import { colorize } from './formatting'
|
|
1
|
+
import { colorize, formatDuration } from './formatting'
|
|
2
2
|
|
|
3
3
|
export type StepOptions = {
|
|
4
4
|
/** Enable caching for this step */
|
|
5
5
|
useCache?: boolean
|
|
6
|
+
/**
|
|
7
|
+
* Any JSON value describing what the step's output depends on (a number you bump,
|
|
8
|
+
* the data the step writes). A cached entry stored with a different version is a
|
|
9
|
+
* miss: the step runs again and its entry is overwritten.
|
|
10
|
+
*/
|
|
11
|
+
version?: unknown
|
|
6
12
|
}
|
|
7
13
|
|
|
8
14
|
export type StepFn = <T>(
|
|
@@ -14,6 +20,8 @@ export type StepFn = <T>(
|
|
|
14
20
|
/**
|
|
15
21
|
* Cache interface for step caching.
|
|
16
22
|
* Provide get/set functions to enable caching in the step runner.
|
|
23
|
+
* plantr stores an envelope object (`{ __plantr: 1, version?, value }`), so `set`
|
|
24
|
+
* always receives an object and `get` should return it as stored.
|
|
17
25
|
*/
|
|
18
26
|
export type SeederCache = {
|
|
19
27
|
/** Get a cached value by key. Returns undefined if not found. */
|
|
@@ -22,26 +30,54 @@ export type SeederCache = {
|
|
|
22
30
|
set: <T>(key: string, value: T) => Promise<void>
|
|
23
31
|
}
|
|
24
32
|
|
|
33
|
+
/** What the steps of the current seeder did, for error reporting */
|
|
34
|
+
export type StepRecord = {
|
|
35
|
+
/** Descriptions of the steps whose output came from the cache */
|
|
36
|
+
cachedSteps: string[]
|
|
37
|
+
/** Description and error of the last step that threw */
|
|
38
|
+
failed?: { step: string; error: unknown }
|
|
39
|
+
}
|
|
40
|
+
|
|
25
41
|
type StepRunnerConfig = {
|
|
26
42
|
cache?: SeederCache
|
|
27
43
|
/** Seeder name for scoping cache keys */
|
|
28
44
|
seederName?: string
|
|
45
|
+
/** Print a line per step (default: true) */
|
|
46
|
+
log?: boolean
|
|
29
47
|
}
|
|
30
48
|
|
|
49
|
+
type CacheEntry = { __plantr: 1; version?: string; value?: unknown }
|
|
50
|
+
|
|
51
|
+
const isCacheEntry = (stored: unknown): stored is CacheEntry =>
|
|
52
|
+
typeof stored === 'object' && stored !== null && (stored as CacheEntry).__plantr === 1
|
|
53
|
+
|
|
31
54
|
/**
|
|
32
55
|
* Create a step runner for organizing seeder workflow.
|
|
33
56
|
* Optionally provide a cache for step caching support.
|
|
34
57
|
*/
|
|
35
58
|
export function createStepRunner(config?: StepRunnerConfig): {
|
|
36
59
|
step: StepFn
|
|
37
|
-
/**
|
|
38
|
-
|
|
60
|
+
/**
|
|
61
|
+
* Start a seeder: scopes cache keys to its name and returns the record its steps fill.
|
|
62
|
+
* With `fresh`, its cached steps ignore stored entries and overwrite them.
|
|
63
|
+
*/
|
|
64
|
+
setSeederName: (name: string, options?: { fresh?: boolean }) => StepRecord
|
|
39
65
|
} {
|
|
40
|
-
const { cache } = config ?? {}
|
|
66
|
+
const { cache, log = true } = config ?? {}
|
|
41
67
|
let currentSeederName = config?.seederName ?? ''
|
|
68
|
+
let fresh = false
|
|
69
|
+
let record: StepRecord = { cachedSteps: [] }
|
|
70
|
+
const usedKeys = new Set<string>()
|
|
42
71
|
|
|
43
|
-
const setSeederName = (name: string):
|
|
72
|
+
const setSeederName = (name: string, options?: { fresh?: boolean }): StepRecord => {
|
|
44
73
|
currentSeederName = name
|
|
74
|
+
fresh = options?.fresh ?? false
|
|
75
|
+
record = { cachedSteps: [] }
|
|
76
|
+
return record
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const print = (line: string) => {
|
|
80
|
+
if (log) console.log(line)
|
|
45
81
|
}
|
|
46
82
|
|
|
47
83
|
const step: StepFn = async <T>(
|
|
@@ -59,37 +95,58 @@ export function createStepRunner(config?: StepRunnerConfig): {
|
|
|
59
95
|
const cacheKey = currentSeederName
|
|
60
96
|
? `${currentSeederName}:${slugifiedDescription}`
|
|
61
97
|
: slugifiedDescription
|
|
98
|
+
const startTime = Date.now()
|
|
62
99
|
|
|
63
100
|
try {
|
|
64
101
|
let result: T
|
|
65
102
|
let wasCached = false
|
|
66
103
|
|
|
67
104
|
if (useCache && cache) {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
105
|
+
if (usedKeys.has(cacheKey)) {
|
|
106
|
+
throw new Error(
|
|
107
|
+
`Step "${description}" uses cache key "${cacheKey}", which another cached step in this run already used. Give each cached step a unique description.`,
|
|
108
|
+
)
|
|
109
|
+
}
|
|
110
|
+
usedKeys.add(cacheKey)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (useCache && cache) {
|
|
114
|
+
const version = options?.version === undefined ? undefined : JSON.stringify(options.version)
|
|
115
|
+
const stored = fresh ? undefined : await cache.get<unknown>(cacheKey)
|
|
116
|
+
if (isCacheEntry(stored) && stored.version === version) {
|
|
117
|
+
result = stored.value as T
|
|
118
|
+
wasCached = true
|
|
119
|
+
} else if (stored !== undefined && !isCacheEntry(stored) && version === undefined) {
|
|
120
|
+
// Written by plantr 1.x, which stored the value bare
|
|
121
|
+
result = stored as T
|
|
72
122
|
wasCached = true
|
|
73
123
|
} else {
|
|
74
|
-
// Execute and cache
|
|
75
124
|
result = await fn()
|
|
76
|
-
|
|
125
|
+
const entry: CacheEntry =
|
|
126
|
+
version === undefined
|
|
127
|
+
? { __plantr: 1, value: result }
|
|
128
|
+
: { __plantr: 1, version, value: result }
|
|
129
|
+
await cache.set(cacheKey, entry)
|
|
77
130
|
}
|
|
78
131
|
} else if (useCache && !cache) {
|
|
79
132
|
// Warn if caching requested but no cache configured
|
|
80
|
-
|
|
133
|
+
print(colorize(` ⚠ Cache not configured, running without cache`, 'yellow'))
|
|
81
134
|
result = await fn()
|
|
82
135
|
} else {
|
|
83
136
|
result = await fn()
|
|
84
137
|
}
|
|
85
138
|
|
|
86
|
-
|
|
87
|
-
|
|
139
|
+
if (wasCached) record.cachedSteps.push(description)
|
|
140
|
+
const suffix = wasCached
|
|
141
|
+
? ` ${colorize('(cached)', 'cyan')}`
|
|
142
|
+
: ` ${colorize(formatDuration(Date.now() - startTime), 'dim')}`
|
|
143
|
+
print(` ${colorize('✓', 'green')} ${description}${suffix}`)
|
|
88
144
|
return result
|
|
89
145
|
} catch (error) {
|
|
90
|
-
|
|
146
|
+
record.failed = { step: description, error }
|
|
147
|
+
print(` ${colorize('✗', 'red')} ${description}`)
|
|
91
148
|
if (error instanceof Error) {
|
|
92
|
-
|
|
149
|
+
print(` ${colorize(error.message, 'dim')}`)
|
|
93
150
|
}
|
|
94
151
|
throw error
|
|
95
152
|
}
|
package/src/types.ts
CHANGED
|
@@ -82,6 +82,10 @@ export type SeederResult = {
|
|
|
82
82
|
durationMs?: number
|
|
83
83
|
output?: unknown
|
|
84
84
|
error?: Error
|
|
85
|
+
/** Description of the step that threw, when the seeder failed in a step */
|
|
86
|
+
failedStep?: string
|
|
87
|
+
/** Descriptions of the steps whose output came from the cache */
|
|
88
|
+
cachedSteps?: string[]
|
|
85
89
|
}
|
|
86
90
|
|
|
87
91
|
/** Options for the seeder runner */
|
|
@@ -96,4 +100,20 @@ export type RunSeedersOptions = {
|
|
|
96
100
|
* but independent seeders will still run.
|
|
97
101
|
*/
|
|
98
102
|
continueOnFailure?: boolean
|
|
103
|
+
/**
|
|
104
|
+
* Run only these seeders and everything they depend on, in dependency order.
|
|
105
|
+
* Throws `UnknownSeederError` for a name that is not registered.
|
|
106
|
+
*/
|
|
107
|
+
only?: readonly string[]
|
|
108
|
+
/**
|
|
109
|
+
* Ignore cached step entries and overwrite them: `true` for every seeder,
|
|
110
|
+
* or the names of the seeders to run fresh. Dependencies of those seeders still
|
|
111
|
+
* replay their cache unless they are named too.
|
|
112
|
+
*/
|
|
113
|
+
fresh?: boolean | readonly string[]
|
|
114
|
+
/**
|
|
115
|
+
* Seed a target that is not local (see `target` on the instance config).
|
|
116
|
+
* Without it, a non-local target throws `SeedTargetError` before anything runs.
|
|
117
|
+
*/
|
|
118
|
+
allowRemote?: boolean
|
|
99
119
|
}
|
package/state.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime entry point: reads the seeding flag without loading faker or bun:test.
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* ```typescript
|
|
6
|
+
* import { isSeedingActive } from 'plantr/state'
|
|
7
|
+
*
|
|
8
|
+
* if (isSeedingActive()) return // skip jobs and mail while seeding
|
|
9
|
+
* ```
|
|
10
|
+
*/
|
|
11
|
+
export { isSeedingActive } from './src/seeding-state'
|
package/dist/cli.d.ts
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env bun
|
|
2
|
-
/**
|
|
3
|
-
* Seeder CLI
|
|
4
|
-
*
|
|
5
|
-
* This is a thin CLI wrapper. Consumers should create their own entry point
|
|
6
|
-
* that imports their seeders and calls runSeeders.
|
|
7
|
-
*
|
|
8
|
-
* Usage:
|
|
9
|
-
* bun run ./path/to/seed-config.ts [options]
|
|
10
|
-
*
|
|
11
|
-
* The config file should export:
|
|
12
|
-
* - default: { seeders, context, cache? }
|
|
13
|
-
*
|
|
14
|
-
* Or simply use the config file as the entry point:
|
|
15
|
-
* bun run apps/backend/src/registries/seed.ts
|
|
16
|
-
*/
|
|
17
|
-
export {};
|
package/dist/cli.js
DELETED
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env bun
|
|
2
|
-
import {
|
|
3
|
-
__require
|
|
4
|
-
} from "./index-a1s5r901.js";
|
|
5
|
-
|
|
6
|
-
// cli.ts
|
|
7
|
-
var args = process.argv.slice(2);
|
|
8
|
-
if (args.includes("--help") || args.includes("-h")) {
|
|
9
|
-
console.log(`
|
|
10
|
-
plantr CLI
|
|
11
|
-
|
|
12
|
-
Usage:
|
|
13
|
-
bunx plantr --config <path> Run seeders from a config file
|
|
14
|
-
bunx plantr --help Show this help message
|
|
15
|
-
|
|
16
|
-
Config file should export:
|
|
17
|
-
export default {
|
|
18
|
-
seeders: [...],
|
|
19
|
-
context: (base) => ({ ...base, prisma }),
|
|
20
|
-
cache?: {
|
|
21
|
-
get: async (key) => { ... },
|
|
22
|
-
set: async (key, value) => { ... },
|
|
23
|
-
},
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
Alternatively, create your own entry point:
|
|
27
|
-
// seed.ts
|
|
28
|
-
import { createSeederInstance } from 'plantr'
|
|
29
|
-
|
|
30
|
-
const { runSeeders } = createSeederInstance({ ... })
|
|
31
|
-
|
|
32
|
-
if (import.meta.main) {
|
|
33
|
-
await runSeeders([...seeders])
|
|
34
|
-
}
|
|
35
|
-
`);
|
|
36
|
-
process.exit(0);
|
|
37
|
-
}
|
|
38
|
-
var configIndex = args.indexOf("--config");
|
|
39
|
-
if (configIndex === -1 || !args[configIndex + 1]) {
|
|
40
|
-
console.error("Error: --config <path> is required");
|
|
41
|
-
console.error("Run with --help for usage information");
|
|
42
|
-
process.exit(1);
|
|
43
|
-
}
|
|
44
|
-
var configPath = args[configIndex + 1];
|
|
45
|
-
try {
|
|
46
|
-
const config = await import(configPath);
|
|
47
|
-
const { seeders, context, cache } = config.default || config;
|
|
48
|
-
if (!seeders || !context) {
|
|
49
|
-
console.error("Error: Config must export { seeders, context }");
|
|
50
|
-
process.exit(1);
|
|
51
|
-
}
|
|
52
|
-
const { createSeederInstance } = await import("./index.js");
|
|
53
|
-
const { runSeeders } = createSeederInstance({ context, cache });
|
|
54
|
-
const { success } = await runSeeders(seeders);
|
|
55
|
-
process.exit(success ? 0 : 1);
|
|
56
|
-
} catch (error) {
|
|
57
|
-
console.error("Error loading config:", error);
|
|
58
|
-
process.exit(1);
|
|
59
|
-
}
|
package/dist/index-a1s5r901.js
DELETED