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.
@@ -0,0 +1,171 @@
1
+ import { type SeederCache } from './step';
2
+ import type { BaseSeederContext, RunSeedersOptions, Seeder, SeederAny, SeederConfig, SeederResult } from './types';
3
+ /**
4
+ * Configuration for creating a seeder instance.
5
+ * The context factory receives the base context (faker, step, expect) and can extend it.
6
+ */
7
+ export type SeederInstanceConfig<TContext extends BaseSeederContext> = {
8
+ /**
9
+ * Factory function that creates the context for each seeder.
10
+ * Receives the base context (faker, step, expect) and should return the full context.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * context: (base) => ({
15
+ * ...base,
16
+ * prisma,
17
+ * myHelper: () => { ... }
18
+ * })
19
+ * ```
20
+ */
21
+ context: (base: BaseSeederContext) => TContext | Promise<TContext>;
22
+ /**
23
+ * Optional cache for step caching.
24
+ * Provide get/set functions to enable caching in the step runner.
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * cache: {
29
+ * get: async (key) => {
30
+ * const cached = await prisma.seedCache.findUnique({ where: { key } })
31
+ * return cached?.output as T | undefined
32
+ * },
33
+ * set: async (key, value) => {
34
+ * await prisma.seedCache.create({ data: { key, output: value } })
35
+ * }
36
+ * }
37
+ * ```
38
+ */
39
+ cache?: SeederCache;
40
+ /**
41
+ * Called before all seeders run.
42
+ * Use for setup like connecting to databases.
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * onBeforeAll: async () => {
47
+ * await prisma.$connect()
48
+ * }
49
+ * ```
50
+ */
51
+ onBeforeAll?: () => void | Promise<void>;
52
+ /**
53
+ * Called after all seeders complete (success or failure).
54
+ * Use for cleanup like disconnecting from databases.
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * onAfterAll: async () => {
59
+ * await prisma.$disconnect()
60
+ * }
61
+ * ```
62
+ */
63
+ onAfterAll?: () => void | Promise<void>;
64
+ };
65
+ /**
66
+ * Result type for the seeder instance
67
+ */
68
+ export type SeederInstance<TContext extends BaseSeederContext> = {
69
+ /**
70
+ * Define a new seeder with typed dependencies
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * const userSeeder = defineSeeder({
75
+ * name: 'userSeeder',
76
+ * dependsOn: [orgSeeder],
77
+ * run: async (ctx, deps) => {
78
+ * const { orgId } = deps.orgSeeder
79
+ * // ctx.faker, ctx.step, ctx.expect are always available
80
+ * return { userId: 'user-1' }
81
+ * }
82
+ * })
83
+ * ```
84
+ */
85
+ defineSeeder: <TName extends string, TOutput, const TDeps extends readonly SeederAny[] = readonly []>(config: SeederConfig<TContext, TName, TOutput, TDeps>) => Seeder<TContext, TName, TOutput>;
86
+ /**
87
+ * Run an array of seeders in dependency order.
88
+ * Automatically sets seeding state to active during execution.
89
+ *
90
+ * @param seeders - Array of seeders to run
91
+ * @param options - Optional runner options
92
+ * @returns Object containing results and success status
93
+ */
94
+ runSeeders: (seeders: readonly SeederAny[], options?: RunSeedersOptions) => Promise<{
95
+ results: SeederResult[];
96
+ success: boolean;
97
+ }>;
98
+ /**
99
+ * Run seeders as a CLI command.
100
+ * Handles help flag, prints banner, runs seeders, and exits with proper code.
101
+ *
102
+ * @example
103
+ * ```typescript
104
+ * // At the bottom of your seed registry file:
105
+ * if (import.meta.main) {
106
+ * runSeedersCli(seeders)
107
+ * }
108
+ * ```
109
+ */
110
+ runSeedersCli: (seeders: readonly SeederAny[], options?: {
111
+ name?: string;
112
+ }) => Promise<void>;
113
+ /**
114
+ * Check if seeding is currently active.
115
+ * Use this in your application to skip side effects during seeding.
116
+ *
117
+ * @example
118
+ * ```typescript
119
+ * if (isSeedingActive()) {
120
+ * console.log('Skipping notification during seeding')
121
+ * return
122
+ * }
123
+ * ```
124
+ */
125
+ isSeedingActive: () => boolean;
126
+ };
127
+ /**
128
+ * Create a seeder instance with a custom context
129
+ *
130
+ * This is the main entry point for the seeder library. The library provides
131
+ * a base context with faker, step, and expect. Consumers extend this with
132
+ * their own context (e.g. prisma, custom helpers).
133
+ *
134
+ * The seeding state is automatically managed - set to active when runSeeders
135
+ * starts and set to inactive when it completes.
136
+ *
137
+ * @example
138
+ * ```typescript
139
+ * import { createSeederInstance } from 'plantr'
140
+ *
141
+ * type MyContext = BaseSeederContext & { prisma: typeof prisma }
142
+ *
143
+ * const { defineSeeder, runSeeders, isSeedingActive } = createSeederInstance<MyContext>({
144
+ * context: (base) => ({
145
+ * ...base,
146
+ * prisma,
147
+ * }),
148
+ * cache: {
149
+ * get: async (key) => {
150
+ * const cached = await prisma.seedCache.findUnique({ where: { key } })
151
+ * return cached?.output
152
+ * },
153
+ * set: async (key, value) => {
154
+ * await prisma.seedCache.create({ data: { key, output: value } })
155
+ * }
156
+ * },
157
+ * })
158
+ *
159
+ * export { defineSeeder, isSeedingActive }
160
+ *
161
+ * // In your message/queue system:
162
+ * if (isSeedingActive()) {
163
+ * console.log('Skipping side effect during seeding')
164
+ * return
165
+ * }
166
+ *
167
+ * // Later...
168
+ * await runSeeders([seeder1, seeder2])
169
+ * ```
170
+ */
171
+ export declare function createSeederInstance<TContext extends BaseSeederContext = BaseSeederContext>(config: SeederInstanceConfig<TContext>): SeederInstance<TContext>;
@@ -0,0 +1,28 @@
1
+ import type { Seeder, SeederAny, SeederConfig } from './types';
2
+ /**
3
+ * Create a typed seeder definition
4
+ *
5
+ * This is the core factory that creates a seeder from a configuration.
6
+ * The seeder can then be passed to `runSeeders` for execution.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { defineSeeder } from './registries/seed'
11
+ *
12
+ * export default defineSeeder({
13
+ * name: 'createUsers',
14
+ * description: 'Seeds user data',
15
+ * dependsOn: [organizationSeeder],
16
+ * run: async (ctx, deps) => {
17
+ * // ctx contains whatever the consumer configured
18
+ * // deps.organizationSeeder is fully typed with the output of organizationSeeder
19
+ * const { organizationId } = deps.organizationSeeder
20
+ *
21
+ * // ... create users
22
+ *
23
+ * return { userIds: [...] }
24
+ * }
25
+ * })
26
+ * ```
27
+ */
28
+ export declare function createDefineSeeder<TContext>(): <TName extends string, TOutput, const TDeps extends readonly SeederAny[] = readonly []>(config: SeederConfig<TContext, TName, TOutput, TDeps>) => Seeder<TContext, TName, TOutput>;
@@ -0,0 +1,23 @@
1
+ import type { SeederAny } from './types';
2
+ /**
3
+ * Error thrown when circular dependencies are detected in seeders
4
+ */
5
+ export declare class CircularDependencyError extends Error {
6
+ constructor(cycle: string[]);
7
+ }
8
+ /**
9
+ * Error thrown when a seeder depends on a non-existent seeder
10
+ */
11
+ export declare class MissingDependencyError extends Error {
12
+ constructor(seeder: string, missingDep: string);
13
+ }
14
+ /**
15
+ * Resolves the execution order of seeders based on their dependencies
16
+ * using Kahn's algorithm (topological sort)
17
+ *
18
+ * @param seeders - Array of seeders to sort
19
+ * @returns Array of seeder names in execution order
20
+ * @throws {CircularDependencyError} If circular dependencies are detected
21
+ * @throws {MissingDependencyError} If a seeder depends on a non-existent seeder
22
+ */
23
+ export declare function resolveDependencyOrder(seeders: readonly SeederAny[]): string[];
@@ -0,0 +1,40 @@
1
+ import type { SeederResult } from './types';
2
+ type ColorName = 'red' | 'green' | 'yellow' | 'cyan' | 'white' | 'gray' | 'dim';
3
+ type StyleName = 'bold' | 'dim';
4
+ /**
5
+ * Simple colorize function for terminal output
6
+ */
7
+ export declare function colorize(text: string, color: ColorName, style?: StyleName): string;
8
+ /**
9
+ * Format duration in a human-readable way
10
+ */
11
+ export declare function formatDuration(ms: number): string;
12
+ /**
13
+ * Print a formatted table of seeder results
14
+ */
15
+ export declare function printResultsTable(results: SeederResult[]): void;
16
+ /**
17
+ * Print error details for failed seeders
18
+ */
19
+ export declare function printErrors(results: SeederResult[]): void;
20
+ /**
21
+ * Print seeder header before execution
22
+ */
23
+ export declare function printSeederHeader(name: string, index: number, total: number, description?: string): void;
24
+ /**
25
+ * Print completion status after a seeder runs
26
+ */
27
+ export declare function printSeederComplete(durationMs: number, success: boolean): void;
28
+ /**
29
+ * Print the initial banner when seeding starts
30
+ */
31
+ export declare function printStartBanner(label?: string): void;
32
+ /**
33
+ * Print message when a seeder is skipped due to failed dependencies
34
+ */
35
+ export declare function printSeederSkipped(failedDeps: string[]): void;
36
+ /**
37
+ * Print the final summary after all seeders complete
38
+ */
39
+ export declare function printSummary(results: SeederResult[]): void;
40
+ export {};
@@ -0,0 +1,27 @@
1
+ import type { RunSeedersOptions, SeederAny, SeederResult } from './types';
2
+ /**
3
+ * Internal configuration used by the runner.
4
+ * This is created by createSeederInstance and includes the wrapped context factory.
5
+ */
6
+ export type InternalSeederConfig<TContext> = {
7
+ /** Factory function that creates the full context (already includes base context) */
8
+ context: () => TContext | Promise<TContext>;
9
+ /** Called before each seeder to set the current seeder name (for cache key scoping) */
10
+ setSeederName?: (name: string) => void;
11
+ /** Called before all seeders run */
12
+ onBeforeAll?: () => void | Promise<void>;
13
+ /** Called after all seeders complete */
14
+ onAfterAll?: () => void | Promise<void>;
15
+ };
16
+ /**
17
+ * Core seeder runner - executes seeders in dependency order
18
+ *
19
+ * @param seeders - Array of seeders to run
20
+ * @param config - Instance configuration (context factory, lifecycle hooks)
21
+ * @param options - Runner options (verbose output, etc.)
22
+ * @returns Object containing results and success status
23
+ */
24
+ export declare function runSeedersCore<TContext>(seeders: readonly SeederAny[], config: InternalSeederConfig<TContext>, options?: RunSeedersOptions): Promise<{
25
+ results: SeederResult[];
26
+ success: boolean;
27
+ }>;
@@ -0,0 +1,18 @@
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
+ * Check if seeding is currently active
12
+ */
13
+ export declare function isSeedingActive(): boolean;
14
+ /**
15
+ * Set the seeding state.
16
+ * Called automatically by the seeder runner's onBeforeAll/onAfterAll hooks.
17
+ */
18
+ export declare function setSeedingActive(active: boolean): void;
@@ -0,0 +1,30 @@
1
+ export type StepOptions = {
2
+ /** Enable caching for this step */
3
+ useCache?: boolean;
4
+ };
5
+ export type StepFn = <T>(description: string, fn: () => T | Promise<T>, options?: StepOptions) => Promise<T>;
6
+ /**
7
+ * Cache interface for step caching.
8
+ * Provide get/set functions to enable caching in the step runner.
9
+ */
10
+ export type SeederCache = {
11
+ /** Get a cached value by key. Returns undefined if not found. */
12
+ get: <T>(key: string) => Promise<T | undefined>;
13
+ /** Set a cached value by key. */
14
+ set: <T>(key: string, value: T) => Promise<void>;
15
+ };
16
+ type StepRunnerConfig = {
17
+ cache?: SeederCache;
18
+ /** Seeder name for scoping cache keys */
19
+ seederName?: string;
20
+ };
21
+ /**
22
+ * Create a step runner for organizing seeder workflow.
23
+ * Optionally provide a cache for step caching support.
24
+ */
25
+ export declare function createStepRunner(config?: StepRunnerConfig): {
26
+ step: StepFn;
27
+ /** Set the current seeder name for cache key scoping */
28
+ setSeederName: (name: string) => void;
29
+ };
30
+ export {};
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Generic seeder types - context-agnostic
3
+ *
4
+ * The library provides a base context with faker, step, and expect.
5
+ * Consumers can extend this with their own context (e.g. prisma, custom helpers).
6
+ */
7
+ import type { expect } from 'bun:test';
8
+ import type { faker } from '@faker-js/faker';
9
+ import type { StepFn } from './step';
10
+ /**
11
+ * Base seeder context provided by the library.
12
+ * Contains faker for generating test data, step for workflow organization,
13
+ * and expect for assertions.
14
+ */
15
+ export type BaseSeederContext = {
16
+ /** Faker instance for generating test data */
17
+ faker: typeof faker;
18
+ /** Step function for organizing seeder workflow */
19
+ step: StepFn;
20
+ /** Assertion function from bun:test for verifying data */
21
+ expect: typeof expect;
22
+ };
23
+ /** Extract the output type from a Seeder */
24
+ export type SeederOutput<T> = T extends Seeder<any, string, infer O> ? O : never;
25
+ /** Extract the name from a Seeder */
26
+ export type SeederName<T> = T extends Seeder<any, infer N, unknown> ? N : never;
27
+ /** Build a typed deps object from an array of seeder dependencies */
28
+ export type DepsFromSeeders<T extends readonly SeederAny[]> = {
29
+ [K in T[number] as SeederName<K>]: SeederOutput<K>;
30
+ };
31
+ /** Configuration for creating a seeder */
32
+ export type SeederConfig<TContext, TName extends string, TOutput, TDeps extends readonly SeederAny[] = readonly []> = {
33
+ /** Unique name for the seeder */
34
+ name: TName;
35
+ /** Optional description of what the seeder does */
36
+ description?: string;
37
+ /** Seeder objects that must run before this one - provides typed outputs */
38
+ dependsOn?: TDeps;
39
+ /** The seeding function that creates data */
40
+ run: (ctx: TContext, deps: TDeps extends readonly never[] ? Record<string, never> : DepsFromSeeders<TDeps>) => Promise<TOutput>;
41
+ };
42
+ /** A seeder instance ready for execution */
43
+ export type Seeder<TContext, TName extends string = string, TOutput = unknown> = {
44
+ /** Unique name for the seeder */
45
+ name: TName;
46
+ /** Optional description of what the seeder does */
47
+ description?: string;
48
+ /** Names of seeders that must run before this one (extracted from dependsOn) */
49
+ dependsOn: readonly string[];
50
+ /** The seeding function that creates data */
51
+ run: (ctx: TContext, deps: Record<string, unknown>) => Promise<TOutput>;
52
+ };
53
+ /** Type-erased seeder for collections (can hold any seeder type) */
54
+ export type SeederAny = Seeder<any, string, unknown>;
55
+ /** Status of a seeder execution */
56
+ export type SeederStatus = 'pending' | 'running' | 'completed' | 'failed' | 'skipped';
57
+ /** Result of running a seeder */
58
+ export type SeederResult = {
59
+ name: string;
60
+ status: SeederStatus;
61
+ durationMs?: number;
62
+ output?: unknown;
63
+ error?: Error;
64
+ };
65
+ /** Options for the seeder runner */
66
+ export type RunSeedersOptions = {
67
+ /** Whether to print the results table (default: true) */
68
+ printResults?: boolean;
69
+ /** Whether to print verbose output (default: true) */
70
+ verbose?: boolean;
71
+ /**
72
+ * Whether to continue running seeders after a failure (default: false).
73
+ * When true, seeders that depend on a failed seeder will be skipped,
74
+ * but independent seeders will still run.
75
+ */
76
+ continueOnFailure?: boolean;
77
+ };
package/index.ts ADDED
@@ -0,0 +1,76 @@
1
+ /**
2
+ * plantr - Generic seeder library with built-in faker, step, and expect
3
+ *
4
+ * A Bun-first library for creating type-safe database seeders with dependency resolution.
5
+ * The library provides a base context with faker, step, and expect. Consumers
6
+ * extend this with their own context (e.g. prisma, custom helpers).
7
+ *
8
+ * Note: This library requires Bun as it uses bun:test for the expect function.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * import { createSeederInstance, type BaseSeederContext } from 'plantr'
13
+ *
14
+ * type MyContext = BaseSeederContext & { prisma: typeof prisma }
15
+ *
16
+ * const { defineSeeder, runSeeders } = createSeederInstance<MyContext>({
17
+ * context: (base) => ({
18
+ * ...base,
19
+ * prisma,
20
+ * }),
21
+ * })
22
+ *
23
+ * const userSeeder = defineSeeder({
24
+ * name: 'userSeeder',
25
+ * run: async ({ faker, step, expect, prisma }) => {
26
+ * // faker, step, expect are always available from base context
27
+ * const user = await step('Create user', async () => {
28
+ * return prisma.user.create({ data: { name: faker.person.fullName() } })
29
+ * })
30
+ * expect(user).toBeDefined()
31
+ * return { userId: user.id }
32
+ * }
33
+ * })
34
+ *
35
+ * await runSeeders([userSeeder])
36
+ * ```
37
+ */
38
+
39
+ // Re-export faker and expect for convenience
40
+ export { expect } from 'bun:test'
41
+ export { faker } from '@faker-js/faker'
42
+
43
+ // Main API
44
+ export type { SeederInstance, SeederInstanceConfig } from './src/create-seeder-instance'
45
+ export { createSeederInstance } from './src/create-seeder-instance'
46
+
47
+ // Utilities (for advanced use cases)
48
+ export { createDefineSeeder } from './src/define-seeder'
49
+ export {
50
+ CircularDependencyError,
51
+ MissingDependencyError,
52
+ resolveDependencyOrder,
53
+ } from './src/dependency-resolver'
54
+ export { colorize, formatDuration } from './src/formatting'
55
+ export { runSeedersCore } from './src/run-seeders'
56
+
57
+ // Seeding state (for advanced use cases - prefer using isSeedingActive from the instance)
58
+ export { isSeedingActive } from './src/seeding-state'
59
+
60
+ // Step types and cache
61
+ export type { SeederCache, StepFn, StepOptions } from './src/step'
62
+ export { createStepRunner } from './src/step'
63
+
64
+ // Types
65
+ export type {
66
+ BaseSeederContext,
67
+ DepsFromSeeders,
68
+ RunSeedersOptions,
69
+ Seeder,
70
+ SeederAny,
71
+ SeederConfig,
72
+ SeederName,
73
+ SeederOutput,
74
+ SeederResult,
75
+ SeederStatus,
76
+ } from './src/types'
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "plantr",
3
+ "version": "1.0.1",
4
+ "description": "A generic seeder library with built-in faker, step, and expect support for type-safe database seeding",
5
+ "type": "module",
6
+ "module": "./dist/index.js",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "license": "MIT",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/HansKristoffer/plantr.git"
13
+ },
14
+ "author": "Kristoffer Hansen",
15
+ "keywords": [
16
+ "bun",
17
+ "seeder",
18
+ "database",
19
+ "faker",
20
+ "testing",
21
+ "seed",
22
+ "prisma",
23
+ "typescript",
24
+ "dependency-injection"
25
+ ],
26
+ "engines": {
27
+ "bun": ">=1.0.0"
28
+ },
29
+ "files": [
30
+ "*.ts",
31
+ "src/*.ts",
32
+ "dist",
33
+ "!*.test.ts",
34
+ "!src/*.test.ts"
35
+ ],
36
+ "exports": {
37
+ ".": {
38
+ "types": "./dist/index.d.ts",
39
+ "bun": "./index.ts",
40
+ "import": "./dist/index.js",
41
+ "default": "./dist/index.js"
42
+ }
43
+ },
44
+ "scripts": {
45
+ "build": "bun run build:js && bun run build:types",
46
+ "build:js": "bun build ./index.ts --outdir ./dist --target node --packages external",
47
+ "build:types": "tsc -p tsconfig.build.json",
48
+ "test": "bun test",
49
+ "prepublishOnly": "bun run build",
50
+ "publish:patch": "npm version patch && npm publish",
51
+ "publish:minor": "npm version minor && npm publish",
52
+ "publish:major": "npm version major && npm publish",
53
+ "lint": "bun run typecheck && biome check",
54
+ "lint:write": "bun run typecheck && biome check --fix && biome format",
55
+ "typecheck": "tsgo --incremental"
56
+ },
57
+ "dependencies": {
58
+ "@faker-js/faker": "^9.0.0"
59
+ },
60
+ "devDependencies": {
61
+ "@types/bun": "1.3.2",
62
+ "@biomejs/biome": "2.3.4",
63
+ "@typescript/native-preview": "7.0.0-dev.20260127.1",
64
+ "typescript": "^5.7.0"
65
+ }
66
+ }