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.
- package/dist/index.d.ts +31 -25
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1050 -251
- package/dist/src/cli.d.ts +13 -3
- package/dist/src/cli.d.ts.map +1 -0
- package/dist/src/create-seeder-instance.d.ts +64 -78
- 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 +2 -1
- package/dist/src/dependency-resolver.d.ts.map +1 -0
- package/dist/src/expect.d.ts +41 -0
- package/dist/src/expect.d.ts.map +1 -0
- package/dist/src/formatting.d.ts +36 -14
- 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 +46 -26
- package/dist/src/run-seeders.d.ts.map +1 -0
- package/dist/src/seeding-state.d.ts +15 -4
- package/dist/src/seeding-state.d.ts.map +1 -0
- package/dist/src/step.d.ts +79 -22
- package/dist/src/step.d.ts.map +1 -0
- package/dist/src/types.d.ts +121 -38
- package/dist/src/types.d.ts.map +1 -0
- package/dist/state.d.ts +2 -1
- package/dist/state.d.ts.map +1 -0
- package/dist/state.js +10 -2
- package/index.ts +70 -28
- package/package.json +5 -2
- package/readme.md +102 -52
- package/src/cli.ts +155 -22
- package/src/create-seeder-instance.ts +252 -111
- package/src/define-seeder.ts +14 -7
- package/src/dependency-resolver.ts +17 -28
- package/src/expect.ts +502 -0
- package/src/formatting.ts +142 -37
- package/src/lazy-faker.ts +46 -0
- package/src/run-seeders.ts +352 -122
- package/src/seeding-state.ts +27 -5
- package/src/step.ts +208 -64
- package/src/types.ts +173 -41
- package/state.ts +1 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1,5 @@
|
|
|
1
|
-
// index.ts
|
|
2
|
-
import { expect as expect2 } from "bun:test";
|
|
3
|
-
import { faker as faker2 } from "@faker-js/faker";
|
|
4
|
-
|
|
5
1
|
// src/create-seeder-instance.ts
|
|
6
|
-
import {
|
|
7
|
-
import { faker } from "@faker-js/faker";
|
|
2
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
8
3
|
|
|
9
4
|
// src/cli.ts
|
|
10
5
|
import { parseArgs } from "node:util";
|
|
@@ -12,7 +7,7 @@ import { parseArgs } from "node:util";
|
|
|
12
7
|
// src/dependency-resolver.ts
|
|
13
8
|
class CircularDependencyError extends Error {
|
|
14
9
|
constructor(cycle) {
|
|
15
|
-
super(`Circular dependency detected in seeders: ${cycle.join(" -> ")} -> ${cycle[0]}`);
|
|
10
|
+
super(`Circular dependency detected in seeders: ${cycle.join(" -> ")} -> ${cycle[0] ?? ""}`);
|
|
16
11
|
this.name = "CircularDependencyError";
|
|
17
12
|
}
|
|
18
13
|
}
|
|
@@ -44,13 +39,6 @@ function resolveDependencyOrder(seeders, only) {
|
|
|
44
39
|
throw new DuplicateSeederError(seeder.name);
|
|
45
40
|
seederMap.set(seeder.name, seeder);
|
|
46
41
|
}
|
|
47
|
-
for (const seeder of seeders) {
|
|
48
|
-
for (const dep of seeder.dependsOn) {
|
|
49
|
-
if (!seederMap.has(dep)) {
|
|
50
|
-
throw new MissingDependencyError(seeder.name, dep);
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
42
|
const inDegree = new Map;
|
|
55
43
|
const dependents = new Map;
|
|
56
44
|
for (const seeder of seeders) {
|
|
@@ -58,12 +46,14 @@ function resolveDependencyOrder(seeders, only) {
|
|
|
58
46
|
dependents.set(seeder.name, []);
|
|
59
47
|
}
|
|
60
48
|
for (const seeder of seeders) {
|
|
61
|
-
|
|
62
|
-
|
|
49
|
+
const uniqueDeps = new Set(seeder.dependsOn);
|
|
50
|
+
inDegree.set(seeder.name, uniqueDeps.size);
|
|
51
|
+
for (const dep of uniqueDeps) {
|
|
63
52
|
const deps = dependents.get(dep);
|
|
64
|
-
if (deps) {
|
|
65
|
-
|
|
53
|
+
if (!deps) {
|
|
54
|
+
throw new MissingDependencyError(seeder.name, dep);
|
|
66
55
|
}
|
|
56
|
+
deps.push(seeder.name);
|
|
67
57
|
}
|
|
68
58
|
}
|
|
69
59
|
const queue = [];
|
|
@@ -73,10 +63,13 @@ function resolveDependencyOrder(seeders, only) {
|
|
|
73
63
|
}
|
|
74
64
|
}
|
|
75
65
|
const result = [];
|
|
76
|
-
|
|
77
|
-
|
|
66
|
+
let head = 0;
|
|
67
|
+
while (head < queue.length) {
|
|
68
|
+
const current = queue[head++];
|
|
78
69
|
result.push(current);
|
|
79
|
-
const deps = dependents.get(current)
|
|
70
|
+
const deps = dependents.get(current);
|
|
71
|
+
if (!deps)
|
|
72
|
+
continue;
|
|
80
73
|
for (const dependent of deps) {
|
|
81
74
|
const newDegree = (inDegree.get(dependent) ?? 0) - 1;
|
|
82
75
|
inDegree.set(dependent, newDegree);
|
|
@@ -86,7 +79,8 @@ function resolveDependencyOrder(seeders, only) {
|
|
|
86
79
|
}
|
|
87
80
|
}
|
|
88
81
|
if (result.length !== seeders.length) {
|
|
89
|
-
const
|
|
82
|
+
const resolved = new Set(result);
|
|
83
|
+
const remaining = seeders.filter((s) => !resolved.has(s.name));
|
|
90
84
|
const cycle = findCycle(remaining, seederMap);
|
|
91
85
|
throw new CircularDependencyError(cycle);
|
|
92
86
|
}
|
|
@@ -144,6 +138,14 @@ function findCycle(remaining, seederMap) {
|
|
|
144
138
|
}
|
|
145
139
|
|
|
146
140
|
// src/formatting.ts
|
|
141
|
+
import { inspect as nodeInspect } from "node:util";
|
|
142
|
+
function inspectValue(value, options) {
|
|
143
|
+
const bunInspect = globalThis.Bun?.inspect;
|
|
144
|
+
if (typeof bunInspect === "function") {
|
|
145
|
+
return options ? bunInspect(value, options) : bunInspect(value);
|
|
146
|
+
}
|
|
147
|
+
return nodeInspect(value, { colors: options?.colors ?? false });
|
|
148
|
+
}
|
|
147
149
|
var colors = {
|
|
148
150
|
reset: "\x1B[0m",
|
|
149
151
|
bold: "\x1B[1m",
|
|
@@ -155,7 +157,16 @@ var colors = {
|
|
|
155
157
|
white: "\x1B[37m",
|
|
156
158
|
gray: "\x1B[90m"
|
|
157
159
|
};
|
|
160
|
+
function supportsColor() {
|
|
161
|
+
if (process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== "")
|
|
162
|
+
return false;
|
|
163
|
+
if (process.env.FORCE_COLOR !== undefined && process.env.FORCE_COLOR !== "0")
|
|
164
|
+
return true;
|
|
165
|
+
return Boolean(process.stdout.isTTY);
|
|
166
|
+
}
|
|
158
167
|
function colorize(text, color, style) {
|
|
168
|
+
if (!supportsColor())
|
|
169
|
+
return text;
|
|
159
170
|
let result = "";
|
|
160
171
|
if (style === "bold")
|
|
161
172
|
result += colors.bold;
|
|
@@ -166,7 +177,7 @@ function colorize(text, color, style) {
|
|
|
166
177
|
}
|
|
167
178
|
function formatDuration(ms) {
|
|
168
179
|
if (ms < 1000)
|
|
169
|
-
return `${ms}ms`;
|
|
180
|
+
return `${Math.round(ms)}ms`;
|
|
170
181
|
if (ms < 60000)
|
|
171
182
|
return `${(ms / 1000).toFixed(1)}s`;
|
|
172
183
|
return `${(ms / 60000).toFixed(1)}m`;
|
|
@@ -181,7 +192,12 @@ function printResultsTable(results) {
|
|
|
181
192
|
const durationHeader = "Duration";
|
|
182
193
|
const maxNameLen = Math.max(nameHeader.length, ...results.map((r) => r.name.length));
|
|
183
194
|
const maxStatusLen = Math.max(statusHeader.length, 10);
|
|
184
|
-
const maxDurationLen = Math.max(durationHeader.length, ...results.map((r) =>
|
|
195
|
+
const maxDurationLen = Math.max(durationHeader.length, ...results.map((r) => {
|
|
196
|
+
if (r.status === "completed" || r.status === "failed") {
|
|
197
|
+
return formatDuration(r.durationMs).length;
|
|
198
|
+
}
|
|
199
|
+
return 1;
|
|
200
|
+
}));
|
|
185
201
|
const topBorder = `┌${"─".repeat(maxNameLen + 2)}┬${"─".repeat(maxStatusLen + 2)}┬${"─".repeat(maxDurationLen + 2)}┐`;
|
|
186
202
|
const divider = `├${"─".repeat(maxNameLen + 2)}┼${"─".repeat(maxStatusLen + 2)}┼${"─".repeat(maxDurationLen + 2)}┤`;
|
|
187
203
|
const bottomBorder = `└${"─".repeat(maxNameLen + 2)}┴${"─".repeat(maxStatusLen + 2)}┴${"─".repeat(maxDurationLen + 2)}┘`;
|
|
@@ -192,28 +208,27 @@ function printResultsTable(results) {
|
|
|
192
208
|
for (const result of results) {
|
|
193
209
|
let statusDisplay;
|
|
194
210
|
let statusColor;
|
|
211
|
+
let duration = "-";
|
|
195
212
|
switch (result.status) {
|
|
196
213
|
case "completed":
|
|
197
214
|
statusDisplay = "✓ Done";
|
|
198
215
|
statusColor = "green";
|
|
216
|
+
duration = formatDuration(result.durationMs);
|
|
199
217
|
break;
|
|
200
218
|
case "failed":
|
|
201
219
|
statusDisplay = "✗ Failed";
|
|
202
220
|
statusColor = "red";
|
|
221
|
+
duration = formatDuration(result.durationMs);
|
|
203
222
|
break;
|
|
204
223
|
case "skipped":
|
|
205
224
|
statusDisplay = "⊘ Skipped";
|
|
206
225
|
statusColor = "yellow";
|
|
207
226
|
break;
|
|
208
|
-
case "
|
|
209
|
-
statusDisplay = "⟳ Running";
|
|
210
|
-
statusColor = "yellow";
|
|
211
|
-
break;
|
|
212
|
-
default:
|
|
227
|
+
case "pending":
|
|
213
228
|
statusDisplay = "○ Pending";
|
|
214
229
|
statusColor = "gray";
|
|
230
|
+
break;
|
|
215
231
|
}
|
|
216
|
-
const duration = result.durationMs !== undefined ? formatDuration(result.durationMs) : "-";
|
|
217
232
|
console.log(`│ ${result.name.padEnd(maxNameLen)} │ ${colorize(statusDisplay.padEnd(maxStatusLen), statusColor)} │ ${colorize(duration.padEnd(maxDurationLen), "dim")} │`);
|
|
218
233
|
}
|
|
219
234
|
console.log(bottomBorder);
|
|
@@ -225,19 +240,16 @@ function printErrors(results) {
|
|
|
225
240
|
for (const result of failed) {
|
|
226
241
|
const where = result.failedStep ? ` in step "${result.failedStep}"` : "";
|
|
227
242
|
console.log(colorize(`❌ Seeder "${result.name}" failed${where}:`, "red"));
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
for (const line of details.split(`
|
|
243
|
+
const details = inspectValue(result.error, { colors: supportsColor() });
|
|
244
|
+
for (const line of details.split(`
|
|
231
245
|
`))
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
if (cached.length > 0) {
|
|
236
|
-
console.log(colorize(` ${cached.length} earlier step(s) came from the cache: ${cached.join(", ")}. If they are stale, run this seeder fresh (CLI: --only ${result.name} --fresh).`, "yellow"));
|
|
246
|
+
console.log(` ${line}`);
|
|
247
|
+
if (result.cachedSteps.length > 0) {
|
|
248
|
+
console.log(colorize(` ${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).`, "yellow"));
|
|
237
249
|
}
|
|
238
250
|
if (process.env.GITHUB_ACTIONS === "true") {
|
|
239
251
|
const title = `Seeder ${result.name} failed${where}`.replace(/[:,]/g, " ");
|
|
240
|
-
console.log(`::error title=${escapeAnnotation(title)}::${escapeAnnotation(result.error
|
|
252
|
+
console.log(`::error title=${escapeAnnotation(title)}::${escapeAnnotation(result.error.message || "failed")}`);
|
|
241
253
|
}
|
|
242
254
|
console.log("");
|
|
243
255
|
}
|
|
@@ -260,10 +272,25 @@ function printSeederComplete(durationMs, success) {
|
|
|
260
272
|
}
|
|
261
273
|
console.log("");
|
|
262
274
|
}
|
|
263
|
-
function
|
|
275
|
+
function printConcurrentComplete(seederName, durationMs, success) {
|
|
276
|
+
const tag = colorize(`[${seederName}]`, "cyan", "bold");
|
|
277
|
+
if (success) {
|
|
278
|
+
console.log(` ${tag} ${colorize(`✓ Completed in ${formatDuration(durationMs)}`, "green")}`);
|
|
279
|
+
} else {
|
|
280
|
+
console.log(` ${tag} ${colorize(`✗ Failed after ${formatDuration(durationMs)}`, "red")}`);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
function printConcurrentSkipped(seederName, failedDeps) {
|
|
284
|
+
const tag = colorize(`[${seederName}]`, "cyan", "bold");
|
|
285
|
+
console.log(` ${tag} ${colorize(`⊘ Skipped (depends on failed: ${failedDeps.join(", ")})`, "yellow")}`);
|
|
286
|
+
}
|
|
287
|
+
function printStartBanner(options) {
|
|
288
|
+
const name = options?.name ?? "Seeders";
|
|
289
|
+
const countText = options?.count !== undefined ? ` ${colorize(`(${options.count} ${options.count === 1 ? "seeder" : "seeders"}${options.concurrency && options.concurrency > 1 ? `, concurrency: ${options.concurrency === Number.POSITIVE_INFINITY ? "∞" : options.concurrency}` : ""})`, "dim")}` : "";
|
|
290
|
+
const target = options?.target;
|
|
264
291
|
const targetText = target ? ` ${colorize(`→ ${target.label}`, "dim")}${target.local ? "" : ` ${colorize("(remote, allowed)", "yellow")}`}` : "";
|
|
265
292
|
console.log(`
|
|
266
|
-
${colorize(
|
|
293
|
+
${colorize(`\uD83C\uDF31 Running ${name}`, "cyan", "bold")}${countText}${targetText}
|
|
267
294
|
`);
|
|
268
295
|
}
|
|
269
296
|
function printSeederSkipped(failedDeps) {
|
|
@@ -271,11 +298,36 @@ function printSeederSkipped(failedDeps) {
|
|
|
271
298
|
console.log(colorize(` ⊘ Skipped (depends on failed: ${failedDeps.join(", ")})`, "yellow"));
|
|
272
299
|
console.log("");
|
|
273
300
|
}
|
|
274
|
-
function printSummary(results) {
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
301
|
+
function printSummary(results, totalDurationMs, concurrency = 1) {
|
|
302
|
+
let completed = 0;
|
|
303
|
+
let failed = 0;
|
|
304
|
+
let skipped = 0;
|
|
305
|
+
let pending = 0;
|
|
306
|
+
let cachedCount = 0;
|
|
307
|
+
let totalWorkMs = 0;
|
|
308
|
+
for (const r of results) {
|
|
309
|
+
switch (r.status) {
|
|
310
|
+
case "completed":
|
|
311
|
+
completed++;
|
|
312
|
+
cachedCount += r.cachedSteps.length;
|
|
313
|
+
totalWorkMs += r.durationMs;
|
|
314
|
+
break;
|
|
315
|
+
case "failed":
|
|
316
|
+
failed++;
|
|
317
|
+
cachedCount += r.cachedSteps.length;
|
|
318
|
+
totalWorkMs += r.durationMs;
|
|
319
|
+
break;
|
|
320
|
+
case "skipped":
|
|
321
|
+
skipped++;
|
|
322
|
+
break;
|
|
323
|
+
case "pending":
|
|
324
|
+
pending++;
|
|
325
|
+
break;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
const durationSuffix = totalDurationMs !== undefined ? ` in ${formatDuration(totalDurationMs)}` : "";
|
|
329
|
+
const speedupSuffix = concurrency > 1 && totalDurationMs !== undefined && totalDurationMs > 0 && totalWorkMs > totalDurationMs * 1.1 ? ` ${colorize(`(${formatDuration(totalWorkMs)} work, ${(totalWorkMs / totalDurationMs).toFixed(1)}× faster)`, "dim")}` : "";
|
|
330
|
+
const cacheSuffix = cachedCount > 0 ? ` ${colorize(`(${cachedCount} cached ${cachedCount === 1 ? "step" : "steps"})`, "cyan")}` : "";
|
|
279
331
|
if (failed > 0 || skipped > 0) {
|
|
280
332
|
const parts = [`${completed} completed`];
|
|
281
333
|
if (failed > 0)
|
|
@@ -284,13 +336,358 @@ function printSummary(results) {
|
|
|
284
336
|
parts.push(`${skipped} skipped`);
|
|
285
337
|
if (pending > 0)
|
|
286
338
|
parts.push(`${pending} pending`);
|
|
287
|
-
console.log(colorize(`Seeding failed: ${parts.join(", ")}`, "red"));
|
|
339
|
+
console.log(colorize(`Seeding failed: ${parts.join(", ")}${durationSuffix}`, "red"));
|
|
288
340
|
} else {
|
|
289
|
-
console.log(`${colorize("✓ Seeding complete:", "green")} ${completed} seeders executed successfully
|
|
341
|
+
console.log(`${colorize("✓ Seeding complete:", "green")} ${completed} ${completed === 1 ? "seeder" : "seeders"} executed successfully${durationSuffix}${speedupSuffix}${cacheSuffix}
|
|
290
342
|
`);
|
|
291
343
|
}
|
|
292
344
|
}
|
|
293
345
|
|
|
346
|
+
// src/seeding-state.ts
|
|
347
|
+
var key = Symbol.for("plantr.seedingActive");
|
|
348
|
+
var countKey = Symbol.for("plantr.seedingCount");
|
|
349
|
+
var state = globalThis;
|
|
350
|
+
function isSeedingActive() {
|
|
351
|
+
return state[key] === true;
|
|
352
|
+
}
|
|
353
|
+
function enterSeeding() {
|
|
354
|
+
const next = (state[countKey] ?? 0) + 1;
|
|
355
|
+
state[countKey] = next;
|
|
356
|
+
state[key] = true;
|
|
357
|
+
}
|
|
358
|
+
function exitSeeding() {
|
|
359
|
+
const next = Math.max(0, (state[countKey] ?? 0) - 1);
|
|
360
|
+
state[countKey] = next;
|
|
361
|
+
state[key] = next > 0;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// src/run-seeders.ts
|
|
365
|
+
class SeedTargetError extends Error {
|
|
366
|
+
constructor(label) {
|
|
367
|
+
super(`Refusing to seed ${label}: it is not a local database. Pass allowRemote (CLI: --allow-remote) to seed it on purpose.`);
|
|
368
|
+
this.name = "SeedTargetError";
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
var isLocalHost = (hostPort) => {
|
|
372
|
+
if (hostPort.startsWith("/"))
|
|
373
|
+
return true;
|
|
374
|
+
const lower = hostPort.toLowerCase();
|
|
375
|
+
const bracketed = /^\[([^\]]*)\]/.exec(lower);
|
|
376
|
+
const hasPort = bracketed ? /:\d+$/.test(lower.slice(bracketed[0].length)) : /:\d+$/.test(lower);
|
|
377
|
+
const host = bracketed ? bracketed[1] ?? "" : lower.replace(/:\d+$/, "");
|
|
378
|
+
return host === "localhost" || host === "::1" || host === "0.0.0.0" || host === "host.docker.internal" || host.endsWith(".localhost") || /^127\./.test(host) || hasPort && host.length > 0 && !/[.:]/.test(host);
|
|
379
|
+
};
|
|
380
|
+
function describeTarget(target) {
|
|
381
|
+
if (/^file:/i.test(target))
|
|
382
|
+
return { label: target.replace(/[?#].*$/, ""), local: true };
|
|
383
|
+
const scheme = /^[a-z][\w+.-]*:\/\//i.exec(target);
|
|
384
|
+
if (!scheme)
|
|
385
|
+
return { label: "a target that is not a URL", local: false };
|
|
386
|
+
const rest = target.slice(scheme[0].length);
|
|
387
|
+
const queryStart = rest.search(/[?#]/);
|
|
388
|
+
const beforeQuery = queryStart === -1 ? rest : rest.slice(0, queryStart);
|
|
389
|
+
const query = queryStart === -1 ? "" : rest.slice(queryStart);
|
|
390
|
+
const authorityAndPath = beforeQuery.slice(beforeQuery.lastIndexOf("@") + 1);
|
|
391
|
+
const pathStart = authorityAndPath.search(/[/;]/);
|
|
392
|
+
const authority = pathStart === -1 ? authorityAndPath : authorityAndPath.slice(0, pathStart);
|
|
393
|
+
const path = pathStart === -1 ? "" : authorityAndPath.slice(pathStart);
|
|
394
|
+
let hosts = authority.split(",").filter(Boolean);
|
|
395
|
+
const hostParam = /[?&;]host=([^&;#]*)/i.exec(`${query}${path.startsWith(";") ? path : ""}`)?.[1];
|
|
396
|
+
if (hostParam) {
|
|
397
|
+
try {
|
|
398
|
+
hosts = decodeURIComponent(hostParam).split(",").filter(Boolean);
|
|
399
|
+
} catch {
|
|
400
|
+
return { label: "a target with an invalid host parameter", local: false };
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
const pathWithoutParams = path.startsWith("/") ? path.split(";", 1)[0] ?? "" : "";
|
|
404
|
+
const pathLabel = pathWithoutParams.length > 1 ? pathWithoutParams : "";
|
|
405
|
+
const label = `${hosts.join(",") || "local socket"}${pathLabel}`;
|
|
406
|
+
return { label, local: hosts.every(isLocalHost) };
|
|
407
|
+
}
|
|
408
|
+
async function runSeedersCore(seeders, config, options = {}) {
|
|
409
|
+
const {
|
|
410
|
+
printResults = true,
|
|
411
|
+
verbose = true,
|
|
412
|
+
continueOnFailure = false,
|
|
413
|
+
only,
|
|
414
|
+
fresh = false,
|
|
415
|
+
allowRemote = false,
|
|
416
|
+
concurrency = 1
|
|
417
|
+
} = options;
|
|
418
|
+
if (Number.isNaN(concurrency) || concurrency < 1 || Number.isFinite(concurrency) && !Number.isInteger(concurrency)) {
|
|
419
|
+
throw new RangeError(`Invalid concurrency (${String(concurrency)}): expected a positive integer or Infinity`);
|
|
420
|
+
}
|
|
421
|
+
const orderedNames = resolveDependencyOrder(seeders, only);
|
|
422
|
+
const seederMap = new Map;
|
|
423
|
+
for (const seeder of seeders) {
|
|
424
|
+
seederMap.set(seeder.name, seeder);
|
|
425
|
+
}
|
|
426
|
+
const freshSet = Array.isArray(fresh) ? new Set(fresh) : undefined;
|
|
427
|
+
if (freshSet) {
|
|
428
|
+
for (const name of freshSet) {
|
|
429
|
+
if (!seederMap.has(name))
|
|
430
|
+
throw new UnknownSeederError(name, [...seederMap.keys()]);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
const targetUrl = config.target?.();
|
|
434
|
+
const target = targetUrl ? describeTarget(targetUrl) : undefined;
|
|
435
|
+
if (target && !target.local && !allowRemote) {
|
|
436
|
+
throw new SeedTargetError(target.label);
|
|
437
|
+
}
|
|
438
|
+
const isFresh = (name) => fresh === true || (freshSet?.has(name) ?? false);
|
|
439
|
+
const results = orderedNames.map((name) => ({
|
|
440
|
+
name,
|
|
441
|
+
status: "pending"
|
|
442
|
+
}));
|
|
443
|
+
const resultIndex = new Map;
|
|
444
|
+
for (let i = 0;i < orderedNames.length; i++) {
|
|
445
|
+
resultIndex.set(orderedNames[i], i);
|
|
446
|
+
}
|
|
447
|
+
const outputs = {};
|
|
448
|
+
const failedSeeders = new Set;
|
|
449
|
+
const concurrent = concurrency > 1;
|
|
450
|
+
enterSeeding();
|
|
451
|
+
try {
|
|
452
|
+
if (verbose) {
|
|
453
|
+
printStartBanner({
|
|
454
|
+
name: config.bannerName,
|
|
455
|
+
count: orderedNames.length,
|
|
456
|
+
target,
|
|
457
|
+
concurrency
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
const runStartTime = performance.now();
|
|
461
|
+
if (config.onBeforeAll) {
|
|
462
|
+
await config.onBeforeAll();
|
|
463
|
+
}
|
|
464
|
+
let ctx;
|
|
465
|
+
try {
|
|
466
|
+
if (config.preloadCache) {
|
|
467
|
+
await config.preloadCache();
|
|
468
|
+
}
|
|
469
|
+
ctx = await config.context();
|
|
470
|
+
const activeCtx = ctx;
|
|
471
|
+
const executeSeeder = async (name) => {
|
|
472
|
+
const idx = resultIndex.get(name);
|
|
473
|
+
const seeder = seederMap.get(name);
|
|
474
|
+
if (idx === undefined || !seeder)
|
|
475
|
+
return true;
|
|
476
|
+
const scopeHandle = config.createSeederScope ? config.createSeederScope({ name, fresh: isFresh(name), concurrent }) : {
|
|
477
|
+
record: config.beforeSeeder?.(name, { fresh: isFresh(name) }),
|
|
478
|
+
run: (fn) => fn()
|
|
479
|
+
};
|
|
480
|
+
const deps = {};
|
|
481
|
+
for (const depName of seeder.dependsOn) {
|
|
482
|
+
deps[depName] = outputs[depName];
|
|
483
|
+
}
|
|
484
|
+
const startTime = performance.now();
|
|
485
|
+
try {
|
|
486
|
+
const output = await scopeHandle.run(async () => seeder.run(activeCtx, deps));
|
|
487
|
+
const durationMs = Math.round(performance.now() - startTime);
|
|
488
|
+
outputs[name] = output;
|
|
489
|
+
results[idx] = {
|
|
490
|
+
name,
|
|
491
|
+
status: "completed",
|
|
492
|
+
durationMs,
|
|
493
|
+
output,
|
|
494
|
+
cachedSteps: scopeHandle.record?.cachedSteps ?? []
|
|
495
|
+
};
|
|
496
|
+
if (verbose) {
|
|
497
|
+
if (concurrent) {
|
|
498
|
+
printConcurrentComplete(name, durationMs, true);
|
|
499
|
+
} else {
|
|
500
|
+
printSeederComplete(durationMs, true);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
return true;
|
|
504
|
+
} catch (error) {
|
|
505
|
+
const durationMs = Math.round(performance.now() - startTime);
|
|
506
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
507
|
+
const failedStep = scopeHandle.record?.failed && scopeHandle.record.failed.error === error ? scopeHandle.record.failed.step : undefined;
|
|
508
|
+
results[idx] = {
|
|
509
|
+
name,
|
|
510
|
+
status: "failed",
|
|
511
|
+
durationMs,
|
|
512
|
+
error: err,
|
|
513
|
+
...failedStep !== undefined ? { failedStep } : {},
|
|
514
|
+
cachedSteps: scopeHandle.record?.cachedSteps ?? []
|
|
515
|
+
};
|
|
516
|
+
failedSeeders.add(name);
|
|
517
|
+
if (verbose) {
|
|
518
|
+
if (concurrent) {
|
|
519
|
+
printConcurrentComplete(name, durationMs, false);
|
|
520
|
+
} else {
|
|
521
|
+
printSeederComplete(durationMs, false);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
return false;
|
|
525
|
+
}
|
|
526
|
+
};
|
|
527
|
+
if (!concurrent) {
|
|
528
|
+
for (let i = 0;i < orderedNames.length; i++) {
|
|
529
|
+
const name = orderedNames[i];
|
|
530
|
+
if (!name)
|
|
531
|
+
continue;
|
|
532
|
+
const seeder = seederMap.get(name);
|
|
533
|
+
if (!seeder)
|
|
534
|
+
continue;
|
|
535
|
+
if (continueOnFailure) {
|
|
536
|
+
const failedDeps = seeder.dependsOn.filter((dep) => failedSeeders.has(dep));
|
|
537
|
+
if (failedDeps.length > 0) {
|
|
538
|
+
results[i] = { name, status: "skipped", failedDeps };
|
|
539
|
+
failedSeeders.add(name);
|
|
540
|
+
if (verbose) {
|
|
541
|
+
printSeederHeader(name, i, orderedNames.length, seeder.description);
|
|
542
|
+
printSeederSkipped(failedDeps);
|
|
543
|
+
}
|
|
544
|
+
continue;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
if (verbose) {
|
|
548
|
+
printSeederHeader(name, i, orderedNames.length, seeder.description);
|
|
549
|
+
}
|
|
550
|
+
const ok = await executeSeeder(name);
|
|
551
|
+
if (!ok && !continueOnFailure) {
|
|
552
|
+
break;
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
} else if (orderedNames.length > 0) {
|
|
556
|
+
const remainingDeps = new Map;
|
|
557
|
+
const dependents = new Map;
|
|
558
|
+
for (const name of orderedNames) {
|
|
559
|
+
remainingDeps.set(name, 0);
|
|
560
|
+
dependents.set(name, []);
|
|
561
|
+
}
|
|
562
|
+
for (const name of orderedNames) {
|
|
563
|
+
const seeder = seederMap.get(name);
|
|
564
|
+
if (!seeder)
|
|
565
|
+
continue;
|
|
566
|
+
const uniqueDeps = new Set(seeder.dependsOn);
|
|
567
|
+
remainingDeps.set(name, uniqueDeps.size);
|
|
568
|
+
for (const dep of uniqueDeps) {
|
|
569
|
+
dependents.get(dep)?.push(name);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
const criticalHeight = new Map;
|
|
573
|
+
for (let i = orderedNames.length - 1;i >= 0; i--) {
|
|
574
|
+
const name = orderedNames[i];
|
|
575
|
+
let maxHeight = 0;
|
|
576
|
+
for (const dependent of dependents.get(name) ?? []) {
|
|
577
|
+
const h = (criticalHeight.get(dependent) ?? 0) + 1;
|
|
578
|
+
if (h > maxHeight)
|
|
579
|
+
maxHeight = h;
|
|
580
|
+
}
|
|
581
|
+
criticalHeight.set(name, maxHeight);
|
|
582
|
+
}
|
|
583
|
+
const ready = [];
|
|
584
|
+
for (const name of orderedNames) {
|
|
585
|
+
if (remainingDeps.get(name) === 0) {
|
|
586
|
+
ready.push(name);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
const popHighestPriority = () => {
|
|
590
|
+
let bestIdx = 0;
|
|
591
|
+
let bestHeight = criticalHeight.get(ready[0]) ?? 0;
|
|
592
|
+
let bestOrder = resultIndex.get(ready[0]) ?? 0;
|
|
593
|
+
for (let i = 1;i < ready.length; i++) {
|
|
594
|
+
const candidate = ready[i];
|
|
595
|
+
const h = criticalHeight.get(candidate) ?? 0;
|
|
596
|
+
const order = resultIndex.get(candidate) ?? 0;
|
|
597
|
+
if (h > bestHeight || h === bestHeight && order < bestOrder) {
|
|
598
|
+
bestIdx = i;
|
|
599
|
+
bestHeight = h;
|
|
600
|
+
bestOrder = order;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
return ready.splice(bestIdx, 1)[0];
|
|
604
|
+
};
|
|
605
|
+
await new Promise((resolve) => {
|
|
606
|
+
let inFlight = 0;
|
|
607
|
+
let stopped = false;
|
|
608
|
+
const markSettled = (settledName) => {
|
|
609
|
+
const deps = dependents.get(settledName);
|
|
610
|
+
if (!deps)
|
|
611
|
+
return;
|
|
612
|
+
for (const dependent of deps) {
|
|
613
|
+
const next = (remainingDeps.get(dependent) ?? 1) - 1;
|
|
614
|
+
remainingDeps.set(dependent, next);
|
|
615
|
+
if (next !== 0 || stopped)
|
|
616
|
+
continue;
|
|
617
|
+
const seeder = seederMap.get(dependent);
|
|
618
|
+
if (!seeder)
|
|
619
|
+
continue;
|
|
620
|
+
const failedDeps = seeder.dependsOn.filter((d) => failedSeeders.has(d));
|
|
621
|
+
if (failedDeps.length > 0) {
|
|
622
|
+
const idx = resultIndex.get(dependent);
|
|
623
|
+
if (idx !== undefined) {
|
|
624
|
+
results[idx] = { name: dependent, status: "skipped", failedDeps };
|
|
625
|
+
}
|
|
626
|
+
failedSeeders.add(dependent);
|
|
627
|
+
if (verbose) {
|
|
628
|
+
printConcurrentSkipped(dependent, failedDeps);
|
|
629
|
+
}
|
|
630
|
+
markSettled(dependent);
|
|
631
|
+
} else {
|
|
632
|
+
ready.push(dependent);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
};
|
|
636
|
+
const schedule = () => {
|
|
637
|
+
while (!stopped && inFlight < concurrency && ready.length > 0) {
|
|
638
|
+
const name = popHighestPriority();
|
|
639
|
+
inFlight++;
|
|
640
|
+
executeSeeder(name).then((ok) => {
|
|
641
|
+
inFlight--;
|
|
642
|
+
if (!ok && !continueOnFailure) {
|
|
643
|
+
stopped = true;
|
|
644
|
+
} else {
|
|
645
|
+
markSettled(name);
|
|
646
|
+
}
|
|
647
|
+
schedule();
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
if (inFlight === 0 && (stopped || ready.length === 0)) {
|
|
651
|
+
resolve();
|
|
652
|
+
}
|
|
653
|
+
};
|
|
654
|
+
schedule();
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
if (printResults) {
|
|
658
|
+
printResultsTable(results);
|
|
659
|
+
printErrors(results);
|
|
660
|
+
printSummary(results, performance.now() - runStartTime, concurrency);
|
|
661
|
+
}
|
|
662
|
+
} finally {
|
|
663
|
+
try {
|
|
664
|
+
if (config.flushCache) {
|
|
665
|
+
await config.flushCache();
|
|
666
|
+
}
|
|
667
|
+
} finally {
|
|
668
|
+
if (config.onAfterAll) {
|
|
669
|
+
await config.onAfterAll(ctx);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
} finally {
|
|
674
|
+
exitSeeding();
|
|
675
|
+
}
|
|
676
|
+
const hasFailure = results.some((r) => r.status === "failed");
|
|
677
|
+
if (hasFailure) {
|
|
678
|
+
return {
|
|
679
|
+
success: false,
|
|
680
|
+
results,
|
|
681
|
+
outputs
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
return {
|
|
685
|
+
success: true,
|
|
686
|
+
results,
|
|
687
|
+
outputs
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
|
|
294
691
|
// src/cli.ts
|
|
295
692
|
var USAGE_ERRORS = new Set([
|
|
296
693
|
"CircularDependencyError",
|
|
@@ -299,7 +696,19 @@ var USAGE_ERRORS = new Set([
|
|
|
299
696
|
"UnknownSeederError",
|
|
300
697
|
"SeedTargetError"
|
|
301
698
|
]);
|
|
302
|
-
|
|
699
|
+
function formatSeedersList(seeders) {
|
|
700
|
+
if (seeders.length === 0)
|
|
701
|
+
return "No seeders registered.";
|
|
702
|
+
const maxLen = Math.max(...seeders.map((s) => s.name.length));
|
|
703
|
+
const lines = seeders.map((s) => {
|
|
704
|
+
const desc = s.description ? ` ${colorize(s.description, "dim")}` : "";
|
|
705
|
+
return ` ${s.name.padEnd(maxLen)}${desc}`;
|
|
706
|
+
});
|
|
707
|
+
return `${colorize(`Registered seeders (${seeders.length}):`, "white", "bold")}
|
|
708
|
+
${lines.join(`
|
|
709
|
+
`)}`;
|
|
710
|
+
}
|
|
711
|
+
var helpText = (seeders) => `
|
|
303
712
|
${colorize("Usage:", "cyan", "bold")} bun run seed [seeder...] [options]
|
|
304
713
|
|
|
305
714
|
${colorize("Arguments:", "white", "bold")}
|
|
@@ -309,59 +718,133 @@ ${colorize("Options:", "white", "bold")}
|
|
|
309
718
|
--only a,b Same as naming the seeders
|
|
310
719
|
--fresh Ignore and overwrite cached steps of the named seeders
|
|
311
720
|
(of every seeder when none are named)
|
|
721
|
+
--concurrency, -c <n> Run up to <n> independent seeders in parallel (default: 1)
|
|
312
722
|
--continue-on-failure Keep running seeders that do not depend on a failed one
|
|
313
723
|
--allow-remote Seed a database that is not local
|
|
724
|
+
--quiet, -q Suppress progress and step output (keep results table)
|
|
314
725
|
--dry-run Show execution order without running seeders
|
|
726
|
+
--list, -l List registered seeders in dependency order and exit
|
|
315
727
|
--help, -h Show this help message
|
|
316
728
|
|
|
317
|
-
${
|
|
729
|
+
${formatSeedersList(seeders)}
|
|
318
730
|
`;
|
|
319
|
-
async function runCli(seeders, runSeeders, {
|
|
731
|
+
async function runCli(seeders, runSeeders, {
|
|
732
|
+
argv,
|
|
733
|
+
target,
|
|
734
|
+
defaultConcurrency
|
|
735
|
+
}) {
|
|
320
736
|
let parsed;
|
|
321
737
|
try {
|
|
322
738
|
parsed = parse(argv);
|
|
323
739
|
} catch (error) {
|
|
324
740
|
console.error(colorize(error instanceof Error ? error.message : String(error), "red"));
|
|
325
|
-
console.log(helpText(seeders
|
|
741
|
+
console.log(helpText(seeders));
|
|
326
742
|
return 1;
|
|
327
743
|
}
|
|
328
744
|
const { values, positionals } = parsed;
|
|
329
745
|
if (values.help) {
|
|
330
|
-
console.log(helpText(seeders
|
|
746
|
+
console.log(helpText(seeders));
|
|
331
747
|
return 0;
|
|
332
748
|
}
|
|
749
|
+
let concurrency;
|
|
750
|
+
if (values.concurrency !== undefined) {
|
|
751
|
+
const parsedConcurrency = values.concurrency.toLowerCase() === "infinity" ? Number.POSITIVE_INFINITY : Number(values.concurrency);
|
|
752
|
+
if (Number.isNaN(parsedConcurrency) || parsedConcurrency < 1 || Number.isFinite(parsedConcurrency) && !Number.isInteger(parsedConcurrency)) {
|
|
753
|
+
console.error(colorize(`Invalid --concurrency value "${values.concurrency}": expected a positive integer`, "red"));
|
|
754
|
+
return 1;
|
|
755
|
+
}
|
|
756
|
+
concurrency = parsedConcurrency;
|
|
757
|
+
}
|
|
333
758
|
const names = [...positionals, ...(values.only ?? []).flatMap((value) => value.split(","))].map((value) => value.trim()).filter(Boolean);
|
|
334
759
|
const only = names.length > 0 ? names : undefined;
|
|
335
760
|
try {
|
|
336
|
-
|
|
761
|
+
if (values.list) {
|
|
762
|
+
const order = resolveDependencyOrder(seeders, only);
|
|
763
|
+
const seederMap = new Map(seeders.map((s) => [s.name, s]));
|
|
764
|
+
console.log(`
|
|
765
|
+
${colorize("\uD83C\uDF31 Seeders", "cyan", "bold")} ${colorize(`(${order.length})`, "dim")}
|
|
766
|
+
`);
|
|
767
|
+
const maxLen = Math.max(0, ...order.map((n) => n.length));
|
|
768
|
+
for (const seederName of order) {
|
|
769
|
+
const seeder = seederMap.get(seederName);
|
|
770
|
+
const desc = seeder?.description ? ` ${colorize(seeder.description, "dim")}` : "";
|
|
771
|
+
const deps = seeder?.dependsOn ?? [];
|
|
772
|
+
const depsStr = deps.length > 0 ? ` ${colorize(`[depends on: ${deps.join(", ")}]`, "dim")}` : "";
|
|
773
|
+
console.log(` ${seederName.padEnd(maxLen)}${desc}${depsStr}`);
|
|
774
|
+
}
|
|
775
|
+
console.log("");
|
|
776
|
+
return 0;
|
|
777
|
+
}
|
|
337
778
|
if (values["dry-run"]) {
|
|
779
|
+
const order = resolveDependencyOrder(seeders, only);
|
|
780
|
+
const seederMap = new Map(seeders.map((s) => [s.name, s]));
|
|
781
|
+
const targetUrl = target?.();
|
|
782
|
+
const targetDesc = targetUrl ? describeTarget(targetUrl) : undefined;
|
|
783
|
+
const targetText = targetDesc ? ` ${colorize(`→ ${targetDesc.label}`, "dim")}${targetDesc.local ? "" : ` ${colorize("(remote)", "yellow")}`}` : "";
|
|
784
|
+
const freshSet = values.fresh ? only ? new Set(only) : true : false;
|
|
785
|
+
const effectiveConcurrency = concurrency ?? defaultConcurrency ?? 1;
|
|
786
|
+
const concurrencyText = effectiveConcurrency > 1 ? `, concurrency: ${effectiveConcurrency === Number.POSITIVE_INFINITY ? "∞" : effectiveConcurrency}` : "";
|
|
338
787
|
console.log(`
|
|
339
|
-
${colorize("\uD83C\uDF31 Dry Run", "cyan", "bold")} ${colorize(`(${order.length} seeders)`, "dim")}
|
|
788
|
+
${colorize("\uD83C\uDF31 Dry Run", "cyan", "bold")} ${colorize(`(${order.length} ${order.length === 1 ? "seeder" : "seeders"}${concurrencyText})`, "dim")}${targetText}
|
|
340
789
|
`);
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
const deps =
|
|
790
|
+
const printItem = (seederName, num, indent) => {
|
|
791
|
+
const seeder = seederMap.get(seederName);
|
|
792
|
+
const deps = seeder?.dependsOn ?? [];
|
|
344
793
|
const depsStr = deps.length > 0 ? ` ${colorize(`(depends on: ${deps.join(", ")})`, "dim")}` : "";
|
|
345
|
-
|
|
346
|
-
|
|
794
|
+
const freshStr = freshSet === true || freshSet instanceof Set && freshSet.has(seederName) ? ` ${colorize("(fresh)", "yellow")}` : "";
|
|
795
|
+
console.log(`${indent}${num}. ${seederName}${depsStr}${freshStr}`);
|
|
796
|
+
if (seeder?.description) {
|
|
797
|
+
console.log(`${indent} ${colorize(seeder.description, "dim")}`);
|
|
798
|
+
}
|
|
799
|
+
};
|
|
800
|
+
if (effectiveConcurrency > 1 && order.length > 0) {
|
|
801
|
+
const waveOf = new Map;
|
|
802
|
+
const waves = [];
|
|
803
|
+
for (const seederName of order) {
|
|
804
|
+
const deps = seederMap.get(seederName)?.dependsOn ?? [];
|
|
805
|
+
let wave = 0;
|
|
806
|
+
for (const dep of deps) {
|
|
807
|
+
wave = Math.max(wave, (waveOf.get(dep) ?? 0) + 1);
|
|
808
|
+
}
|
|
809
|
+
waveOf.set(seederName, wave);
|
|
810
|
+
let bucket = waves[wave];
|
|
811
|
+
if (!bucket) {
|
|
812
|
+
bucket = [];
|
|
813
|
+
waves[wave] = bucket;
|
|
814
|
+
}
|
|
815
|
+
bucket.push(seederName);
|
|
816
|
+
}
|
|
817
|
+
console.log(colorize(`Execution plan (${waves.length} ${waves.length === 1 ? "wave" : "waves"}):`, "white", "bold"));
|
|
818
|
+
let index = 1;
|
|
819
|
+
waves.forEach((waveSeeders, waveIdx) => {
|
|
820
|
+
const parallelTag = waveSeeders.length > 1 ? ` ${colorize("(parallel)", "cyan")}` : "";
|
|
821
|
+
console.log(` ${colorize(`Wave ${waveIdx + 1}`, "white", "bold")}${parallelTag}`);
|
|
822
|
+
for (const seederName of waveSeeders) {
|
|
823
|
+
printItem(seederName, index++, " ");
|
|
824
|
+
}
|
|
825
|
+
});
|
|
826
|
+
} else {
|
|
827
|
+
console.log(colorize("Execution order:", "white", "bold"));
|
|
828
|
+
order.forEach((seederName, i) => {
|
|
829
|
+
printItem(seederName, i + 1, " ");
|
|
830
|
+
});
|
|
831
|
+
}
|
|
347
832
|
console.log("");
|
|
348
833
|
return 0;
|
|
349
834
|
}
|
|
350
|
-
console.log(`
|
|
351
|
-
${colorize(`\uD83C\uDF31 Running ${name}`, "cyan", "bold")} ${colorize(`(${order.length} seeders)`, "dim")}
|
|
352
|
-
`);
|
|
353
835
|
const { success } = await runSeeders(seeders, {
|
|
354
836
|
printResults: true,
|
|
355
|
-
verbose:
|
|
837
|
+
verbose: !values.quiet,
|
|
356
838
|
only,
|
|
357
839
|
fresh: values.fresh ? only ?? true : false,
|
|
358
840
|
continueOnFailure: values["continue-on-failure"],
|
|
359
|
-
allowRemote: values["allow-remote"]
|
|
841
|
+
allowRemote: values["allow-remote"],
|
|
842
|
+
concurrency
|
|
360
843
|
});
|
|
361
844
|
return success ? 0 : 1;
|
|
362
845
|
} catch (error) {
|
|
363
846
|
const usage = error instanceof Error && USAGE_ERRORS.has(error.name);
|
|
364
|
-
console.error(colorize(usage ? error.message :
|
|
847
|
+
console.error(colorize(usage ? error.message : inspectValue(error), "red"));
|
|
365
848
|
return 1;
|
|
366
849
|
}
|
|
367
850
|
}
|
|
@@ -372,6 +855,9 @@ function parse(argv) {
|
|
|
372
855
|
strict: true,
|
|
373
856
|
options: {
|
|
374
857
|
help: { type: "boolean", short: "h" },
|
|
858
|
+
list: { type: "boolean", short: "l" },
|
|
859
|
+
quiet: { type: "boolean", short: "q" },
|
|
860
|
+
concurrency: { type: "string", short: "c" },
|
|
375
861
|
"dry-run": { type: "boolean" },
|
|
376
862
|
only: { type: "string", multiple: true },
|
|
377
863
|
fresh: { type: "boolean" },
|
|
@@ -384,7 +870,9 @@ function parse(argv) {
|
|
|
384
870
|
// src/define-seeder.ts
|
|
385
871
|
function createDefineSeeder() {
|
|
386
872
|
return function defineSeeder(config) {
|
|
387
|
-
const dependsOnNames =
|
|
873
|
+
const dependsOnNames = [
|
|
874
|
+
...new Set((config.dependsOn ?? []).map((seeder) => seeder.name))
|
|
875
|
+
];
|
|
388
876
|
return {
|
|
389
877
|
name: config.name,
|
|
390
878
|
description: config.description,
|
|
@@ -394,263 +882,574 @@ function createDefineSeeder() {
|
|
|
394
882
|
};
|
|
395
883
|
}
|
|
396
884
|
|
|
397
|
-
// src/
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
885
|
+
// src/expect.ts
|
|
886
|
+
import assert, { AssertionError } from "node:assert/strict";
|
|
887
|
+
import { createRequire } from "node:module";
|
|
888
|
+
function isPlainObject(value) {
|
|
889
|
+
const proto = Object.getPrototypeOf(value);
|
|
890
|
+
return proto === Object.prototype || proto === null;
|
|
891
|
+
}
|
|
892
|
+
function normalizeForEqual(value, seen = new WeakMap) {
|
|
893
|
+
if (value === null || typeof value !== "object")
|
|
894
|
+
return value;
|
|
895
|
+
if (seen.has(value))
|
|
896
|
+
return seen.get(value);
|
|
897
|
+
if (Array.isArray(value)) {
|
|
898
|
+
const normalized = new Array(value.length);
|
|
899
|
+
seen.set(value, normalized);
|
|
900
|
+
for (let i = 0;i < value.length; i++) {
|
|
901
|
+
normalized[i] = normalizeForEqual(value[i], seen);
|
|
902
|
+
}
|
|
903
|
+
return normalized;
|
|
904
|
+
}
|
|
905
|
+
if (isPlainObject(value)) {
|
|
906
|
+
const normalized = Object.getPrototypeOf(value) === null ? Object.create(null) : {};
|
|
907
|
+
seen.set(value, normalized);
|
|
908
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
909
|
+
const desc = Object.getOwnPropertyDescriptor(value, key);
|
|
910
|
+
if (!desc?.enumerable)
|
|
911
|
+
continue;
|
|
912
|
+
const entryValue = value[key];
|
|
913
|
+
if (entryValue !== undefined) {
|
|
914
|
+
normalized[key] = normalizeForEqual(entryValue, seen);
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
return normalized;
|
|
402
918
|
}
|
|
919
|
+
return value;
|
|
403
920
|
}
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
return true;
|
|
407
|
-
const lower = hostPort.toLowerCase();
|
|
408
|
-
const bracketed = /^\[([^\]]*)\]/.exec(lower);
|
|
409
|
-
const host = bracketed ? bracketed[1] ?? "" : lower.replace(/:\d+$/, "");
|
|
410
|
-
return host === "::1" || host === "0.0.0.0" || host === "host.docker.internal" || host.endsWith(".localhost") || /^127\./.test(host) || !/[.:]/.test(host);
|
|
411
|
-
};
|
|
412
|
-
function describeTarget(target) {
|
|
413
|
-
if (/^file:/i.test(target))
|
|
414
|
-
return { label: target.replace(/[?#].*$/, ""), local: true };
|
|
415
|
-
const scheme = /^[a-z][\w+.-]*:\/\//i.exec(target);
|
|
416
|
-
if (!scheme)
|
|
417
|
-
return { label: "a target that is not a URL", local: false };
|
|
418
|
-
const rest = target.slice(scheme[0].length);
|
|
419
|
-
const queryStart = rest.search(/[?#]/);
|
|
420
|
-
const beforeQuery = queryStart === -1 ? rest : rest.slice(0, queryStart);
|
|
421
|
-
const query = queryStart === -1 ? "" : rest.slice(queryStart);
|
|
422
|
-
const authorityAndPath = beforeQuery.slice(beforeQuery.lastIndexOf("@") + 1);
|
|
423
|
-
const [authority = "", path = ""] = authorityAndPath.split(/(?=[/;])/, 2);
|
|
424
|
-
let hosts = authority.split(",").filter(Boolean);
|
|
425
|
-
const hostParam = /[?&;]host=([^&;#]*)/i.exec(`${query}${path.startsWith(";") ? path : ""}`)?.[1];
|
|
426
|
-
if (hostParam)
|
|
427
|
-
hosts = decodeURIComponent(hostParam).split(",").filter(Boolean);
|
|
428
|
-
const label = `${hosts.join(",") || "local socket"}${path.startsWith("/") ? path : ""}`;
|
|
429
|
-
return { label, local: hosts.every(isLocalHost) };
|
|
921
|
+
function sameValueZero(a, b) {
|
|
922
|
+
return a === b || Number.isNaN(a) && Number.isNaN(b);
|
|
430
923
|
}
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
verbose = true,
|
|
435
|
-
continueOnFailure = false,
|
|
436
|
-
only,
|
|
437
|
-
fresh = false,
|
|
438
|
-
allowRemote = false
|
|
439
|
-
} = options;
|
|
440
|
-
const orderedNames = resolveDependencyOrder(seeders, only);
|
|
441
|
-
const seederMap = new Map;
|
|
442
|
-
for (const seeder of seeders) {
|
|
443
|
-
seederMap.set(seeder.name, seeder);
|
|
924
|
+
function containsValue(actual, expected) {
|
|
925
|
+
if (typeof actual === "string") {
|
|
926
|
+
return typeof expected === "string" && actual.includes(expected);
|
|
444
927
|
}
|
|
445
|
-
if (Array.isArray(
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
928
|
+
if (Array.isArray(actual)) {
|
|
929
|
+
return actual.includes(expected);
|
|
930
|
+
}
|
|
931
|
+
if (actual instanceof Set) {
|
|
932
|
+
return actual.has(expected);
|
|
933
|
+
}
|
|
934
|
+
if (actual !== null && actual !== undefined && typeof actual[Symbol.iterator] === "function") {
|
|
935
|
+
for (const item of actual) {
|
|
936
|
+
if (sameValueZero(item, expected))
|
|
937
|
+
return true;
|
|
449
938
|
}
|
|
450
939
|
}
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
940
|
+
return false;
|
|
941
|
+
}
|
|
942
|
+
function matchesThrown(thrown, expected) {
|
|
943
|
+
if (typeof expected === "string") {
|
|
944
|
+
const errorMessage = thrown instanceof Error ? thrown.message : String(thrown);
|
|
945
|
+
return errorMessage.includes(expected);
|
|
455
946
|
}
|
|
456
|
-
if (
|
|
457
|
-
|
|
947
|
+
if (expected instanceof RegExp) {
|
|
948
|
+
const errorMessage = thrown instanceof Error ? thrown.message : String(thrown);
|
|
949
|
+
const re = expected.global || expected.sticky ? new RegExp(expected.source, expected.flags) : expected;
|
|
950
|
+
return re.test(errorMessage);
|
|
458
951
|
}
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
if (config.onBeforeAll) {
|
|
466
|
-
await config.onBeforeAll();
|
|
952
|
+
if (expected instanceof Error) {
|
|
953
|
+
if (!(thrown instanceof Error))
|
|
954
|
+
return false;
|
|
955
|
+
if (expected.constructor !== Error && !(thrown instanceof expected.constructor))
|
|
956
|
+
return false;
|
|
957
|
+
return thrown.message === expected.message;
|
|
467
958
|
}
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
959
|
+
if (typeof expected === "function") {
|
|
960
|
+
return thrown instanceof expected;
|
|
961
|
+
}
|
|
962
|
+
return false;
|
|
963
|
+
}
|
|
964
|
+
function failAssertion(defaultMessage, actual, expected, operator, customMessage) {
|
|
965
|
+
throw new AssertionError({
|
|
966
|
+
message: customMessage ?? defaultMessage,
|
|
967
|
+
actual,
|
|
968
|
+
expected,
|
|
969
|
+
operator
|
|
970
|
+
});
|
|
971
|
+
}
|
|
972
|
+
function createMatchers(actual, message, negated) {
|
|
973
|
+
const checkComparison = (expected, operator, label, compare) => {
|
|
974
|
+
if (typeof actual !== "number" && typeof actual !== "bigint") {
|
|
975
|
+
failAssertion(`Expected a number or bigint, received ${typeof actual} (${inspectValue(actual)})`, actual, expected, operator, message);
|
|
976
|
+
}
|
|
977
|
+
const passed = compare(actual, expected);
|
|
978
|
+
if (negated ? passed : !passed) {
|
|
979
|
+
failAssertion(`Expected ${inspectValue(actual)} ${negated ? "not " : ""}${label} ${inspectValue(expected)}`, actual, expected, negated ? `not ${operator}` : operator, message);
|
|
980
|
+
}
|
|
981
|
+
};
|
|
982
|
+
return {
|
|
983
|
+
get not() {
|
|
984
|
+
return createMatchers(actual, message, !negated);
|
|
985
|
+
},
|
|
986
|
+
toBe(expected) {
|
|
987
|
+
if (negated) {
|
|
988
|
+
assert.notStrictEqual(actual, expected, message);
|
|
989
|
+
} else {
|
|
990
|
+
assert.strictEqual(actual, expected, message);
|
|
991
|
+
}
|
|
992
|
+
},
|
|
993
|
+
toEqual(expected) {
|
|
994
|
+
const normActual = normalizeForEqual(actual);
|
|
995
|
+
const normExpected = normalizeForEqual(expected);
|
|
996
|
+
if (negated) {
|
|
997
|
+
try {
|
|
998
|
+
assert.notDeepStrictEqual(normActual, normExpected, message);
|
|
999
|
+
} catch (err) {
|
|
1000
|
+
if (err instanceof AssertionError) {
|
|
1001
|
+
failAssertion(err.message, actual, expected, "not toEqual", message);
|
|
1002
|
+
}
|
|
1003
|
+
throw err;
|
|
1004
|
+
}
|
|
1005
|
+
} else {
|
|
1006
|
+
try {
|
|
1007
|
+
assert.deepStrictEqual(normActual, normExpected, message);
|
|
1008
|
+
} catch (err) {
|
|
1009
|
+
if (err instanceof AssertionError) {
|
|
1010
|
+
failAssertion(err.message, actual, expected, "toEqual", message);
|
|
486
1011
|
}
|
|
487
|
-
|
|
1012
|
+
throw err;
|
|
488
1013
|
}
|
|
489
1014
|
}
|
|
490
|
-
|
|
491
|
-
|
|
1015
|
+
},
|
|
1016
|
+
toStrictEqual(expected) {
|
|
1017
|
+
if (negated) {
|
|
1018
|
+
assert.notDeepStrictEqual(actual, expected, message);
|
|
1019
|
+
} else {
|
|
1020
|
+
assert.deepStrictEqual(actual, expected, message);
|
|
492
1021
|
}
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
for (const depName of seeder.dependsOn) {
|
|
499
|
-
deps[depName] = outputs[depName];
|
|
1022
|
+
},
|
|
1023
|
+
toBeDefined() {
|
|
1024
|
+
const isDefined = actual !== undefined;
|
|
1025
|
+
if (negated ? isDefined : !isDefined) {
|
|
1026
|
+
failAssertion(negated ? `Expected ${inspectValue(actual)} to be undefined` : "Expected value to be defined, received undefined", actual, undefined, negated ? "not toBeDefined" : "toBeDefined", message);
|
|
500
1027
|
}
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
1028
|
+
},
|
|
1029
|
+
toBeUndefined() {
|
|
1030
|
+
if (negated) {
|
|
1031
|
+
assert.notStrictEqual(actual, undefined, message);
|
|
1032
|
+
} else {
|
|
1033
|
+
assert.strictEqual(actual, undefined, message);
|
|
1034
|
+
}
|
|
1035
|
+
},
|
|
1036
|
+
toBeNull() {
|
|
1037
|
+
if (negated) {
|
|
1038
|
+
assert.notStrictEqual(actual, null, message);
|
|
1039
|
+
} else {
|
|
1040
|
+
assert.strictEqual(actual, null, message);
|
|
1041
|
+
}
|
|
1042
|
+
},
|
|
1043
|
+
toBeTruthy() {
|
|
1044
|
+
const isTruthy = Boolean(actual);
|
|
1045
|
+
if (negated ? isTruthy : !isTruthy) {
|
|
1046
|
+
failAssertion(`Expected ${inspectValue(actual)} ${negated ? "not " : ""}to be truthy`, actual, !negated, negated ? "not toBeTruthy" : "toBeTruthy", message);
|
|
1047
|
+
}
|
|
1048
|
+
},
|
|
1049
|
+
toBeFalsy() {
|
|
1050
|
+
const isFalsy = !actual;
|
|
1051
|
+
if (negated ? isFalsy : !isFalsy) {
|
|
1052
|
+
failAssertion(`Expected ${inspectValue(actual)} ${negated ? "not " : ""}to be falsy`, actual, negated, negated ? "not toBeFalsy" : "toBeFalsy", message);
|
|
1053
|
+
}
|
|
1054
|
+
},
|
|
1055
|
+
toContain(expected) {
|
|
1056
|
+
const passed = containsValue(actual, expected);
|
|
1057
|
+
if (negated ? passed : !passed) {
|
|
1058
|
+
failAssertion(`Expected ${inspectValue(actual)} ${negated ? "not " : ""}to contain ${inspectValue(expected)}`, actual, expected, negated ? "not toContain" : "toContain", message);
|
|
1059
|
+
}
|
|
1060
|
+
},
|
|
1061
|
+
toHaveLength(length) {
|
|
1062
|
+
const actualLength = actual !== null && actual !== undefined ? actual.length : undefined;
|
|
1063
|
+
if (typeof actualLength !== "number") {
|
|
1064
|
+
failAssertion(`Expected ${inspectValue(actual)} to have a numeric length property`, actual, length, "toHaveLength", message);
|
|
1065
|
+
}
|
|
1066
|
+
if (negated) {
|
|
1067
|
+
if (actualLength === length) {
|
|
1068
|
+
failAssertion(`Expected ${inspectValue(actual)} not to have length ${length}`, actualLength, length, "not toHaveLength", message);
|
|
521
1069
|
}
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
1070
|
+
} else {
|
|
1071
|
+
assert.strictEqual(actualLength, length, message ?? `Expected ${inspectValue(actual)} to have length ${length}, received ${actualLength}`);
|
|
1072
|
+
}
|
|
1073
|
+
},
|
|
1074
|
+
toMatch(expected) {
|
|
1075
|
+
if (typeof actual !== "string") {
|
|
1076
|
+
failAssertion(`Expected a string for toMatch, received ${typeof actual} (${inspectValue(actual)})`, actual, expected, "toMatch", message);
|
|
1077
|
+
}
|
|
1078
|
+
const passed = expected instanceof RegExp ? (expected.global || expected.sticky ? new RegExp(expected.source, expected.flags) : expected).test(actual) : actual.includes(expected);
|
|
1079
|
+
if (negated ? passed : !passed) {
|
|
1080
|
+
failAssertion(`Expected ${inspectValue(actual)} ${negated ? "not " : ""}to match ${inspectValue(expected)}`, actual, expected, negated ? "not toMatch" : "toMatch", message);
|
|
1081
|
+
}
|
|
1082
|
+
},
|
|
1083
|
+
toBeGreaterThan(expected) {
|
|
1084
|
+
checkComparison(expected, ">", "to be greater than", (a, b) => a > b);
|
|
1085
|
+
},
|
|
1086
|
+
toBeGreaterThanOrEqual(expected) {
|
|
1087
|
+
checkComparison(expected, ">=", "to be greater than or equal to", (a, b) => a >= b);
|
|
1088
|
+
},
|
|
1089
|
+
toBeLessThan(expected) {
|
|
1090
|
+
checkComparison(expected, "<", "to be less than", (a, b) => a < b);
|
|
1091
|
+
},
|
|
1092
|
+
toBeLessThanOrEqual(expected) {
|
|
1093
|
+
checkComparison(expected, "<=", "to be less than or equal to", (a, b) => a <= b);
|
|
1094
|
+
},
|
|
1095
|
+
toThrow(expected) {
|
|
1096
|
+
if (typeof actual !== "function") {
|
|
1097
|
+
failAssertion(`Expected a function for toThrow, received ${typeof actual} (${inspectValue(actual)})`, actual, expected, "toThrow", message);
|
|
1098
|
+
}
|
|
1099
|
+
let threw = false;
|
|
1100
|
+
let thrown;
|
|
1101
|
+
try {
|
|
1102
|
+
actual();
|
|
1103
|
+
} catch (err) {
|
|
1104
|
+
threw = true;
|
|
1105
|
+
thrown = err;
|
|
1106
|
+
}
|
|
1107
|
+
if (!threw) {
|
|
1108
|
+
if (!negated) {
|
|
1109
|
+
failAssertion(expected === undefined ? "Expected function to throw" : `Expected function to throw ${inspectValue(expected)}, but it did not throw`, undefined, expected, "toThrow", message);
|
|
525
1110
|
}
|
|
526
|
-
|
|
527
|
-
|
|
1111
|
+
return;
|
|
1112
|
+
}
|
|
1113
|
+
if (expected === undefined) {
|
|
1114
|
+
if (negated) {
|
|
1115
|
+
failAssertion(`Expected function not to throw, but it threw ${inspectValue(thrown)}`, thrown, undefined, "not toThrow", message);
|
|
528
1116
|
}
|
|
1117
|
+
return;
|
|
1118
|
+
}
|
|
1119
|
+
const matched = matchesThrown(thrown, expected);
|
|
1120
|
+
if (negated ? matched : !matched) {
|
|
1121
|
+
failAssertion(negated ? `Expected function not to throw matching ${inspectValue(expected)}, but it threw ${inspectValue(thrown)}` : `Expected function to throw matching ${inspectValue(expected)}, but it threw ${inspectValue(thrown)}`, thrown, expected, negated ? "not toThrow" : "toThrow", message);
|
|
529
1122
|
}
|
|
530
1123
|
}
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
1124
|
+
};
|
|
1125
|
+
}
|
|
1126
|
+
function createNodeExpect() {
|
|
1127
|
+
return (actual, message) => createMatchers(actual, message, false);
|
|
1128
|
+
}
|
|
1129
|
+
var cachedDefaultExpect;
|
|
1130
|
+
function loadBunExpect() {
|
|
1131
|
+
if (typeof globalThis.Bun === "undefined")
|
|
1132
|
+
return;
|
|
1133
|
+
try {
|
|
1134
|
+
const req = createRequire(import.meta.url);
|
|
1135
|
+
const specifier = ["bun", "test"].join(":");
|
|
1136
|
+
const mod = req(specifier);
|
|
1137
|
+
if (typeof mod.expect === "function")
|
|
1138
|
+
return mod.expect;
|
|
1139
|
+
} catch {}
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
function getDefaultExpect() {
|
|
1143
|
+
if (!cachedDefaultExpect) {
|
|
1144
|
+
cachedDefaultExpect = loadBunExpect() ?? createNodeExpect();
|
|
540
1145
|
}
|
|
541
|
-
|
|
542
|
-
return { results, success: failed === 0 };
|
|
1146
|
+
return cachedDefaultExpect;
|
|
543
1147
|
}
|
|
1148
|
+
var expectTarget = () => {
|
|
1149
|
+
throw new Error("unreachable");
|
|
1150
|
+
};
|
|
1151
|
+
var expect = new Proxy(expectTarget, {
|
|
1152
|
+
apply(_target, thisArg, args) {
|
|
1153
|
+
return Reflect.apply(getDefaultExpect(), thisArg, args);
|
|
1154
|
+
},
|
|
1155
|
+
get(_target, prop) {
|
|
1156
|
+
const impl = getDefaultExpect();
|
|
1157
|
+
const value = Reflect.get(impl, prop, impl);
|
|
1158
|
+
return typeof value === "function" ? value.bind(impl) : value;
|
|
1159
|
+
},
|
|
1160
|
+
has(_target, prop) {
|
|
1161
|
+
return Reflect.has(getDefaultExpect(), prop);
|
|
1162
|
+
},
|
|
1163
|
+
ownKeys() {
|
|
1164
|
+
return Reflect.ownKeys(getDefaultExpect());
|
|
1165
|
+
},
|
|
1166
|
+
getOwnPropertyDescriptor(_target, prop) {
|
|
1167
|
+
const desc = Reflect.getOwnPropertyDescriptor(getDefaultExpect(), prop);
|
|
1168
|
+
return desc ? { ...desc, configurable: true } : undefined;
|
|
1169
|
+
},
|
|
1170
|
+
getPrototypeOf() {
|
|
1171
|
+
return Reflect.getPrototypeOf(getDefaultExpect());
|
|
1172
|
+
}
|
|
1173
|
+
});
|
|
544
1174
|
|
|
545
|
-
// src/
|
|
546
|
-
|
|
547
|
-
var
|
|
548
|
-
function
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
1175
|
+
// src/lazy-faker.ts
|
|
1176
|
+
import { createRequire as createRequire2 } from "node:module";
|
|
1177
|
+
var loadedFaker;
|
|
1178
|
+
function getDefaultFaker() {
|
|
1179
|
+
if (!loadedFaker) {
|
|
1180
|
+
const req = createRequire2(import.meta.url);
|
|
1181
|
+
const mod = req("@faker-js/faker/locale/en");
|
|
1182
|
+
loadedFaker = mod.faker;
|
|
1183
|
+
}
|
|
1184
|
+
return loadedFaker;
|
|
553
1185
|
}
|
|
1186
|
+
var lazyFaker = new Proxy({}, {
|
|
1187
|
+
get(_target, prop) {
|
|
1188
|
+
const instance = getDefaultFaker();
|
|
1189
|
+
const value = Reflect.get(instance, prop, instance);
|
|
1190
|
+
return typeof value === "function" && prop !== "constructor" ? value.bind(instance) : value;
|
|
1191
|
+
},
|
|
1192
|
+
set(_target, prop, value) {
|
|
1193
|
+
const instance = getDefaultFaker();
|
|
1194
|
+
return Reflect.set(instance, prop, value, instance);
|
|
1195
|
+
},
|
|
1196
|
+
has(_target, prop) {
|
|
1197
|
+
return Reflect.has(getDefaultFaker(), prop);
|
|
1198
|
+
},
|
|
1199
|
+
ownKeys() {
|
|
1200
|
+
return Reflect.ownKeys(getDefaultFaker());
|
|
1201
|
+
},
|
|
1202
|
+
getOwnPropertyDescriptor(_target, prop) {
|
|
1203
|
+
const desc = Reflect.getOwnPropertyDescriptor(getDefaultFaker(), prop);
|
|
1204
|
+
return desc ? { ...desc, configurable: true } : undefined;
|
|
1205
|
+
},
|
|
1206
|
+
getPrototypeOf() {
|
|
1207
|
+
return Reflect.getPrototypeOf(getDefaultFaker());
|
|
1208
|
+
}
|
|
1209
|
+
});
|
|
554
1210
|
|
|
555
1211
|
// src/step.ts
|
|
1212
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
556
1213
|
var isCacheEntry = (stored) => typeof stored === "object" && stored !== null && stored.__plantr === 1;
|
|
1214
|
+
var slugify = (description) => description.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
1215
|
+
function canonicalStringify(value) {
|
|
1216
|
+
if (value === null || typeof value !== "object") {
|
|
1217
|
+
return JSON.stringify(value);
|
|
1218
|
+
}
|
|
1219
|
+
if (Array.isArray(value)) {
|
|
1220
|
+
return `[${value.map((item) => item === undefined ? "null" : canonicalStringify(item)).join(",")}]`;
|
|
1221
|
+
}
|
|
1222
|
+
if (typeof value.toJSON === "function") {
|
|
1223
|
+
return canonicalStringify(value.toJSON());
|
|
1224
|
+
}
|
|
1225
|
+
const obj = value;
|
|
1226
|
+
const keys = Object.keys(obj).sort();
|
|
1227
|
+
const parts = [];
|
|
1228
|
+
for (const key of keys) {
|
|
1229
|
+
const entryValue = obj[key];
|
|
1230
|
+
if (entryValue !== undefined) {
|
|
1231
|
+
parts.push(`${JSON.stringify(key)}:${canonicalStringify(entryValue)}`);
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
return `{${parts.join(",")}}`;
|
|
1235
|
+
}
|
|
557
1236
|
function createStepRunner(config) {
|
|
558
1237
|
const { cache, log = true } = config ?? {};
|
|
559
|
-
|
|
560
|
-
let
|
|
561
|
-
|
|
1238
|
+
const scopeStorage = new AsyncLocalStorage;
|
|
1239
|
+
let fallbackScope = {
|
|
1240
|
+
seederName: config?.seederName ?? "",
|
|
1241
|
+
fresh: false,
|
|
1242
|
+
record: { cachedSteps: [] }
|
|
1243
|
+
};
|
|
562
1244
|
const usedKeys = new Set;
|
|
1245
|
+
const pendingWrites = new Map;
|
|
1246
|
+
let preloaded;
|
|
1247
|
+
let warnedNoCache = false;
|
|
563
1248
|
const setSeederName = (name, options) => {
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
1249
|
+
const record = { cachedSteps: [] };
|
|
1250
|
+
fallbackScope = {
|
|
1251
|
+
seederName: name,
|
|
1252
|
+
fresh: options?.fresh ?? false,
|
|
1253
|
+
record
|
|
1254
|
+
};
|
|
567
1255
|
return record;
|
|
568
1256
|
};
|
|
1257
|
+
const createScope = (options) => ({
|
|
1258
|
+
seederName: options.seederName,
|
|
1259
|
+
fresh: options.fresh ?? false,
|
|
1260
|
+
record: { cachedSteps: [] },
|
|
1261
|
+
prefix: options.prefix
|
|
1262
|
+
});
|
|
1263
|
+
const runWithScope = (scope, fn) => scopeStorage.run(scope, fn);
|
|
1264
|
+
const preload = async () => {
|
|
1265
|
+
if (!cache?.getAll)
|
|
1266
|
+
return;
|
|
1267
|
+
const entries = await cache.getAll();
|
|
1268
|
+
preloaded = entries instanceof Map ? new Map(entries) : new Map(Object.entries(entries));
|
|
1269
|
+
};
|
|
1270
|
+
const flush = async () => {
|
|
1271
|
+
if (!cache?.setMany || pendingWrites.size === 0)
|
|
1272
|
+
return;
|
|
1273
|
+
const entries = [...pendingWrites.entries()].map(([key, value]) => ({
|
|
1274
|
+
key,
|
|
1275
|
+
value
|
|
1276
|
+
}));
|
|
1277
|
+
pendingWrites.clear();
|
|
1278
|
+
await cache.setMany(entries);
|
|
1279
|
+
};
|
|
569
1280
|
const print = (line) => {
|
|
570
1281
|
if (log)
|
|
571
1282
|
console.log(line);
|
|
572
1283
|
};
|
|
1284
|
+
const formatPrefix = (scope) => scope.prefix ? ` ${colorize(`[${scope.prefix}]`, "cyan")} ` : " ";
|
|
573
1285
|
const step = async (description, fn, options) => {
|
|
574
|
-
const
|
|
575
|
-
const
|
|
576
|
-
const
|
|
577
|
-
const
|
|
1286
|
+
const scope = scopeStorage.getStore() ?? fallbackScope;
|
|
1287
|
+
const useCache = options?.useCache === true;
|
|
1288
|
+
const startTime = performance.now();
|
|
1289
|
+
const prefix = formatPrefix(scope);
|
|
578
1290
|
try {
|
|
579
1291
|
let result;
|
|
580
1292
|
let wasCached = false;
|
|
581
1293
|
if (useCache && cache) {
|
|
1294
|
+
const rawKey = options.key !== undefined ? options.key : slugify(description);
|
|
1295
|
+
const cacheKey = scope.seederName ? `${scope.seederName}:${rawKey}` : rawKey;
|
|
582
1296
|
if (usedKeys.has(cacheKey)) {
|
|
583
|
-
throw new Error(`Step "${description}" uses cache key "${cacheKey}", which another cached step in this run already used. Give each cached step a unique description.`);
|
|
1297
|
+
throw new Error(`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.`);
|
|
584
1298
|
}
|
|
585
1299
|
usedKeys.add(cacheKey);
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
const version = options?.version === undefined ? undefined : JSON.stringify(options.version);
|
|
589
|
-
const stored = fresh ? undefined : await cache.get(cacheKey);
|
|
1300
|
+
const version = options.version === undefined ? undefined : canonicalStringify(options.version);
|
|
1301
|
+
const stored = scope.fresh ? undefined : preloaded !== undefined ? preloaded.get(cacheKey) : await cache.get(cacheKey);
|
|
590
1302
|
if (isCacheEntry(stored) && stored.version === version) {
|
|
591
1303
|
result = stored.value;
|
|
592
1304
|
wasCached = true;
|
|
593
|
-
} else if (stored !== undefined && !isCacheEntry(stored) && version === undefined) {
|
|
1305
|
+
} else if (stored !== undefined && stored !== null && !isCacheEntry(stored) && version === undefined) {
|
|
594
1306
|
result = stored;
|
|
595
1307
|
wasCached = true;
|
|
596
1308
|
} else {
|
|
597
1309
|
result = await fn();
|
|
598
1310
|
const entry = version === undefined ? { __plantr: 1, value: result } : { __plantr: 1, version, value: result };
|
|
599
|
-
|
|
1311
|
+
preloaded?.set(cacheKey, entry);
|
|
1312
|
+
if (cache.setMany) {
|
|
1313
|
+
pendingWrites.set(cacheKey, entry);
|
|
1314
|
+
} else {
|
|
1315
|
+
await cache.set(cacheKey, entry);
|
|
1316
|
+
}
|
|
600
1317
|
}
|
|
601
1318
|
} else if (useCache && !cache) {
|
|
602
|
-
|
|
1319
|
+
if (!warnedNoCache) {
|
|
1320
|
+
warnedNoCache = true;
|
|
1321
|
+
print(`${prefix}${colorize("⚠ Cache not configured, running without cache", "yellow")}`);
|
|
1322
|
+
}
|
|
603
1323
|
result = await fn();
|
|
604
1324
|
} else {
|
|
605
1325
|
result = await fn();
|
|
606
1326
|
}
|
|
607
1327
|
if (wasCached)
|
|
608
|
-
record.cachedSteps.push(description);
|
|
609
|
-
const suffix = wasCached ? ` ${colorize("(cached)", "cyan")}` : ` ${colorize(formatDuration(
|
|
610
|
-
print(
|
|
1328
|
+
scope.record.cachedSteps.push(description);
|
|
1329
|
+
const suffix = wasCached ? ` ${colorize("(cached)", "cyan")}` : ` ${colorize(formatDuration(performance.now() - startTime), "dim")}`;
|
|
1330
|
+
print(`${prefix}${colorize("✓", "green")} ${description}${suffix}`);
|
|
611
1331
|
return result;
|
|
612
1332
|
} catch (error) {
|
|
613
|
-
record.failed
|
|
614
|
-
|
|
1333
|
+
if (!scope.record.failed || scope.record.failed.error !== error) {
|
|
1334
|
+
scope.record.failed = { step: description, error };
|
|
1335
|
+
}
|
|
1336
|
+
print(`${prefix}${colorize("✗", "red")} ${description}`);
|
|
615
1337
|
if (error instanceof Error) {
|
|
616
|
-
print(
|
|
1338
|
+
print(`${prefix} ${colorize(error.message, "dim")}`);
|
|
617
1339
|
}
|
|
618
1340
|
throw error;
|
|
619
1341
|
}
|
|
620
1342
|
};
|
|
621
|
-
return { step, setSeederName };
|
|
1343
|
+
return { step, setSeederName, createScope, runWithScope, preload, flush };
|
|
622
1344
|
}
|
|
623
1345
|
|
|
624
1346
|
// src/create-seeder-instance.ts
|
|
1347
|
+
function cloneFaker(baseFaker) {
|
|
1348
|
+
const Ctor = baseFaker.constructor;
|
|
1349
|
+
if (typeof Ctor === "function" && "rawDefinitions" in baseFaker && baseFaker.rawDefinitions) {
|
|
1350
|
+
return new Ctor({ locale: baseFaker.rawDefinitions });
|
|
1351
|
+
}
|
|
1352
|
+
return baseFaker;
|
|
1353
|
+
}
|
|
625
1354
|
function createSeederInstance(config) {
|
|
626
1355
|
const defineSeeder = createDefineSeeder();
|
|
627
|
-
const
|
|
628
|
-
|
|
629
|
-
|
|
1356
|
+
const customFaker = config?.faker && config.faker !== lazyFaker ? config.faker : undefined;
|
|
1357
|
+
const resolveBaseFaker = () => customFaker ?? getDefaultFaker();
|
|
1358
|
+
const customExpect = config?.expect;
|
|
1359
|
+
const fakerSeed = config?.fakerSeed;
|
|
1360
|
+
const defaultConcurrency = config?.concurrency;
|
|
1361
|
+
const runInternal = async (seeders, options, bannerName) => {
|
|
1362
|
+
const stepRunner = createStepRunner({
|
|
1363
|
+
cache: config?.cache,
|
|
630
1364
|
log: options?.verbose ?? true
|
|
631
1365
|
});
|
|
632
|
-
const
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
1366
|
+
const fakerStorage = new AsyncLocalStorage2;
|
|
1367
|
+
const resolveActiveFaker = () => {
|
|
1368
|
+
const slot = fakerStorage.getStore();
|
|
1369
|
+
if (!slot)
|
|
1370
|
+
return resolveBaseFaker();
|
|
1371
|
+
if (slot.instance)
|
|
1372
|
+
return slot.instance;
|
|
1373
|
+
const base = resolveBaseFaker();
|
|
1374
|
+
if (!slot.isolated) {
|
|
1375
|
+
slot.instance = base;
|
|
1376
|
+
return base;
|
|
1377
|
+
}
|
|
1378
|
+
const cloned = cloneFaker(base);
|
|
1379
|
+
if (fakerSeed !== undefined) {
|
|
1380
|
+
cloned.seed(fakerSeed + hashName(slot.name));
|
|
1381
|
+
}
|
|
1382
|
+
slot.instance = cloned;
|
|
1383
|
+
return cloned;
|
|
1384
|
+
};
|
|
1385
|
+
const scopedFaker = new Proxy({}, {
|
|
1386
|
+
get(_target, prop) {
|
|
1387
|
+
const active = resolveActiveFaker();
|
|
1388
|
+
const value = Reflect.get(active, prop, active);
|
|
1389
|
+
return typeof value === "function" && prop !== "constructor" ? value.bind(active) : value;
|
|
1390
|
+
},
|
|
1391
|
+
set(_target, prop, value) {
|
|
1392
|
+
const active = resolveActiveFaker();
|
|
1393
|
+
return Reflect.set(active, prop, value, active);
|
|
1394
|
+
},
|
|
1395
|
+
has(_target, prop) {
|
|
1396
|
+
return Reflect.has(resolveActiveFaker(), prop);
|
|
1397
|
+
},
|
|
1398
|
+
ownKeys() {
|
|
1399
|
+
return Reflect.ownKeys(resolveActiveFaker());
|
|
1400
|
+
},
|
|
1401
|
+
getOwnPropertyDescriptor(_target, prop) {
|
|
1402
|
+
const desc = Reflect.getOwnPropertyDescriptor(resolveActiveFaker(), prop);
|
|
1403
|
+
return desc ? { ...desc, configurable: true } : undefined;
|
|
1404
|
+
},
|
|
1405
|
+
getPrototypeOf() {
|
|
1406
|
+
return Reflect.getPrototypeOf(resolveActiveFaker());
|
|
1407
|
+
}
|
|
1408
|
+
});
|
|
1409
|
+
const mergedOptions = defaultConcurrency !== undefined && options?.concurrency === undefined ? { ...options, concurrency: defaultConcurrency } : options ?? {};
|
|
1410
|
+
return runSeedersCore(seeders, {
|
|
1411
|
+
context: async () => {
|
|
1412
|
+
const base = {
|
|
1413
|
+
faker: scopedFaker,
|
|
1414
|
+
step: stepRunner.step,
|
|
1415
|
+
expect: customExpect ?? getDefaultExpect()
|
|
1416
|
+
};
|
|
1417
|
+
if (!config?.context)
|
|
1418
|
+
return base;
|
|
1419
|
+
const extra = await config.context(base);
|
|
1420
|
+
return extra === base ? base : { ...base, ...extra };
|
|
1421
|
+
},
|
|
1422
|
+
preloadCache: config?.cache?.getAll ? () => stepRunner.preload() : undefined,
|
|
1423
|
+
flushCache: config?.cache?.setMany ? () => stepRunner.flush() : undefined,
|
|
1424
|
+
createSeederScope: ({ name, fresh, concurrent }) => {
|
|
1425
|
+
const stepScope = stepRunner.createScope({
|
|
1426
|
+
seederName: name,
|
|
1427
|
+
fresh,
|
|
1428
|
+
prefix: concurrent ? name : undefined
|
|
1429
|
+
});
|
|
1430
|
+
const slot = {
|
|
1431
|
+
name,
|
|
1432
|
+
isolated: fakerSeed !== undefined || concurrent
|
|
1433
|
+
};
|
|
1434
|
+
return {
|
|
1435
|
+
record: stepScope.record,
|
|
1436
|
+
run: (fn) => stepRunner.runWithScope(stepScope, () => fakerStorage.run(slot, fn))
|
|
1437
|
+
};
|
|
1438
|
+
},
|
|
1439
|
+
bannerName,
|
|
1440
|
+
target: config?.target,
|
|
1441
|
+
onBeforeAll: config?.onBeforeAll,
|
|
1442
|
+
onAfterAll: config?.onAfterAll
|
|
1443
|
+
}, mergedOptions);
|
|
649
1444
|
};
|
|
1445
|
+
const runSeeders = (seeders, options) => runInternal(seeders, options);
|
|
650
1446
|
const runSeedersCli = async (seeders, options) => {
|
|
651
|
-
const
|
|
652
|
-
|
|
653
|
-
|
|
1447
|
+
const bannerName = options?.name ?? "Seeders";
|
|
1448
|
+
const code = await runCli(seeders, (s, opts) => runInternal(s, opts, bannerName), {
|
|
1449
|
+
name: bannerName,
|
|
1450
|
+
argv: options?.argv ?? process.argv.slice(2),
|
|
1451
|
+
target: config?.target,
|
|
1452
|
+
defaultConcurrency
|
|
654
1453
|
});
|
|
655
1454
|
process.exit(code);
|
|
656
1455
|
};
|
|
@@ -680,8 +1479,8 @@ export {
|
|
|
680
1479
|
createSeederInstance,
|
|
681
1480
|
createStepRunner,
|
|
682
1481
|
describeTarget,
|
|
683
|
-
|
|
684
|
-
|
|
1482
|
+
expect,
|
|
1483
|
+
lazyFaker as faker,
|
|
685
1484
|
formatDuration,
|
|
686
1485
|
isSeedingActive,
|
|
687
1486
|
resolveDependencyOrder,
|