plantr 1.0.1 → 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.
- package/LICENSE +21 -0
- package/dist/index.d.ts +23 -20
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +906 -235
- package/dist/src/cli.d.ts +23 -0
- package/dist/src/cli.d.ts.map +1 -0
- package/dist/src/create-seeder-instance.d.ts +73 -83
- package/dist/src/create-seeder-instance.d.ts.map +1 -0
- package/dist/src/define-seeder.d.ts +4 -3
- package/dist/src/define-seeder.d.ts.map +1 -0
- package/dist/src/dependency-resolver.d.ts +18 -2
- package/dist/src/dependency-resolver.d.ts.map +1 -0
- package/dist/src/formatting.d.ts +31 -12
- package/dist/src/formatting.d.ts.map +1 -0
- package/dist/src/lazy-faker.d.ts +12 -0
- package/dist/src/lazy-faker.d.ts.map +1 -0
- package/dist/src/run-seeders.d.ts +57 -17
- package/dist/src/run-seeders.d.ts.map +1 -0
- package/dist/src/seeding-state.d.ts +17 -2
- package/dist/src/seeding-state.d.ts.map +1 -0
- package/dist/src/step.d.ts +97 -15
- package/dist/src/step.d.ts.map +1 -0
- package/dist/src/types.d.ts +132 -29
- package/dist/src/types.d.ts.map +1 -0
- package/dist/state.d.ts +12 -0
- package/dist/state.d.ts.map +1 -0
- package/dist/state.js +20 -0
- package/index.ts +60 -24
- package/package.json +20 -10
- package/readme.md +169 -49
- package/src/cli.ts +251 -0
- package/src/create-seeder-instance.ts +254 -173
- package/src/define-seeder.ts +14 -7
- package/src/dependency-resolver.ts +59 -30
- package/src/formatting.ts +142 -39
- package/src/lazy-faker.ts +46 -0
- package/src/run-seeders.ts +413 -123
- package/src/seeding-state.ts +32 -5
- package/src/step.ts +247 -46
- package/src/types.ts +184 -32
- 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/step.ts
CHANGED
|
@@ -1,99 +1,300 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import { colorize, formatDuration } from './formatting.js'
|
|
3
|
+
import type { JsonValue, MaybePromise } from './types.js'
|
|
2
4
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
5
|
+
/** Envelope written to `SeederCache.set` / `SeederCache.setMany` by plantr */
|
|
6
|
+
export type CacheEntry = {
|
|
7
|
+
readonly __plantr: 1
|
|
8
|
+
readonly version?: string
|
|
9
|
+
readonly value?: unknown
|
|
6
10
|
}
|
|
7
11
|
|
|
12
|
+
/** Single entry passed to `SeederCache.setMany` */
|
|
13
|
+
export type CacheWrite = {
|
|
14
|
+
readonly key: string
|
|
15
|
+
readonly value: CacheEntry
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type StepOptions =
|
|
19
|
+
| {
|
|
20
|
+
/** Enable caching for this step */
|
|
21
|
+
useCache?: false | undefined
|
|
22
|
+
version?: never
|
|
23
|
+
key?: never
|
|
24
|
+
}
|
|
25
|
+
| {
|
|
26
|
+
/** Enable caching for this step */
|
|
27
|
+
useCache: true
|
|
28
|
+
/**
|
|
29
|
+
* Optional explicit cache key (scoped to the seeder name).
|
|
30
|
+
* Defaults to a slugified version of the step description.
|
|
31
|
+
* Use this when you want to reword a description without busting the cache,
|
|
32
|
+
* or when the description contains non-ASCII characters.
|
|
33
|
+
*/
|
|
34
|
+
key?: string | undefined
|
|
35
|
+
/**
|
|
36
|
+
* Any JSON value describing what the step's output depends on (a number you bump,
|
|
37
|
+
* the data the step writes). A cached entry stored with a different version is a
|
|
38
|
+
* miss: the step runs again and its entry is overwritten. Object keys are compared
|
|
39
|
+
* deterministically regardless of insertion order.
|
|
40
|
+
*/
|
|
41
|
+
version?: JsonValue | undefined
|
|
42
|
+
}
|
|
43
|
+
|
|
8
44
|
export type StepFn = <T>(
|
|
9
45
|
description: string,
|
|
10
|
-
fn: () =>
|
|
46
|
+
fn: () => MaybePromise<T>,
|
|
11
47
|
options?: StepOptions,
|
|
12
48
|
) => Promise<T>
|
|
13
49
|
|
|
14
50
|
/**
|
|
15
51
|
* Cache interface for step caching.
|
|
16
|
-
* Provide get/set functions to enable caching in the step runner.
|
|
52
|
+
* Provide `get` / `set` functions to enable caching in the step runner.
|
|
53
|
+
* plantr stores an envelope object (`{ __plantr: 1, version?, value }`), so `set`
|
|
54
|
+
* always receives a `CacheEntry` and `get` should return it as stored (or `undefined`/`null` on miss).
|
|
55
|
+
*
|
|
56
|
+
* Optionally provide `getAll` to preload all entries in one query at the start of a run,
|
|
57
|
+
* and `setMany` to flush new/updated entries in one batch write at the end of a run.
|
|
17
58
|
*/
|
|
18
59
|
export type SeederCache = {
|
|
19
|
-
/** Get a cached value by key.
|
|
20
|
-
get:
|
|
60
|
+
/** Get a cached value by key. Return undefined or null if not found. */
|
|
61
|
+
get: (key: string) => MaybePromise<unknown>
|
|
21
62
|
/** Set a cached value by key. */
|
|
22
|
-
set:
|
|
63
|
+
set: (key: string, value: CacheEntry) => MaybePromise<void>
|
|
64
|
+
/**
|
|
65
|
+
* Optional: load all cached entries once at the start of a run to avoid N+1 `get` queries.
|
|
66
|
+
*/
|
|
67
|
+
getAll?: (() => MaybePromise<Map<string, unknown> | Record<string, unknown>>) | undefined
|
|
68
|
+
/**
|
|
69
|
+
* Optional: write all new/updated cache entries in a single batch at the end of a run
|
|
70
|
+
* (before `onAfterAll`), removing per-step write round-trips from the critical path.
|
|
71
|
+
*/
|
|
72
|
+
setMany?: ((entries: readonly CacheWrite[]) => MaybePromise<void>) | undefined
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** What the steps of the current seeder did, for error reporting */
|
|
76
|
+
export type StepRecord = {
|
|
77
|
+
/** Descriptions of the steps whose output came from the cache */
|
|
78
|
+
cachedSteps: string[]
|
|
79
|
+
/** Description and error of the innermost step that threw */
|
|
80
|
+
failed?: { step: string; error: unknown }
|
|
23
81
|
}
|
|
24
82
|
|
|
25
|
-
|
|
26
|
-
|
|
83
|
+
/** Isolated execution scope for a single seeder's steps (concurrency-safe) */
|
|
84
|
+
export type StepScope = {
|
|
85
|
+
seederName: string
|
|
86
|
+
fresh: boolean
|
|
87
|
+
record: StepRecord
|
|
88
|
+
prefix?: string | undefined
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export type StepRunnerConfig = {
|
|
92
|
+
cache?: SeederCache | undefined
|
|
27
93
|
/** Seeder name for scoping cache keys */
|
|
28
|
-
seederName?: string
|
|
94
|
+
seederName?: string | undefined
|
|
95
|
+
/** Print a line per step (default: true) */
|
|
96
|
+
log?: boolean | undefined
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export type StepRunner = {
|
|
100
|
+
step: StepFn
|
|
101
|
+
/**
|
|
102
|
+
* Start a seeder in sequential mode: scopes cache keys to its name and returns the
|
|
103
|
+
* record its steps fill. With `fresh`, its cached steps ignore stored entries and overwrite them.
|
|
104
|
+
*/
|
|
105
|
+
setSeederName: (name: string, options?: { fresh?: boolean }) => StepRecord
|
|
106
|
+
/** Create an isolated scope for running one seeder concurrently */
|
|
107
|
+
createScope: (options: { seederName: string; fresh?: boolean; prefix?: string }) => StepScope
|
|
108
|
+
/** Run an async callback with `scope` bound via AsyncLocalStorage */
|
|
109
|
+
runWithScope: <T>(scope: StepScope, fn: () => Promise<T>) => Promise<T>
|
|
110
|
+
/** Preload cache entries via `cache.getAll()` if configured */
|
|
111
|
+
preload: () => Promise<void>
|
|
112
|
+
/** Flush buffered cache writes via `cache.setMany()` if configured */
|
|
113
|
+
flush: () => Promise<void>
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const isCacheEntry = (stored: unknown): stored is CacheEntry =>
|
|
117
|
+
typeof stored === 'object' && stored !== null && (stored as CacheEntry).__plantr === 1
|
|
118
|
+
|
|
119
|
+
const slugify = (description: string): string =>
|
|
120
|
+
description
|
|
121
|
+
.toLowerCase()
|
|
122
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
123
|
+
.replace(/^-|-$/g, '')
|
|
124
|
+
|
|
125
|
+
/** Canonical JSON stringify with sorted object keys so version comparisons are order-independent */
|
|
126
|
+
function canonicalStringify(value: unknown): string {
|
|
127
|
+
if (value === null || typeof value !== 'object') {
|
|
128
|
+
return JSON.stringify(value)
|
|
129
|
+
}
|
|
130
|
+
if (Array.isArray(value)) {
|
|
131
|
+
return `[${value.map((item) => (item === undefined ? 'null' : canonicalStringify(item))).join(',')}]`
|
|
132
|
+
}
|
|
133
|
+
if (typeof (value as { toJSON?: unknown }).toJSON === 'function') {
|
|
134
|
+
return canonicalStringify((value as { toJSON: () => unknown }).toJSON())
|
|
135
|
+
}
|
|
136
|
+
const obj = value as Record<string, unknown>
|
|
137
|
+
const keys = Object.keys(obj).sort()
|
|
138
|
+
const parts: string[] = []
|
|
139
|
+
for (const key of keys) {
|
|
140
|
+
const entryValue = obj[key]
|
|
141
|
+
if (entryValue !== undefined) {
|
|
142
|
+
parts.push(`${JSON.stringify(key)}:${canonicalStringify(entryValue)}`)
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return `{${parts.join(',')}}`
|
|
29
146
|
}
|
|
30
147
|
|
|
31
148
|
/**
|
|
32
149
|
* Create a step runner for organizing seeder workflow.
|
|
33
150
|
* Optionally provide a cache for step caching support.
|
|
34
151
|
*/
|
|
35
|
-
export function createStepRunner(config?: StepRunnerConfig): {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
const setSeederName = (name: string): void => {
|
|
44
|
-
currentSeederName = name
|
|
152
|
+
export function createStepRunner(config?: StepRunnerConfig): StepRunner {
|
|
153
|
+
const { cache, log = true } = config ?? {}
|
|
154
|
+
const scopeStorage = new AsyncLocalStorage<StepScope>()
|
|
155
|
+
let fallbackScope: StepScope = {
|
|
156
|
+
seederName: config?.seederName ?? '',
|
|
157
|
+
fresh: false,
|
|
158
|
+
record: { cachedSteps: [] },
|
|
45
159
|
}
|
|
160
|
+
const usedKeys = new Set<string>()
|
|
161
|
+
const pendingWrites = new Map<string, CacheEntry>()
|
|
162
|
+
let preloaded: Map<string, unknown> | undefined
|
|
163
|
+
let warnedNoCache = false
|
|
164
|
+
|
|
165
|
+
const setSeederName = (name: string, options?: { fresh?: boolean }): StepRecord => {
|
|
166
|
+
const record: StepRecord = { cachedSteps: [] }
|
|
167
|
+
fallbackScope = {
|
|
168
|
+
seederName: name,
|
|
169
|
+
fresh: options?.fresh ?? false,
|
|
170
|
+
record,
|
|
171
|
+
}
|
|
172
|
+
return record
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const createScope = (options: {
|
|
176
|
+
seederName: string
|
|
177
|
+
fresh?: boolean
|
|
178
|
+
prefix?: string
|
|
179
|
+
}): StepScope => ({
|
|
180
|
+
seederName: options.seederName,
|
|
181
|
+
fresh: options.fresh ?? false,
|
|
182
|
+
record: { cachedSteps: [] },
|
|
183
|
+
prefix: options.prefix,
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
const runWithScope = <T>(scope: StepScope, fn: () => Promise<T>): Promise<T> =>
|
|
187
|
+
scopeStorage.run(scope, fn)
|
|
188
|
+
|
|
189
|
+
const preload = async (): Promise<void> => {
|
|
190
|
+
if (!cache?.getAll) return
|
|
191
|
+
const entries = await cache.getAll()
|
|
192
|
+
preloaded = entries instanceof Map ? new Map(entries) : new Map(Object.entries(entries))
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const flush = async (): Promise<void> => {
|
|
196
|
+
if (!cache?.setMany || pendingWrites.size === 0) return
|
|
197
|
+
const entries: CacheWrite[] = [...pendingWrites.entries()].map(([key, value]) => ({
|
|
198
|
+
key,
|
|
199
|
+
value,
|
|
200
|
+
}))
|
|
201
|
+
pendingWrites.clear()
|
|
202
|
+
await cache.setMany(entries)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const print = (line: string) => {
|
|
206
|
+
if (log) console.log(line)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const formatPrefix = (scope: StepScope): string =>
|
|
210
|
+
scope.prefix ? ` ${colorize(`[${scope.prefix}]`, 'cyan')} ` : ' '
|
|
46
211
|
|
|
47
212
|
const step: StepFn = async <T>(
|
|
48
213
|
description: string,
|
|
49
|
-
fn: () =>
|
|
214
|
+
fn: () => MaybePromise<T>,
|
|
50
215
|
options?: StepOptions,
|
|
51
216
|
): Promise<T> => {
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
const
|
|
56
|
-
.toLowerCase()
|
|
57
|
-
.replace(/[^a-z0-9]+/g, '-')
|
|
58
|
-
.replace(/^-|-$/g, '')
|
|
59
|
-
const cacheKey = currentSeederName
|
|
60
|
-
? `${currentSeederName}:${slugifiedDescription}`
|
|
61
|
-
: slugifiedDescription
|
|
217
|
+
const scope = scopeStorage.getStore() ?? fallbackScope
|
|
218
|
+
const useCache = options?.useCache === true
|
|
219
|
+
const startTime = performance.now()
|
|
220
|
+
const prefix = formatPrefix(scope)
|
|
62
221
|
|
|
63
222
|
try {
|
|
64
223
|
let result: T
|
|
65
224
|
let wasCached = false
|
|
66
225
|
|
|
67
226
|
if (useCache && cache) {
|
|
68
|
-
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
227
|
+
const rawKey = options.key !== undefined ? options.key : slugify(description)
|
|
228
|
+
const cacheKey = scope.seederName ? `${scope.seederName}:${rawKey}` : rawKey
|
|
229
|
+
|
|
230
|
+
if (usedKeys.has(cacheKey)) {
|
|
231
|
+
throw new Error(
|
|
232
|
+
`Step "${description}" uses cache key "${cacheKey}", which another cached step in this run already used. Give each cached step a unique description or explicit key.`,
|
|
233
|
+
)
|
|
234
|
+
}
|
|
235
|
+
usedKeys.add(cacheKey)
|
|
236
|
+
|
|
237
|
+
const version =
|
|
238
|
+
options.version === undefined ? undefined : canonicalStringify(options.version)
|
|
239
|
+
const stored = scope.fresh
|
|
240
|
+
? undefined
|
|
241
|
+
: preloaded !== undefined
|
|
242
|
+
? preloaded.get(cacheKey)
|
|
243
|
+
: await cache.get(cacheKey)
|
|
244
|
+
|
|
245
|
+
if (isCacheEntry(stored) && stored.version === version) {
|
|
246
|
+
result = stored.value as T
|
|
247
|
+
wasCached = true
|
|
248
|
+
} else if (
|
|
249
|
+
stored !== undefined &&
|
|
250
|
+
stored !== null &&
|
|
251
|
+
!isCacheEntry(stored) &&
|
|
252
|
+
version === undefined
|
|
253
|
+
) {
|
|
254
|
+
// Written by plantr 1.x, which stored the value bare
|
|
255
|
+
result = stored as T
|
|
72
256
|
wasCached = true
|
|
73
257
|
} else {
|
|
74
|
-
// Execute and cache
|
|
75
258
|
result = await fn()
|
|
76
|
-
|
|
259
|
+
const entry: CacheEntry =
|
|
260
|
+
version === undefined
|
|
261
|
+
? { __plantr: 1, value: result }
|
|
262
|
+
: { __plantr: 1, version, value: result }
|
|
263
|
+
preloaded?.set(cacheKey, entry)
|
|
264
|
+
if (cache.setMany) {
|
|
265
|
+
pendingWrites.set(cacheKey, entry)
|
|
266
|
+
} else {
|
|
267
|
+
await cache.set(cacheKey, entry)
|
|
268
|
+
}
|
|
77
269
|
}
|
|
78
270
|
} else if (useCache && !cache) {
|
|
79
|
-
|
|
80
|
-
|
|
271
|
+
if (!warnedNoCache) {
|
|
272
|
+
warnedNoCache = true
|
|
273
|
+
print(`${prefix}${colorize('⚠ Cache not configured, running without cache', 'yellow')}`)
|
|
274
|
+
}
|
|
81
275
|
result = await fn()
|
|
82
276
|
} else {
|
|
83
277
|
result = await fn()
|
|
84
278
|
}
|
|
85
279
|
|
|
86
|
-
|
|
87
|
-
|
|
280
|
+
if (wasCached) scope.record.cachedSteps.push(description)
|
|
281
|
+
const suffix = wasCached
|
|
282
|
+
? ` ${colorize('(cached)', 'cyan')}`
|
|
283
|
+
: ` ${colorize(formatDuration(performance.now() - startTime), 'dim')}`
|
|
284
|
+
print(`${prefix}${colorize('✓', 'green')} ${description}${suffix}`)
|
|
88
285
|
return result
|
|
89
286
|
} catch (error) {
|
|
90
|
-
|
|
287
|
+
// Preserve the innermost failing step if steps are nested
|
|
288
|
+
if (!scope.record.failed || scope.record.failed.error !== error) {
|
|
289
|
+
scope.record.failed = { step: description, error }
|
|
290
|
+
}
|
|
291
|
+
print(`${prefix}${colorize('✗', 'red')} ${description}`)
|
|
91
292
|
if (error instanceof Error) {
|
|
92
|
-
|
|
293
|
+
print(`${prefix} ${colorize(error.message, 'dim')}`)
|
|
93
294
|
}
|
|
94
295
|
throw error
|
|
95
296
|
}
|
|
96
297
|
}
|
|
97
298
|
|
|
98
|
-
return { step, setSeederName }
|
|
299
|
+
return { step, setSeederName, createScope, runWithScope, preload, flush }
|
|
99
300
|
}
|
package/src/types.ts
CHANGED
|
@@ -6,8 +6,23 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import type { expect } from 'bun:test'
|
|
9
|
-
import type {
|
|
10
|
-
import type { StepFn } from './step'
|
|
9
|
+
import type { Faker } from '@faker-js/faker'
|
|
10
|
+
import type { StepFn } from './step.js'
|
|
11
|
+
|
|
12
|
+
/** Flatten intersections and mapped types for cleaner IDE hover tooltips */
|
|
13
|
+
export type Prettify<T> = { [K in keyof T]: T[K] } & {}
|
|
14
|
+
|
|
15
|
+
/** A value or a Promise resolving to that value */
|
|
16
|
+
export type MaybePromise<T> = T | Promise<T>
|
|
17
|
+
|
|
18
|
+
/** JSON-serializable primitive */
|
|
19
|
+
export type JsonPrimitive = string | number | boolean | null
|
|
20
|
+
|
|
21
|
+
/** JSON-serializable value (used for step cache versions) */
|
|
22
|
+
export type JsonValue =
|
|
23
|
+
| JsonPrimitive
|
|
24
|
+
| readonly JsonValue[]
|
|
25
|
+
| { readonly [key: string]: JsonValue | undefined }
|
|
11
26
|
|
|
12
27
|
/**
|
|
13
28
|
* Base seeder context provided by the library.
|
|
@@ -16,7 +31,7 @@ import type { StepFn } from './step'
|
|
|
16
31
|
*/
|
|
17
32
|
export type BaseSeederContext = {
|
|
18
33
|
/** Faker instance for generating test data */
|
|
19
|
-
faker:
|
|
34
|
+
faker: Faker
|
|
20
35
|
/** Step function for organizing seeder workflow */
|
|
21
36
|
step: StepFn
|
|
22
37
|
/** Assertion function from bun:test for verifying data */
|
|
@@ -25,16 +40,49 @@ export type BaseSeederContext = {
|
|
|
25
40
|
|
|
26
41
|
/** Extract the output type from a Seeder */
|
|
27
42
|
// biome-ignore lint/suspicious/noExplicitAny: needs any to match any context type
|
|
28
|
-
export type SeederOutput<T> = T extends Seeder<any,
|
|
43
|
+
export type SeederOutput<T> = T extends Seeder<any, any, infer O, any> ? O : never
|
|
29
44
|
|
|
30
45
|
/** Extract the name from a Seeder */
|
|
31
46
|
// biome-ignore lint/suspicious/noExplicitAny: needs any to match any context type
|
|
32
|
-
export type SeederName<T> = T extends Seeder<any, infer N,
|
|
47
|
+
export type SeederName<T> = T extends Seeder<any, infer N, any, any> ? N : never
|
|
48
|
+
|
|
49
|
+
/** Extract the dependency names from a Seeder */
|
|
50
|
+
// biome-ignore lint/suspicious/noExplicitAny: needs any to match any context type
|
|
51
|
+
export type SeederDeps<T> = T extends Seeder<any, any, any, infer D> ? D : never
|
|
33
52
|
|
|
34
53
|
/** Build a typed deps object from an array of seeder dependencies */
|
|
35
|
-
export type DepsFromSeeders<T extends readonly SeederAny[]> = {
|
|
54
|
+
export type DepsFromSeeders<T extends readonly SeederAny[]> = Prettify<{
|
|
36
55
|
[K in T[number] as SeederName<K>]: SeederOutput<K>
|
|
37
|
-
}
|
|
56
|
+
}>
|
|
57
|
+
|
|
58
|
+
/** Map of seeder name -> output type for a collection of seeders */
|
|
59
|
+
export type SeederOutputs<TSeeders extends readonly SeederAny[]> = Prettify<{
|
|
60
|
+
[K in TSeeders[number] as SeederName<K>]: SeederOutput<K>
|
|
61
|
+
}>
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Dependency names required by seeders in `TSeeders` that are not present in `TSeeders`.
|
|
65
|
+
* Evaluates to `never` when all dependencies are present or when names are widened to `string`.
|
|
66
|
+
*/
|
|
67
|
+
export type MissingSeederDeps<TSeeders extends readonly SeederAny[]> = string extends SeederName<
|
|
68
|
+
TSeeders[number]
|
|
69
|
+
>
|
|
70
|
+
? never
|
|
71
|
+
: string extends SeederDeps<TSeeders[number]>
|
|
72
|
+
? never
|
|
73
|
+
: Exclude<SeederDeps<TSeeders[number]>, SeederName<TSeeders[number]>>
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Compile-time constraint verifying that every dependency declared by a seeder in `TSeeders`
|
|
77
|
+
* is also included in `TSeeders`.
|
|
78
|
+
*/
|
|
79
|
+
export type ValidateSeeders<TSeeders extends readonly SeederAny[]> = [
|
|
80
|
+
MissingSeederDeps<TSeeders>,
|
|
81
|
+
] extends [never]
|
|
82
|
+
? unknown
|
|
83
|
+
: {
|
|
84
|
+
readonly __missingDependencies__: `Missing required seeder(s) in list: ${MissingSeederDeps<TSeeders>}`
|
|
85
|
+
}
|
|
38
86
|
|
|
39
87
|
/** Configuration for creating a seeder */
|
|
40
88
|
export type SeederConfig<
|
|
@@ -46,54 +94,158 @@ export type SeederConfig<
|
|
|
46
94
|
/** Unique name for the seeder */
|
|
47
95
|
name: TName
|
|
48
96
|
/** Optional description of what the seeder does */
|
|
49
|
-
description?: string
|
|
97
|
+
description?: string | undefined
|
|
50
98
|
/** Seeder objects that must run before this one - provides typed outputs */
|
|
51
|
-
dependsOn?: TDeps
|
|
52
|
-
/** The seeding function that creates data */
|
|
99
|
+
dependsOn?: TDeps | undefined
|
|
100
|
+
/** The seeding function that creates data (sync or async) */
|
|
53
101
|
run: (
|
|
54
102
|
ctx: TContext,
|
|
55
103
|
deps: TDeps extends readonly never[] ? Record<string, never> : DepsFromSeeders<TDeps>,
|
|
56
|
-
) =>
|
|
104
|
+
) => MaybePromise<TOutput>
|
|
57
105
|
}
|
|
58
106
|
|
|
59
107
|
/** A seeder instance ready for execution */
|
|
60
|
-
export type Seeder<
|
|
108
|
+
export type Seeder<
|
|
109
|
+
TContext,
|
|
110
|
+
TName extends string = string,
|
|
111
|
+
TOutput = unknown,
|
|
112
|
+
TDepNames extends string = string,
|
|
113
|
+
> = {
|
|
61
114
|
/** Unique name for the seeder */
|
|
62
|
-
name: TName
|
|
115
|
+
readonly name: TName
|
|
63
116
|
/** Optional description of what the seeder does */
|
|
64
|
-
description?: string
|
|
117
|
+
readonly description?: string | undefined
|
|
65
118
|
/** Names of seeders that must run before this one (extracted from dependsOn) */
|
|
66
|
-
dependsOn: readonly
|
|
119
|
+
readonly dependsOn: readonly TDepNames[]
|
|
67
120
|
/** The seeding function that creates data */
|
|
68
|
-
run: (ctx: TContext, deps: Record<string, unknown>) =>
|
|
121
|
+
readonly run: (ctx: TContext, deps: Record<string, unknown>) => MaybePromise<TOutput>
|
|
69
122
|
}
|
|
70
123
|
|
|
71
124
|
/** Type-erased seeder for collections (can hold any seeder type) */
|
|
72
125
|
// biome-ignore lint/suspicious/noExplicitAny: SeederAny needs 'any' to work without explicit context type
|
|
73
|
-
export type SeederAny = Seeder<any, string, unknown>
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
export type
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
126
|
+
export type SeederAny = Seeder<any, string, unknown, string>
|
|
127
|
+
|
|
128
|
+
/** Result for a seeder that completed successfully */
|
|
129
|
+
export type CompletedSeederResult<TName extends string = string, TOutput = unknown> = {
|
|
130
|
+
name: TName
|
|
131
|
+
status: 'completed'
|
|
132
|
+
durationMs: number
|
|
133
|
+
output: TOutput
|
|
134
|
+
/** Descriptions of the steps whose output came from the cache */
|
|
135
|
+
cachedSteps: string[]
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Result for a seeder that threw an error */
|
|
139
|
+
export type FailedSeederResult<TName extends string = string> = {
|
|
140
|
+
name: TName
|
|
141
|
+
status: 'failed'
|
|
142
|
+
durationMs: number
|
|
143
|
+
error: Error
|
|
144
|
+
/** Description of the step that threw, when the seeder failed in a step */
|
|
145
|
+
failedStep?: string | undefined
|
|
146
|
+
/** Descriptions of the steps whose output came from the cache */
|
|
147
|
+
cachedSteps: string[]
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Result for a seeder that was skipped because one or more dependencies failed */
|
|
151
|
+
export type SkippedSeederResult<TName extends string = string> = {
|
|
152
|
+
name: TName
|
|
153
|
+
status: 'skipped'
|
|
154
|
+
/** Names of direct dependencies that failed or were skipped */
|
|
155
|
+
failedDeps: string[]
|
|
85
156
|
}
|
|
86
157
|
|
|
158
|
+
/** Result for a seeder that never started (e.g. an earlier seeder failed without continueOnFailure) */
|
|
159
|
+
export type PendingSeederResult<TName extends string = string> = {
|
|
160
|
+
name: TName
|
|
161
|
+
status: 'pending'
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Discriminated union representing the outcome of a seeder */
|
|
165
|
+
export type SeederResult<TName extends string = string, TOutput = unknown> =
|
|
166
|
+
| CompletedSeederResult<TName, TOutput>
|
|
167
|
+
| FailedSeederResult<TName>
|
|
168
|
+
| SkippedSeederResult<TName>
|
|
169
|
+
| PendingSeederResult<TName>
|
|
170
|
+
|
|
171
|
+
/** Status of a seeder result */
|
|
172
|
+
export type SeederStatus = SeederResult['status']
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Union of typed `SeederResult` members pairing each seeder in `TSeeders`
|
|
176
|
+
* with its literal name and output type.
|
|
177
|
+
*/
|
|
178
|
+
export type SeederResultFor<TSeeders extends readonly SeederAny[]> =
|
|
179
|
+
TSeeders[number] extends infer S
|
|
180
|
+
? S extends SeederAny
|
|
181
|
+
? SeederResult<SeederName<S>, SeederOutput<S>>
|
|
182
|
+
: never
|
|
183
|
+
: never
|
|
184
|
+
|
|
87
185
|
/** Options for the seeder runner */
|
|
88
|
-
export type RunSeedersOptions = {
|
|
186
|
+
export type RunSeedersOptions<TName extends string = string> = {
|
|
89
187
|
/** Whether to print the results table (default: true) */
|
|
90
|
-
printResults?: boolean
|
|
188
|
+
printResults?: boolean | undefined
|
|
91
189
|
/** Whether to print verbose output (default: true) */
|
|
92
|
-
verbose?: boolean
|
|
190
|
+
verbose?: boolean | undefined
|
|
93
191
|
/**
|
|
94
192
|
* Whether to continue running seeders after a failure (default: false).
|
|
95
193
|
* When true, seeders that depend on a failed seeder will be skipped,
|
|
96
194
|
* but independent seeders will still run.
|
|
97
195
|
*/
|
|
98
|
-
continueOnFailure?: boolean
|
|
196
|
+
continueOnFailure?: boolean | undefined
|
|
197
|
+
/**
|
|
198
|
+
* Run only these seeders and everything they depend on, in dependency order.
|
|
199
|
+
* Throws `UnknownSeederError` for a name that is not registered.
|
|
200
|
+
*/
|
|
201
|
+
only?: readonly TName[] | undefined
|
|
202
|
+
/**
|
|
203
|
+
* Ignore cached step entries and overwrite them: `true` for every seeder,
|
|
204
|
+
* or the names of the seeders to run fresh. Dependencies of those seeders still
|
|
205
|
+
* replay their cache unless they are named too.
|
|
206
|
+
*/
|
|
207
|
+
fresh?: boolean | readonly TName[] | undefined
|
|
208
|
+
/**
|
|
209
|
+
* Seed a target that is not local (see `target` on the instance config).
|
|
210
|
+
* Without it, a non-local target throws `SeedTargetError` before anything runs.
|
|
211
|
+
*/
|
|
212
|
+
allowRemote?: boolean | undefined
|
|
213
|
+
/**
|
|
214
|
+
* Maximum number of independent seeders to run concurrently (default: 1).
|
|
215
|
+
* Set to a positive integer (e.g. `4`) or `Infinity` to run independent DAG branches in parallel.
|
|
216
|
+
*/
|
|
217
|
+
concurrency?: number | undefined
|
|
99
218
|
}
|
|
219
|
+
|
|
220
|
+
type OutputsOnSuccess<TSeeders extends readonly SeederAny[], TOptions> = [TOptions] extends [
|
|
221
|
+
undefined,
|
|
222
|
+
]
|
|
223
|
+
? SeederOutputs<TSeeders>
|
|
224
|
+
: TOptions extends { readonly only: readonly (infer TOnly extends string)[] }
|
|
225
|
+
? string extends TOnly
|
|
226
|
+
? Partial<SeederOutputs<TSeeders>>
|
|
227
|
+
: Prettify<
|
|
228
|
+
Pick<SeederOutputs<TSeeders>, Extract<TOnly, keyof SeederOutputs<TSeeders>>> &
|
|
229
|
+
Partial<SeederOutputs<TSeeders>>
|
|
230
|
+
>
|
|
231
|
+
: TOptions extends { readonly only?: readonly string[] | undefined }
|
|
232
|
+
? 'only' extends keyof TOptions
|
|
233
|
+
? Partial<SeederOutputs<TSeeders>>
|
|
234
|
+
: SeederOutputs<TSeeders>
|
|
235
|
+
: SeederOutputs<TSeeders>
|
|
236
|
+
|
|
237
|
+
/** Return value of `runSeeders` with typed `results` and `outputs` */
|
|
238
|
+
export type RunSeedersResult<
|
|
239
|
+
TSeeders extends readonly SeederAny[] = readonly SeederAny[],
|
|
240
|
+
TOptions = undefined,
|
|
241
|
+
> =
|
|
242
|
+
| {
|
|
243
|
+
success: true
|
|
244
|
+
results: SeederResultFor<TSeeders>[]
|
|
245
|
+
outputs: OutputsOnSuccess<TSeeders, TOptions>
|
|
246
|
+
}
|
|
247
|
+
| {
|
|
248
|
+
success: false
|
|
249
|
+
results: SeederResultFor<TSeeders>[]
|
|
250
|
+
outputs: Partial<SeederOutputs<TSeeders>>
|
|
251
|
+
}
|
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.js'
|
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 {};
|