plantr 2.1.0 → 2.3.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 +13 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +694 -232
- package/dist/src/cli.d.ts.map +1 -1
- package/dist/src/create-seeder-instance.d.ts +87 -12
- package/dist/src/create-seeder-instance.d.ts.map +1 -1
- package/dist/src/dependency-resolver.d.ts +5 -4
- package/dist/src/dependency-resolver.d.ts.map +1 -1
- package/dist/src/errors.d.ts +18 -0
- package/dist/src/errors.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 +25 -1
- package/dist/src/formatting.d.ts.map +1 -1
- package/dist/src/map-with-limit.d.ts +19 -0
- package/dist/src/map-with-limit.d.ts.map +1 -0
- package/dist/src/run-seeders.d.ts +46 -12
- package/dist/src/run-seeders.d.ts.map +1 -1
- package/dist/src/signals.d.ts +9 -0
- package/dist/src/signals.d.ts.map +1 -0
- package/dist/src/step.d.ts +15 -0
- package/dist/src/step.d.ts.map +1 -1
- package/dist/src/types.d.ts +11 -4
- package/dist/src/types.d.ts.map +1 -1
- package/index.ts +20 -6
- package/package.json +4 -2
- package/readme.md +178 -29
- package/src/cli.ts +4 -13
- package/src/create-seeder-instance.ts +156 -32
- package/src/dependency-resolver.ts +5 -4
- package/src/errors.ts +29 -0
- package/src/expect.ts +502 -0
- package/src/formatting.ts +53 -2
- package/src/map-with-limit.ts +48 -0
- package/src/run-seeders.ts +320 -212
- package/src/signals.ts +54 -0
- package/src/step.ts +30 -4
- package/src/types.ts +11 -4
package/dist/index.js
CHANGED
|
@@ -1,36 +1,46 @@
|
|
|
1
|
-
// index.ts
|
|
2
|
-
import { expect as expect2 } from "bun:test";
|
|
3
|
-
|
|
4
1
|
// src/create-seeder-instance.ts
|
|
5
|
-
import { expect } from "bun:test";
|
|
6
2
|
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
7
3
|
|
|
8
4
|
// src/cli.ts
|
|
9
5
|
import { parseArgs } from "node:util";
|
|
10
6
|
|
|
7
|
+
// src/errors.ts
|
|
8
|
+
var usageErrorSymbol = Symbol.for("plantr.usageError");
|
|
9
|
+
|
|
10
|
+
class SeedUsageError extends Error {
|
|
11
|
+
[usageErrorSymbol] = true;
|
|
12
|
+
constructor(message, options) {
|
|
13
|
+
super(message, options);
|
|
14
|
+
this.name = "SeedUsageError";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function isSeedUsageError(error) {
|
|
18
|
+
return typeof error === "object" && error !== null && error[usageErrorSymbol] === true;
|
|
19
|
+
}
|
|
20
|
+
|
|
11
21
|
// src/dependency-resolver.ts
|
|
12
|
-
class CircularDependencyError extends
|
|
22
|
+
class CircularDependencyError extends SeedUsageError {
|
|
13
23
|
constructor(cycle) {
|
|
14
24
|
super(`Circular dependency detected in seeders: ${cycle.join(" -> ")} -> ${cycle[0] ?? ""}`);
|
|
15
25
|
this.name = "CircularDependencyError";
|
|
16
26
|
}
|
|
17
27
|
}
|
|
18
28
|
|
|
19
|
-
class MissingDependencyError extends
|
|
29
|
+
class MissingDependencyError extends SeedUsageError {
|
|
20
30
|
constructor(seeder, missingDep) {
|
|
21
31
|
super(`Seeder "${seeder}" depends on "${missingDep}" which does not exist`);
|
|
22
32
|
this.name = "MissingDependencyError";
|
|
23
33
|
}
|
|
24
34
|
}
|
|
25
35
|
|
|
26
|
-
class DuplicateSeederError extends
|
|
36
|
+
class DuplicateSeederError extends SeedUsageError {
|
|
27
37
|
constructor(name) {
|
|
28
38
|
super(`Two seeders are named "${name}"; seeder names must be unique`);
|
|
29
39
|
this.name = "DuplicateSeederError";
|
|
30
40
|
}
|
|
31
41
|
}
|
|
32
42
|
|
|
33
|
-
class UnknownSeederError extends
|
|
43
|
+
class UnknownSeederError extends SeedUsageError {
|
|
34
44
|
constructor(name, known) {
|
|
35
45
|
super(`Unknown seeder "${name}". Registered seeders: ${known.join(", ") || "(none)"}`);
|
|
36
46
|
this.name = "UnknownSeederError";
|
|
@@ -142,6 +152,17 @@ function findCycle(remaining, seederMap) {
|
|
|
142
152
|
}
|
|
143
153
|
|
|
144
154
|
// src/formatting.ts
|
|
155
|
+
import { inspect as nodeInspect } from "node:util";
|
|
156
|
+
function inspectValue(value, options) {
|
|
157
|
+
const bunInspect = globalThis.Bun?.inspect;
|
|
158
|
+
if (typeof bunInspect === "function") {
|
|
159
|
+
return options ? bunInspect(value, options) : bunInspect(value);
|
|
160
|
+
}
|
|
161
|
+
return nodeInspect(value, { colors: options?.colors ?? false });
|
|
162
|
+
}
|
|
163
|
+
function formatError(error, options) {
|
|
164
|
+
return isSeedUsageError(error) ? error.message : inspectValue(error, options);
|
|
165
|
+
}
|
|
145
166
|
var colors = {
|
|
146
167
|
reset: "\x1B[0m",
|
|
147
168
|
bold: "\x1B[1m",
|
|
@@ -236,7 +257,7 @@ function printErrors(results) {
|
|
|
236
257
|
for (const result of failed) {
|
|
237
258
|
const where = result.failedStep ? ` in step "${result.failedStep}"` : "";
|
|
238
259
|
console.log(colorize(`❌ Seeder "${result.name}" failed${where}:`, "red"));
|
|
239
|
-
const details =
|
|
260
|
+
const details = formatError(result.error, { colors: supportsColor() });
|
|
240
261
|
for (const line of details.split(`
|
|
241
262
|
`))
|
|
242
263
|
console.log(` ${line}`);
|
|
@@ -250,6 +271,20 @@ function printErrors(results) {
|
|
|
250
271
|
console.log("");
|
|
251
272
|
}
|
|
252
273
|
}
|
|
274
|
+
function printCleanupErrors(errors) {
|
|
275
|
+
for (const error of errors) {
|
|
276
|
+
console.error(colorize("Cleanup after the run also failed:", "red"));
|
|
277
|
+
for (const line of formatError(error, { colors: supportsColor() }).split(`
|
|
278
|
+
`)) {
|
|
279
|
+
console.error(` ${line}`);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
function printFreshReset(seeders, all) {
|
|
284
|
+
const which = all ? "every seeder runs fresh" : `fresh: ${seeders.join(", ")}`;
|
|
285
|
+
console.log(colorize(`↺ onFresh (${which})`, "yellow"));
|
|
286
|
+
console.log("");
|
|
287
|
+
}
|
|
253
288
|
function printSeederHeader(name, index, total, description) {
|
|
254
289
|
const seederIndex = `[${index + 1}/${total}]`;
|
|
255
290
|
const headerLine = `━━━ ${seederIndex} ${name} ${"━".repeat(Math.max(0, 50 - name.length - seederIndex.length))}`;
|
|
@@ -357,8 +392,40 @@ function exitSeeding() {
|
|
|
357
392
|
state[key] = next > 0;
|
|
358
393
|
}
|
|
359
394
|
|
|
395
|
+
// src/signals.ts
|
|
396
|
+
var EXIT_CODES = { SIGINT: 130, SIGTERM: 143 };
|
|
397
|
+
var cleanups = new Set;
|
|
398
|
+
var received;
|
|
399
|
+
var onSignal = (signal) => {
|
|
400
|
+
if (received) {
|
|
401
|
+
process.exit(EXIT_CODES[signal]);
|
|
402
|
+
}
|
|
403
|
+
received = signal;
|
|
404
|
+
console.error(colorize(`
|
|
405
|
+
Received ${signal}: tearing down before exiting (send it again to exit now)`, "yellow"));
|
|
406
|
+
Promise.allSettled([...cleanups].map((cleanup) => cleanup())).then(() => process.exit(EXIT_CODES[signal]));
|
|
407
|
+
};
|
|
408
|
+
var listeners = {
|
|
409
|
+
SIGINT: () => onSignal("SIGINT"),
|
|
410
|
+
SIGTERM: () => onSignal("SIGTERM")
|
|
411
|
+
};
|
|
412
|
+
function onTerminationSignal(cleanup) {
|
|
413
|
+
if (cleanups.size === 0 && !received) {
|
|
414
|
+
process.on("SIGINT", listeners.SIGINT);
|
|
415
|
+
process.on("SIGTERM", listeners.SIGTERM);
|
|
416
|
+
}
|
|
417
|
+
cleanups.add(cleanup);
|
|
418
|
+
return () => {
|
|
419
|
+
cleanups.delete(cleanup);
|
|
420
|
+
if (cleanups.size === 0 && !received) {
|
|
421
|
+
process.off("SIGINT", listeners.SIGINT);
|
|
422
|
+
process.off("SIGTERM", listeners.SIGTERM);
|
|
423
|
+
}
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
|
|
360
427
|
// src/run-seeders.ts
|
|
361
|
-
class SeedTargetError extends
|
|
428
|
+
class SeedTargetError extends SeedUsageError {
|
|
362
429
|
constructor(label) {
|
|
363
430
|
super(`Refusing to seed ${label}: it is not a local database. Pass allowRemote (CLI: --allow-remote) to seed it on purpose.`);
|
|
364
431
|
this.name = "SeedTargetError";
|
|
@@ -369,8 +436,9 @@ var isLocalHost = (hostPort) => {
|
|
|
369
436
|
return true;
|
|
370
437
|
const lower = hostPort.toLowerCase();
|
|
371
438
|
const bracketed = /^\[([^\]]*)\]/.exec(lower);
|
|
439
|
+
const hasPort = bracketed ? /:\d+$/.test(lower.slice(bracketed[0].length)) : /:\d+$/.test(lower);
|
|
372
440
|
const host = bracketed ? bracketed[1] ?? "" : lower.replace(/:\d+$/, "");
|
|
373
|
-
return host === "::1" || host === "0.0.0.0" || host === "host.docker.internal" || host.endsWith(".localhost") || /^127\./.test(host) || !/[.:]/.test(host);
|
|
441
|
+
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);
|
|
374
442
|
};
|
|
375
443
|
function describeTarget(target) {
|
|
376
444
|
if (/^file:/i.test(target))
|
|
@@ -383,7 +451,9 @@ function describeTarget(target) {
|
|
|
383
451
|
const beforeQuery = queryStart === -1 ? rest : rest.slice(0, queryStart);
|
|
384
452
|
const query = queryStart === -1 ? "" : rest.slice(queryStart);
|
|
385
453
|
const authorityAndPath = beforeQuery.slice(beforeQuery.lastIndexOf("@") + 1);
|
|
386
|
-
const
|
|
454
|
+
const pathStart = authorityAndPath.search(/[/;]/);
|
|
455
|
+
const authority = pathStart === -1 ? authorityAndPath : authorityAndPath.slice(0, pathStart);
|
|
456
|
+
const path = pathStart === -1 ? "" : authorityAndPath.slice(pathStart);
|
|
387
457
|
let hosts = authority.split(",").filter(Boolean);
|
|
388
458
|
const hostParam = /[?&;]host=([^&;#]*)/i.exec(`${query}${path.startsWith(";") ? path : ""}`)?.[1];
|
|
389
459
|
if (hostParam) {
|
|
@@ -393,7 +463,9 @@ function describeTarget(target) {
|
|
|
393
463
|
return { label: "a target with an invalid host parameter", local: false };
|
|
394
464
|
}
|
|
395
465
|
}
|
|
396
|
-
const
|
|
466
|
+
const pathWithoutParams = path.startsWith("/") ? path.split(";", 1)[0] ?? "" : "";
|
|
467
|
+
const pathLabel = pathWithoutParams.length > 1 ? pathWithoutParams : "";
|
|
468
|
+
const label = `${hosts.join(",") || "local socket"}${pathLabel}`;
|
|
397
469
|
return { label, local: hosts.every(isLocalHost) };
|
|
398
470
|
}
|
|
399
471
|
async function runSeedersCore(seeders, config, options = {}) {
|
|
@@ -404,7 +476,8 @@ async function runSeedersCore(seeders, config, options = {}) {
|
|
|
404
476
|
only,
|
|
405
477
|
fresh = false,
|
|
406
478
|
allowRemote = false,
|
|
407
|
-
concurrency = 1
|
|
479
|
+
concurrency = 1,
|
|
480
|
+
handleSignals = true
|
|
408
481
|
} = options;
|
|
409
482
|
if (Number.isNaN(concurrency) || concurrency < 1 || Number.isFinite(concurrency) && !Number.isInteger(concurrency)) {
|
|
410
483
|
throw new RangeError(`Invalid concurrency (${String(concurrency)}): expected a positive integer or Infinity`);
|
|
@@ -438,7 +511,46 @@ async function runSeedersCore(seeders, config, options = {}) {
|
|
|
438
511
|
const outputs = {};
|
|
439
512
|
const failedSeeders = new Set;
|
|
440
513
|
const concurrent = concurrency > 1;
|
|
514
|
+
let beforeAllDone = false;
|
|
515
|
+
let acquired;
|
|
516
|
+
let prepared = false;
|
|
517
|
+
let ctx;
|
|
518
|
+
let interrupted = false;
|
|
519
|
+
const deferred = [];
|
|
520
|
+
let cleanup;
|
|
521
|
+
const runCleanup = () => {
|
|
522
|
+
cleanup ??= (async () => {
|
|
523
|
+
const errors = [];
|
|
524
|
+
const attempt = async (fn) => {
|
|
525
|
+
try {
|
|
526
|
+
await fn();
|
|
527
|
+
} catch (error) {
|
|
528
|
+
errors.push(error);
|
|
529
|
+
}
|
|
530
|
+
};
|
|
531
|
+
if (prepared && config.flushCache)
|
|
532
|
+
await attempt(config.flushCache);
|
|
533
|
+
if (beforeAllDone && config.onAfterAll) {
|
|
534
|
+
const onAfterAll = config.onAfterAll;
|
|
535
|
+
await attempt(() => onAfterAll(ctx));
|
|
536
|
+
}
|
|
537
|
+
if (acquired && config.teardown) {
|
|
538
|
+
const { teardown } = config;
|
|
539
|
+
const { resources } = acquired;
|
|
540
|
+
await attempt(() => teardown(resources));
|
|
541
|
+
}
|
|
542
|
+
for (const release of deferred.splice(0).reverse())
|
|
543
|
+
await attempt(release);
|
|
544
|
+
return errors;
|
|
545
|
+
})();
|
|
546
|
+
return cleanup;
|
|
547
|
+
};
|
|
441
548
|
enterSeeding();
|
|
549
|
+
const unregisterSignals = handleSignals ? onTerminationSignal(async () => {
|
|
550
|
+
interrupted = true;
|
|
551
|
+
printCleanupErrors(await runCleanup());
|
|
552
|
+
}) : () => {};
|
|
553
|
+
let bodyError;
|
|
442
554
|
try {
|
|
443
555
|
if (verbose) {
|
|
444
556
|
printStartBanner({
|
|
@@ -452,218 +564,233 @@ async function runSeedersCore(seeders, config, options = {}) {
|
|
|
452
564
|
if (config.onBeforeAll) {
|
|
453
565
|
await config.onBeforeAll();
|
|
454
566
|
}
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
567
|
+
beforeAllDone = true;
|
|
568
|
+
const resources = config.setup ? await config.setup({ defer: (release) => deferred.push(release) }) : undefined;
|
|
569
|
+
acquired = { resources };
|
|
570
|
+
if (config.prepare) {
|
|
571
|
+
await config.prepare(resources);
|
|
572
|
+
}
|
|
573
|
+
prepared = true;
|
|
574
|
+
const freshSeeders = orderedNames.filter(isFresh);
|
|
575
|
+
if (config.onFresh && freshSeeders.length > 0) {
|
|
576
|
+
const all = freshSeeders.length === seederMap.size;
|
|
577
|
+
if (verbose)
|
|
578
|
+
printFreshReset(freshSeeders, all);
|
|
579
|
+
await config.onFresh({ resources, seeders: freshSeeders, all });
|
|
580
|
+
}
|
|
581
|
+
if (config.preloadCache) {
|
|
582
|
+
await config.preloadCache();
|
|
583
|
+
}
|
|
584
|
+
ctx = await config.context(resources);
|
|
585
|
+
const activeCtx = ctx;
|
|
586
|
+
const executeSeeder = async (name) => {
|
|
587
|
+
const idx = resultIndex.get(name);
|
|
588
|
+
const seeder = seederMap.get(name);
|
|
589
|
+
if (idx === undefined || !seeder)
|
|
590
|
+
return true;
|
|
591
|
+
const scopeHandle = config.createSeederScope ? config.createSeederScope({ name, fresh: isFresh(name), concurrent }) : {
|
|
592
|
+
record: config.beforeSeeder?.(name, { fresh: isFresh(name) }),
|
|
593
|
+
run: (fn) => fn()
|
|
594
|
+
};
|
|
595
|
+
const deps = {};
|
|
596
|
+
for (const depName of seeder.dependsOn) {
|
|
597
|
+
deps[depName] = outputs[depName];
|
|
459
598
|
}
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
const
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
599
|
+
const startTime = performance.now();
|
|
600
|
+
try {
|
|
601
|
+
const output = await scopeHandle.run(async () => seeder.run(activeCtx, deps));
|
|
602
|
+
const durationMs = Math.round(performance.now() - startTime);
|
|
603
|
+
outputs[name] = output;
|
|
604
|
+
results[idx] = {
|
|
605
|
+
name,
|
|
606
|
+
status: "completed",
|
|
607
|
+
durationMs,
|
|
608
|
+
output,
|
|
609
|
+
cachedSteps: scopeHandle.record?.cachedSteps ?? []
|
|
470
610
|
};
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
try {
|
|
477
|
-
const output = await scopeHandle.run(async () => seeder.run(activeCtx, deps));
|
|
478
|
-
const durationMs = Math.round(performance.now() - startTime);
|
|
479
|
-
outputs[name] = output;
|
|
480
|
-
results[idx] = {
|
|
481
|
-
name,
|
|
482
|
-
status: "completed",
|
|
483
|
-
durationMs,
|
|
484
|
-
output,
|
|
485
|
-
cachedSteps: scopeHandle.record?.cachedSteps ?? []
|
|
486
|
-
};
|
|
487
|
-
if (verbose) {
|
|
488
|
-
if (concurrent) {
|
|
489
|
-
printConcurrentComplete(name, durationMs, true);
|
|
490
|
-
} else {
|
|
491
|
-
printSeederComplete(durationMs, true);
|
|
492
|
-
}
|
|
611
|
+
if (verbose) {
|
|
612
|
+
if (concurrent) {
|
|
613
|
+
printConcurrentComplete(name, durationMs, true);
|
|
614
|
+
} else {
|
|
615
|
+
printSeederComplete(durationMs, true);
|
|
493
616
|
}
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
617
|
+
}
|
|
618
|
+
return true;
|
|
619
|
+
} catch (error) {
|
|
620
|
+
const durationMs = Math.round(performance.now() - startTime);
|
|
621
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
622
|
+
const failedStep = scopeHandle.record?.failed && scopeHandle.record.failed.error === error ? scopeHandle.record.failed.step : undefined;
|
|
623
|
+
results[idx] = {
|
|
624
|
+
name,
|
|
625
|
+
status: "failed",
|
|
626
|
+
durationMs,
|
|
627
|
+
error: err,
|
|
628
|
+
...failedStep !== undefined ? { failedStep } : {},
|
|
629
|
+
cachedSteps: scopeHandle.record?.cachedSteps ?? []
|
|
630
|
+
};
|
|
631
|
+
failedSeeders.add(name);
|
|
632
|
+
if (verbose) {
|
|
633
|
+
if (concurrent) {
|
|
634
|
+
printConcurrentComplete(name, durationMs, false);
|
|
635
|
+
} else {
|
|
636
|
+
printSeederComplete(durationMs, false);
|
|
514
637
|
}
|
|
515
|
-
return false;
|
|
516
638
|
}
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
639
|
+
return false;
|
|
640
|
+
}
|
|
641
|
+
};
|
|
642
|
+
if (!concurrent) {
|
|
643
|
+
for (let i = 0;i < orderedNames.length; i++) {
|
|
644
|
+
if (interrupted)
|
|
645
|
+
break;
|
|
646
|
+
const name = orderedNames[i];
|
|
647
|
+
if (!name)
|
|
648
|
+
continue;
|
|
649
|
+
const seeder = seederMap.get(name);
|
|
650
|
+
if (!seeder)
|
|
651
|
+
continue;
|
|
652
|
+
if (continueOnFailure) {
|
|
653
|
+
const failedDeps = seeder.dependsOn.filter((dep) => failedSeeders.has(dep));
|
|
654
|
+
if (failedDeps.length > 0) {
|
|
655
|
+
results[i] = { name, status: "skipped", failedDeps };
|
|
656
|
+
failedSeeders.add(name);
|
|
657
|
+
if (verbose) {
|
|
658
|
+
printSeederHeader(name, i, orderedNames.length, seeder.description);
|
|
659
|
+
printSeederSkipped(failedDeps);
|
|
536
660
|
}
|
|
537
|
-
|
|
538
|
-
if (verbose) {
|
|
539
|
-
printSeederHeader(name, i, orderedNames.length, seeder.description);
|
|
540
|
-
}
|
|
541
|
-
const ok = await executeSeeder(name);
|
|
542
|
-
if (!ok && !continueOnFailure) {
|
|
543
|
-
break;
|
|
661
|
+
continue;
|
|
544
662
|
}
|
|
545
663
|
}
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
const dependents = new Map;
|
|
549
|
-
for (const name of orderedNames) {
|
|
550
|
-
remainingDeps.set(name, 0);
|
|
551
|
-
dependents.set(name, []);
|
|
664
|
+
if (verbose) {
|
|
665
|
+
printSeederHeader(name, i, orderedNames.length, seeder.description);
|
|
552
666
|
}
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
continue;
|
|
557
|
-
const uniqueDeps = new Set(seeder.dependsOn);
|
|
558
|
-
remainingDeps.set(name, uniqueDeps.size);
|
|
559
|
-
for (const dep of uniqueDeps) {
|
|
560
|
-
dependents.get(dep)?.push(name);
|
|
561
|
-
}
|
|
667
|
+
const ok = await executeSeeder(name);
|
|
668
|
+
if (!ok && !continueOnFailure) {
|
|
669
|
+
break;
|
|
562
670
|
}
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
671
|
+
}
|
|
672
|
+
} else if (orderedNames.length > 0) {
|
|
673
|
+
const remainingDeps = new Map;
|
|
674
|
+
const dependents = new Map;
|
|
675
|
+
for (const name of orderedNames) {
|
|
676
|
+
remainingDeps.set(name, 0);
|
|
677
|
+
dependents.set(name, []);
|
|
678
|
+
}
|
|
679
|
+
for (const name of orderedNames) {
|
|
680
|
+
const seeder = seederMap.get(name);
|
|
681
|
+
if (!seeder)
|
|
682
|
+
continue;
|
|
683
|
+
const uniqueDeps = new Set(seeder.dependsOn);
|
|
684
|
+
remainingDeps.set(name, uniqueDeps.size);
|
|
685
|
+
for (const dep of uniqueDeps) {
|
|
686
|
+
dependents.get(dep)?.push(name);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
const criticalHeight = new Map;
|
|
690
|
+
for (let i = orderedNames.length - 1;i >= 0; i--) {
|
|
691
|
+
const name = orderedNames[i];
|
|
692
|
+
let maxHeight = 0;
|
|
693
|
+
for (const dependent of dependents.get(name) ?? []) {
|
|
694
|
+
const h = (criticalHeight.get(dependent) ?? 0) + 1;
|
|
695
|
+
if (h > maxHeight)
|
|
696
|
+
maxHeight = h;
|
|
573
697
|
}
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
698
|
+
criticalHeight.set(name, maxHeight);
|
|
699
|
+
}
|
|
700
|
+
const ready = [];
|
|
701
|
+
for (const name of orderedNames) {
|
|
702
|
+
if (remainingDeps.get(name) === 0) {
|
|
703
|
+
ready.push(name);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
const popHighestPriority = () => {
|
|
707
|
+
let bestIdx = 0;
|
|
708
|
+
let bestHeight = criticalHeight.get(ready[0]) ?? 0;
|
|
709
|
+
let bestOrder = resultIndex.get(ready[0]) ?? 0;
|
|
710
|
+
for (let i = 1;i < ready.length; i++) {
|
|
711
|
+
const candidate = ready[i];
|
|
712
|
+
const h = criticalHeight.get(candidate) ?? 0;
|
|
713
|
+
const order = resultIndex.get(candidate) ?? 0;
|
|
714
|
+
if (h > bestHeight || h === bestHeight && order < bestOrder) {
|
|
715
|
+
bestIdx = i;
|
|
716
|
+
bestHeight = h;
|
|
717
|
+
bestOrder = order;
|
|
578
718
|
}
|
|
579
719
|
}
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
720
|
+
return ready.splice(bestIdx, 1)[0];
|
|
721
|
+
};
|
|
722
|
+
await new Promise((resolve) => {
|
|
723
|
+
let inFlight = 0;
|
|
724
|
+
let stopped = false;
|
|
725
|
+
const markSettled = (settledName) => {
|
|
726
|
+
const deps = dependents.get(settledName);
|
|
727
|
+
if (!deps)
|
|
728
|
+
return;
|
|
729
|
+
for (const dependent of deps) {
|
|
730
|
+
const next = (remainingDeps.get(dependent) ?? 1) - 1;
|
|
731
|
+
remainingDeps.set(dependent, next);
|
|
732
|
+
if (next !== 0 || stopped)
|
|
733
|
+
continue;
|
|
734
|
+
const seeder = seederMap.get(dependent);
|
|
735
|
+
if (!seeder)
|
|
736
|
+
continue;
|
|
737
|
+
const failedDeps = seeder.dependsOn.filter((d) => failedSeeders.has(d));
|
|
738
|
+
if (failedDeps.length > 0) {
|
|
739
|
+
const idx = resultIndex.get(dependent);
|
|
740
|
+
if (idx !== undefined) {
|
|
741
|
+
results[idx] = { name: dependent, status: "skipped", failedDeps };
|
|
742
|
+
}
|
|
743
|
+
failedSeeders.add(dependent);
|
|
744
|
+
if (verbose) {
|
|
745
|
+
printConcurrentSkipped(dependent, failedDeps);
|
|
746
|
+
}
|
|
747
|
+
markSettled(dependent);
|
|
748
|
+
} else {
|
|
749
|
+
ready.push(dependent);
|
|
592
750
|
}
|
|
593
751
|
}
|
|
594
|
-
return ready.splice(bestIdx, 1)[0];
|
|
595
752
|
};
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
const next = (remainingDeps.get(dependent) ?? 1) - 1;
|
|
605
|
-
remainingDeps.set(dependent, next);
|
|
606
|
-
if (next !== 0 || stopped)
|
|
607
|
-
continue;
|
|
608
|
-
const seeder = seederMap.get(dependent);
|
|
609
|
-
if (!seeder)
|
|
610
|
-
continue;
|
|
611
|
-
const failedDeps = seeder.dependsOn.filter((d) => failedSeeders.has(d));
|
|
612
|
-
if (failedDeps.length > 0) {
|
|
613
|
-
const idx = resultIndex.get(dependent);
|
|
614
|
-
if (idx !== undefined) {
|
|
615
|
-
results[idx] = { name: dependent, status: "skipped", failedDeps };
|
|
616
|
-
}
|
|
617
|
-
failedSeeders.add(dependent);
|
|
618
|
-
if (verbose) {
|
|
619
|
-
printConcurrentSkipped(dependent, failedDeps);
|
|
620
|
-
}
|
|
621
|
-
markSettled(dependent);
|
|
753
|
+
const schedule = () => {
|
|
754
|
+
while (!stopped && !interrupted && inFlight < concurrency && ready.length > 0) {
|
|
755
|
+
const name = popHighestPriority();
|
|
756
|
+
inFlight++;
|
|
757
|
+
executeSeeder(name).then((ok) => {
|
|
758
|
+
inFlight--;
|
|
759
|
+
if (!ok && !continueOnFailure) {
|
|
760
|
+
stopped = true;
|
|
622
761
|
} else {
|
|
623
|
-
|
|
762
|
+
markSettled(name);
|
|
624
763
|
}
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
stopped = true;
|
|
635
|
-
} else {
|
|
636
|
-
markSettled(name);
|
|
637
|
-
}
|
|
638
|
-
schedule();
|
|
639
|
-
});
|
|
640
|
-
}
|
|
641
|
-
if (inFlight === 0 && (stopped || ready.length === 0)) {
|
|
642
|
-
resolve();
|
|
643
|
-
}
|
|
644
|
-
};
|
|
645
|
-
schedule();
|
|
646
|
-
});
|
|
647
|
-
}
|
|
648
|
-
if (printResults) {
|
|
649
|
-
printResultsTable(results);
|
|
650
|
-
printErrors(results);
|
|
651
|
-
printSummary(results, performance.now() - runStartTime, concurrency);
|
|
652
|
-
}
|
|
653
|
-
} finally {
|
|
654
|
-
try {
|
|
655
|
-
if (config.flushCache) {
|
|
656
|
-
await config.flushCache();
|
|
657
|
-
}
|
|
658
|
-
} finally {
|
|
659
|
-
if (config.onAfterAll) {
|
|
660
|
-
await config.onAfterAll(ctx);
|
|
661
|
-
}
|
|
662
|
-
}
|
|
764
|
+
schedule();
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
if (inFlight === 0 && (stopped || interrupted || ready.length === 0)) {
|
|
768
|
+
resolve();
|
|
769
|
+
}
|
|
770
|
+
};
|
|
771
|
+
schedule();
|
|
772
|
+
});
|
|
663
773
|
}
|
|
774
|
+
if (printResults) {
|
|
775
|
+
printResultsTable(results);
|
|
776
|
+
printErrors(results);
|
|
777
|
+
printSummary(results, performance.now() - runStartTime, concurrency);
|
|
778
|
+
}
|
|
779
|
+
} catch (error) {
|
|
780
|
+
bodyError = { error };
|
|
664
781
|
} finally {
|
|
782
|
+
const cleanupErrors = await runCleanup();
|
|
783
|
+
unregisterSignals();
|
|
665
784
|
exitSeeding();
|
|
785
|
+
if (bodyError) {
|
|
786
|
+
printCleanupErrors(cleanupErrors);
|
|
787
|
+
} else if (cleanupErrors.length > 0) {
|
|
788
|
+
printCleanupErrors(cleanupErrors.slice(1));
|
|
789
|
+
bodyError = { error: cleanupErrors[0] };
|
|
790
|
+
}
|
|
666
791
|
}
|
|
792
|
+
if (bodyError)
|
|
793
|
+
throw bodyError.error;
|
|
667
794
|
const hasFailure = results.some((r) => r.status === "failed");
|
|
668
795
|
if (hasFailure) {
|
|
669
796
|
return {
|
|
@@ -680,13 +807,6 @@ async function runSeedersCore(seeders, config, options = {}) {
|
|
|
680
807
|
}
|
|
681
808
|
|
|
682
809
|
// src/cli.ts
|
|
683
|
-
var USAGE_ERRORS = new Set([
|
|
684
|
-
"CircularDependencyError",
|
|
685
|
-
"MissingDependencyError",
|
|
686
|
-
"DuplicateSeederError",
|
|
687
|
-
"UnknownSeederError",
|
|
688
|
-
"SeedTargetError"
|
|
689
|
-
]);
|
|
690
810
|
function formatSeedersList(seeders) {
|
|
691
811
|
if (seeders.length === 0)
|
|
692
812
|
return "No seeders registered.";
|
|
@@ -708,7 +828,8 @@ ${colorize("Arguments:", "white", "bold")}
|
|
|
708
828
|
${colorize("Options:", "white", "bold")}
|
|
709
829
|
--only a,b Same as naming the seeders
|
|
710
830
|
--fresh Ignore and overwrite cached steps of the named seeders
|
|
711
|
-
(of every seeder when none are named)
|
|
831
|
+
(of every seeder when none are named), after the
|
|
832
|
+
instance's onFresh hook, if any, resets the target
|
|
712
833
|
--concurrency, -c <n> Run up to <n> independent seeders in parallel (default: 1)
|
|
713
834
|
--continue-on-failure Keep running seeders that do not depend on a failed one
|
|
714
835
|
--allow-remote Seed a database that is not local
|
|
@@ -834,8 +955,7 @@ ${colorize("\uD83C\uDF31 Dry Run", "cyan", "bold")} ${colorize(`(${order.length}
|
|
|
834
955
|
});
|
|
835
956
|
return success ? 0 : 1;
|
|
836
957
|
} catch (error) {
|
|
837
|
-
|
|
838
|
-
console.error(colorize(usage ? error.message : Bun.inspect(error), "red"));
|
|
958
|
+
console.error(colorize(formatError(error), "red"));
|
|
839
959
|
return 1;
|
|
840
960
|
}
|
|
841
961
|
}
|
|
@@ -873,12 +993,302 @@ function createDefineSeeder() {
|
|
|
873
993
|
};
|
|
874
994
|
}
|
|
875
995
|
|
|
876
|
-
// src/
|
|
996
|
+
// src/expect.ts
|
|
997
|
+
import assert, { AssertionError } from "node:assert/strict";
|
|
877
998
|
import { createRequire } from "node:module";
|
|
999
|
+
function isPlainObject(value) {
|
|
1000
|
+
const proto = Object.getPrototypeOf(value);
|
|
1001
|
+
return proto === Object.prototype || proto === null;
|
|
1002
|
+
}
|
|
1003
|
+
function normalizeForEqual(value, seen = new WeakMap) {
|
|
1004
|
+
if (value === null || typeof value !== "object")
|
|
1005
|
+
return value;
|
|
1006
|
+
if (seen.has(value))
|
|
1007
|
+
return seen.get(value);
|
|
1008
|
+
if (Array.isArray(value)) {
|
|
1009
|
+
const normalized = new Array(value.length);
|
|
1010
|
+
seen.set(value, normalized);
|
|
1011
|
+
for (let i = 0;i < value.length; i++) {
|
|
1012
|
+
normalized[i] = normalizeForEqual(value[i], seen);
|
|
1013
|
+
}
|
|
1014
|
+
return normalized;
|
|
1015
|
+
}
|
|
1016
|
+
if (isPlainObject(value)) {
|
|
1017
|
+
const normalized = Object.getPrototypeOf(value) === null ? Object.create(null) : {};
|
|
1018
|
+
seen.set(value, normalized);
|
|
1019
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
1020
|
+
const desc = Object.getOwnPropertyDescriptor(value, key);
|
|
1021
|
+
if (!desc?.enumerable)
|
|
1022
|
+
continue;
|
|
1023
|
+
const entryValue = value[key];
|
|
1024
|
+
if (entryValue !== undefined) {
|
|
1025
|
+
normalized[key] = normalizeForEqual(entryValue, seen);
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
return normalized;
|
|
1029
|
+
}
|
|
1030
|
+
return value;
|
|
1031
|
+
}
|
|
1032
|
+
function sameValueZero(a, b) {
|
|
1033
|
+
return a === b || Number.isNaN(a) && Number.isNaN(b);
|
|
1034
|
+
}
|
|
1035
|
+
function containsValue(actual, expected) {
|
|
1036
|
+
if (typeof actual === "string") {
|
|
1037
|
+
return typeof expected === "string" && actual.includes(expected);
|
|
1038
|
+
}
|
|
1039
|
+
if (Array.isArray(actual)) {
|
|
1040
|
+
return actual.includes(expected);
|
|
1041
|
+
}
|
|
1042
|
+
if (actual instanceof Set) {
|
|
1043
|
+
return actual.has(expected);
|
|
1044
|
+
}
|
|
1045
|
+
if (actual !== null && actual !== undefined && typeof actual[Symbol.iterator] === "function") {
|
|
1046
|
+
for (const item of actual) {
|
|
1047
|
+
if (sameValueZero(item, expected))
|
|
1048
|
+
return true;
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
return false;
|
|
1052
|
+
}
|
|
1053
|
+
function matchesThrown(thrown, expected) {
|
|
1054
|
+
if (typeof expected === "string") {
|
|
1055
|
+
const errorMessage = thrown instanceof Error ? thrown.message : String(thrown);
|
|
1056
|
+
return errorMessage.includes(expected);
|
|
1057
|
+
}
|
|
1058
|
+
if (expected instanceof RegExp) {
|
|
1059
|
+
const errorMessage = thrown instanceof Error ? thrown.message : String(thrown);
|
|
1060
|
+
const re = expected.global || expected.sticky ? new RegExp(expected.source, expected.flags) : expected;
|
|
1061
|
+
return re.test(errorMessage);
|
|
1062
|
+
}
|
|
1063
|
+
if (expected instanceof Error) {
|
|
1064
|
+
if (!(thrown instanceof Error))
|
|
1065
|
+
return false;
|
|
1066
|
+
if (expected.constructor !== Error && !(thrown instanceof expected.constructor))
|
|
1067
|
+
return false;
|
|
1068
|
+
return thrown.message === expected.message;
|
|
1069
|
+
}
|
|
1070
|
+
if (typeof expected === "function") {
|
|
1071
|
+
return thrown instanceof expected;
|
|
1072
|
+
}
|
|
1073
|
+
return false;
|
|
1074
|
+
}
|
|
1075
|
+
function failAssertion(defaultMessage, actual, expected, operator, customMessage) {
|
|
1076
|
+
throw new AssertionError({
|
|
1077
|
+
message: customMessage ?? defaultMessage,
|
|
1078
|
+
actual,
|
|
1079
|
+
expected,
|
|
1080
|
+
operator
|
|
1081
|
+
});
|
|
1082
|
+
}
|
|
1083
|
+
function createMatchers(actual, message, negated) {
|
|
1084
|
+
const checkComparison = (expected, operator, label, compare) => {
|
|
1085
|
+
if (typeof actual !== "number" && typeof actual !== "bigint") {
|
|
1086
|
+
failAssertion(`Expected a number or bigint, received ${typeof actual} (${inspectValue(actual)})`, actual, expected, operator, message);
|
|
1087
|
+
}
|
|
1088
|
+
const passed = compare(actual, expected);
|
|
1089
|
+
if (negated ? passed : !passed) {
|
|
1090
|
+
failAssertion(`Expected ${inspectValue(actual)} ${negated ? "not " : ""}${label} ${inspectValue(expected)}`, actual, expected, negated ? `not ${operator}` : operator, message);
|
|
1091
|
+
}
|
|
1092
|
+
};
|
|
1093
|
+
return {
|
|
1094
|
+
get not() {
|
|
1095
|
+
return createMatchers(actual, message, !negated);
|
|
1096
|
+
},
|
|
1097
|
+
toBe(expected) {
|
|
1098
|
+
if (negated) {
|
|
1099
|
+
assert.notStrictEqual(actual, expected, message);
|
|
1100
|
+
} else {
|
|
1101
|
+
assert.strictEqual(actual, expected, message);
|
|
1102
|
+
}
|
|
1103
|
+
},
|
|
1104
|
+
toEqual(expected) {
|
|
1105
|
+
const normActual = normalizeForEqual(actual);
|
|
1106
|
+
const normExpected = normalizeForEqual(expected);
|
|
1107
|
+
if (negated) {
|
|
1108
|
+
try {
|
|
1109
|
+
assert.notDeepStrictEqual(normActual, normExpected, message);
|
|
1110
|
+
} catch (err) {
|
|
1111
|
+
if (err instanceof AssertionError) {
|
|
1112
|
+
failAssertion(err.message, actual, expected, "not toEqual", message);
|
|
1113
|
+
}
|
|
1114
|
+
throw err;
|
|
1115
|
+
}
|
|
1116
|
+
} else {
|
|
1117
|
+
try {
|
|
1118
|
+
assert.deepStrictEqual(normActual, normExpected, message);
|
|
1119
|
+
} catch (err) {
|
|
1120
|
+
if (err instanceof AssertionError) {
|
|
1121
|
+
failAssertion(err.message, actual, expected, "toEqual", message);
|
|
1122
|
+
}
|
|
1123
|
+
throw err;
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
},
|
|
1127
|
+
toStrictEqual(expected) {
|
|
1128
|
+
if (negated) {
|
|
1129
|
+
assert.notDeepStrictEqual(actual, expected, message);
|
|
1130
|
+
} else {
|
|
1131
|
+
assert.deepStrictEqual(actual, expected, message);
|
|
1132
|
+
}
|
|
1133
|
+
},
|
|
1134
|
+
toBeDefined() {
|
|
1135
|
+
const isDefined = actual !== undefined;
|
|
1136
|
+
if (negated ? isDefined : !isDefined) {
|
|
1137
|
+
failAssertion(negated ? `Expected ${inspectValue(actual)} to be undefined` : "Expected value to be defined, received undefined", actual, undefined, negated ? "not toBeDefined" : "toBeDefined", message);
|
|
1138
|
+
}
|
|
1139
|
+
},
|
|
1140
|
+
toBeUndefined() {
|
|
1141
|
+
if (negated) {
|
|
1142
|
+
assert.notStrictEqual(actual, undefined, message);
|
|
1143
|
+
} else {
|
|
1144
|
+
assert.strictEqual(actual, undefined, message);
|
|
1145
|
+
}
|
|
1146
|
+
},
|
|
1147
|
+
toBeNull() {
|
|
1148
|
+
if (negated) {
|
|
1149
|
+
assert.notStrictEqual(actual, null, message);
|
|
1150
|
+
} else {
|
|
1151
|
+
assert.strictEqual(actual, null, message);
|
|
1152
|
+
}
|
|
1153
|
+
},
|
|
1154
|
+
toBeTruthy() {
|
|
1155
|
+
const isTruthy = Boolean(actual);
|
|
1156
|
+
if (negated ? isTruthy : !isTruthy) {
|
|
1157
|
+
failAssertion(`Expected ${inspectValue(actual)} ${negated ? "not " : ""}to be truthy`, actual, !negated, negated ? "not toBeTruthy" : "toBeTruthy", message);
|
|
1158
|
+
}
|
|
1159
|
+
},
|
|
1160
|
+
toBeFalsy() {
|
|
1161
|
+
const isFalsy = !actual;
|
|
1162
|
+
if (negated ? isFalsy : !isFalsy) {
|
|
1163
|
+
failAssertion(`Expected ${inspectValue(actual)} ${negated ? "not " : ""}to be falsy`, actual, negated, negated ? "not toBeFalsy" : "toBeFalsy", message);
|
|
1164
|
+
}
|
|
1165
|
+
},
|
|
1166
|
+
toContain(expected) {
|
|
1167
|
+
const passed = containsValue(actual, expected);
|
|
1168
|
+
if (negated ? passed : !passed) {
|
|
1169
|
+
failAssertion(`Expected ${inspectValue(actual)} ${negated ? "not " : ""}to contain ${inspectValue(expected)}`, actual, expected, negated ? "not toContain" : "toContain", message);
|
|
1170
|
+
}
|
|
1171
|
+
},
|
|
1172
|
+
toHaveLength(length) {
|
|
1173
|
+
const actualLength = actual !== null && actual !== undefined ? actual.length : undefined;
|
|
1174
|
+
if (typeof actualLength !== "number") {
|
|
1175
|
+
failAssertion(`Expected ${inspectValue(actual)} to have a numeric length property`, actual, length, "toHaveLength", message);
|
|
1176
|
+
}
|
|
1177
|
+
if (negated) {
|
|
1178
|
+
if (actualLength === length) {
|
|
1179
|
+
failAssertion(`Expected ${inspectValue(actual)} not to have length ${length}`, actualLength, length, "not toHaveLength", message);
|
|
1180
|
+
}
|
|
1181
|
+
} else {
|
|
1182
|
+
assert.strictEqual(actualLength, length, message ?? `Expected ${inspectValue(actual)} to have length ${length}, received ${actualLength}`);
|
|
1183
|
+
}
|
|
1184
|
+
},
|
|
1185
|
+
toMatch(expected) {
|
|
1186
|
+
if (typeof actual !== "string") {
|
|
1187
|
+
failAssertion(`Expected a string for toMatch, received ${typeof actual} (${inspectValue(actual)})`, actual, expected, "toMatch", message);
|
|
1188
|
+
}
|
|
1189
|
+
const passed = expected instanceof RegExp ? (expected.global || expected.sticky ? new RegExp(expected.source, expected.flags) : expected).test(actual) : actual.includes(expected);
|
|
1190
|
+
if (negated ? passed : !passed) {
|
|
1191
|
+
failAssertion(`Expected ${inspectValue(actual)} ${negated ? "not " : ""}to match ${inspectValue(expected)}`, actual, expected, negated ? "not toMatch" : "toMatch", message);
|
|
1192
|
+
}
|
|
1193
|
+
},
|
|
1194
|
+
toBeGreaterThan(expected) {
|
|
1195
|
+
checkComparison(expected, ">", "to be greater than", (a, b) => a > b);
|
|
1196
|
+
},
|
|
1197
|
+
toBeGreaterThanOrEqual(expected) {
|
|
1198
|
+
checkComparison(expected, ">=", "to be greater than or equal to", (a, b) => a >= b);
|
|
1199
|
+
},
|
|
1200
|
+
toBeLessThan(expected) {
|
|
1201
|
+
checkComparison(expected, "<", "to be less than", (a, b) => a < b);
|
|
1202
|
+
},
|
|
1203
|
+
toBeLessThanOrEqual(expected) {
|
|
1204
|
+
checkComparison(expected, "<=", "to be less than or equal to", (a, b) => a <= b);
|
|
1205
|
+
},
|
|
1206
|
+
toThrow(expected) {
|
|
1207
|
+
if (typeof actual !== "function") {
|
|
1208
|
+
failAssertion(`Expected a function for toThrow, received ${typeof actual} (${inspectValue(actual)})`, actual, expected, "toThrow", message);
|
|
1209
|
+
}
|
|
1210
|
+
let threw = false;
|
|
1211
|
+
let thrown;
|
|
1212
|
+
try {
|
|
1213
|
+
actual();
|
|
1214
|
+
} catch (err) {
|
|
1215
|
+
threw = true;
|
|
1216
|
+
thrown = err;
|
|
1217
|
+
}
|
|
1218
|
+
if (!threw) {
|
|
1219
|
+
if (!negated) {
|
|
1220
|
+
failAssertion(expected === undefined ? "Expected function to throw" : `Expected function to throw ${inspectValue(expected)}, but it did not throw`, undefined, expected, "toThrow", message);
|
|
1221
|
+
}
|
|
1222
|
+
return;
|
|
1223
|
+
}
|
|
1224
|
+
if (expected === undefined) {
|
|
1225
|
+
if (negated) {
|
|
1226
|
+
failAssertion(`Expected function not to throw, but it threw ${inspectValue(thrown)}`, thrown, undefined, "not toThrow", message);
|
|
1227
|
+
}
|
|
1228
|
+
return;
|
|
1229
|
+
}
|
|
1230
|
+
const matched = matchesThrown(thrown, expected);
|
|
1231
|
+
if (negated ? matched : !matched) {
|
|
1232
|
+
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);
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
};
|
|
1236
|
+
}
|
|
1237
|
+
function createNodeExpect() {
|
|
1238
|
+
return (actual, message) => createMatchers(actual, message, false);
|
|
1239
|
+
}
|
|
1240
|
+
var cachedDefaultExpect;
|
|
1241
|
+
function loadBunExpect() {
|
|
1242
|
+
if (typeof globalThis.Bun === "undefined")
|
|
1243
|
+
return;
|
|
1244
|
+
try {
|
|
1245
|
+
const req = createRequire(import.meta.url);
|
|
1246
|
+
const specifier = ["bun", "test"].join(":");
|
|
1247
|
+
const mod = req(specifier);
|
|
1248
|
+
if (typeof mod.expect === "function")
|
|
1249
|
+
return mod.expect;
|
|
1250
|
+
} catch {}
|
|
1251
|
+
return;
|
|
1252
|
+
}
|
|
1253
|
+
function getDefaultExpect() {
|
|
1254
|
+
if (!cachedDefaultExpect) {
|
|
1255
|
+
cachedDefaultExpect = loadBunExpect() ?? createNodeExpect();
|
|
1256
|
+
}
|
|
1257
|
+
return cachedDefaultExpect;
|
|
1258
|
+
}
|
|
1259
|
+
var expectTarget = () => {
|
|
1260
|
+
throw new Error("unreachable");
|
|
1261
|
+
};
|
|
1262
|
+
var expect = new Proxy(expectTarget, {
|
|
1263
|
+
apply(_target, thisArg, args) {
|
|
1264
|
+
return Reflect.apply(getDefaultExpect(), thisArg, args);
|
|
1265
|
+
},
|
|
1266
|
+
get(_target, prop) {
|
|
1267
|
+
const impl = getDefaultExpect();
|
|
1268
|
+
const value = Reflect.get(impl, prop, impl);
|
|
1269
|
+
return typeof value === "function" ? value.bind(impl) : value;
|
|
1270
|
+
},
|
|
1271
|
+
has(_target, prop) {
|
|
1272
|
+
return Reflect.has(getDefaultExpect(), prop);
|
|
1273
|
+
},
|
|
1274
|
+
ownKeys() {
|
|
1275
|
+
return Reflect.ownKeys(getDefaultExpect());
|
|
1276
|
+
},
|
|
1277
|
+
getOwnPropertyDescriptor(_target, prop) {
|
|
1278
|
+
const desc = Reflect.getOwnPropertyDescriptor(getDefaultExpect(), prop);
|
|
1279
|
+
return desc ? { ...desc, configurable: true } : undefined;
|
|
1280
|
+
},
|
|
1281
|
+
getPrototypeOf() {
|
|
1282
|
+
return Reflect.getPrototypeOf(getDefaultExpect());
|
|
1283
|
+
}
|
|
1284
|
+
});
|
|
1285
|
+
|
|
1286
|
+
// src/lazy-faker.ts
|
|
1287
|
+
import { createRequire as createRequire2 } from "node:module";
|
|
878
1288
|
var loadedFaker;
|
|
879
1289
|
function getDefaultFaker() {
|
|
880
1290
|
if (!loadedFaker) {
|
|
881
|
-
const req =
|
|
1291
|
+
const req = createRequire2(import.meta.url);
|
|
882
1292
|
const mod = req("@faker-js/faker/locale/en");
|
|
883
1293
|
loadedFaker = mod.faker;
|
|
884
1294
|
}
|
|
@@ -935,7 +1345,7 @@ function canonicalStringify(value) {
|
|
|
935
1345
|
return `{${parts.join(",")}}`;
|
|
936
1346
|
}
|
|
937
1347
|
function createStepRunner(config) {
|
|
938
|
-
const { cache, log = true } = config ?? {};
|
|
1348
|
+
const { cache, log = true, aroundStep } = config ?? {};
|
|
939
1349
|
const scopeStorage = new AsyncLocalStorage;
|
|
940
1350
|
let fallbackScope = {
|
|
941
1351
|
seederName: config?.seederName ?? "",
|
|
@@ -988,6 +1398,11 @@ function createStepRunner(config) {
|
|
|
988
1398
|
const useCache = options?.useCache === true;
|
|
989
1399
|
const startTime = performance.now();
|
|
990
1400
|
const prefix = formatPrefix(scope);
|
|
1401
|
+
const identityKey = options?.key ?? description;
|
|
1402
|
+
scope.keyCounts ??= new Map;
|
|
1403
|
+
const occurrence = scope.keyCounts.get(identityKey) ?? 0;
|
|
1404
|
+
scope.keyCounts.set(identityKey, occurrence + 1);
|
|
1405
|
+
const run = () => aroundStep ? aroundStep({ seederName: scope.seederName, key: identityKey, occurrence }, fn) : fn();
|
|
991
1406
|
try {
|
|
992
1407
|
let result;
|
|
993
1408
|
let wasCached = false;
|
|
@@ -1007,7 +1422,7 @@ function createStepRunner(config) {
|
|
|
1007
1422
|
result = stored;
|
|
1008
1423
|
wasCached = true;
|
|
1009
1424
|
} else {
|
|
1010
|
-
result = await
|
|
1425
|
+
result = await run();
|
|
1011
1426
|
const entry = version === undefined ? { __plantr: 1, value: result } : { __plantr: 1, version, value: result };
|
|
1012
1427
|
preloaded?.set(cacheKey, entry);
|
|
1013
1428
|
if (cache.setMany) {
|
|
@@ -1021,9 +1436,9 @@ function createStepRunner(config) {
|
|
|
1021
1436
|
warnedNoCache = true;
|
|
1022
1437
|
print(`${prefix}${colorize("⚠ Cache not configured, running without cache", "yellow")}`);
|
|
1023
1438
|
}
|
|
1024
|
-
result = await
|
|
1439
|
+
result = await run();
|
|
1025
1440
|
} else {
|
|
1026
|
-
result = await
|
|
1441
|
+
result = await run();
|
|
1027
1442
|
}
|
|
1028
1443
|
if (wasCached)
|
|
1029
1444
|
scope.record.cachedSteps.push(description);
|
|
@@ -1056,13 +1471,17 @@ function createSeederInstance(config) {
|
|
|
1056
1471
|
const defineSeeder = createDefineSeeder();
|
|
1057
1472
|
const customFaker = config?.faker && config.faker !== lazyFaker ? config.faker : undefined;
|
|
1058
1473
|
const resolveBaseFaker = () => customFaker ?? getDefaultFaker();
|
|
1474
|
+
const customExpect = config?.expect;
|
|
1059
1475
|
const fakerSeed = config?.fakerSeed;
|
|
1476
|
+
const seedPerStep = fakerSeed !== undefined && config?.fakerSeedScope === "step";
|
|
1060
1477
|
const defaultConcurrency = config?.concurrency;
|
|
1061
1478
|
const runInternal = async (seeders, options, bannerName) => {
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1479
|
+
let stepRunner;
|
|
1480
|
+
const requireStepRunner = () => {
|
|
1481
|
+
if (!stepRunner)
|
|
1482
|
+
throw new Error("plantr: the step runner is used before setup finished");
|
|
1483
|
+
return stepRunner;
|
|
1484
|
+
};
|
|
1066
1485
|
const fakerStorage = new AsyncLocalStorage2;
|
|
1067
1486
|
const resolveActiveFaker = () => {
|
|
1068
1487
|
const slot = fakerStorage.getStore();
|
|
@@ -1108,20 +1527,32 @@ function createSeederInstance(config) {
|
|
|
1108
1527
|
});
|
|
1109
1528
|
const mergedOptions = defaultConcurrency !== undefined && options?.concurrency === undefined ? { ...options, concurrency: defaultConcurrency } : options ?? {};
|
|
1110
1529
|
return runSeedersCore(seeders, {
|
|
1111
|
-
|
|
1530
|
+
prepare: async (resources) => {
|
|
1531
|
+
const cache = typeof config?.cache === "function" ? await config.cache(resources) : config?.cache;
|
|
1532
|
+
stepRunner = createStepRunner({
|
|
1533
|
+
cache,
|
|
1534
|
+
log: options?.verbose ?? true,
|
|
1535
|
+
aroundStep: seedPerStep ? ({ seederName, key, occurrence }, run) => {
|
|
1536
|
+
const name = `${seederName}:${key}${occurrence > 0 ? `#${occurrence}` : ""}`;
|
|
1537
|
+
return fakerStorage.run({ name, isolated: true }, run);
|
|
1538
|
+
} : undefined
|
|
1539
|
+
});
|
|
1540
|
+
},
|
|
1541
|
+
preloadCache: () => stepRunner?.preload(),
|
|
1542
|
+
flushCache: () => stepRunner?.flush(),
|
|
1543
|
+
context: async (resources) => {
|
|
1112
1544
|
const base = {
|
|
1113
1545
|
faker: scopedFaker,
|
|
1114
|
-
step:
|
|
1115
|
-
expect
|
|
1546
|
+
step: requireStepRunner().step,
|
|
1547
|
+
expect: customExpect ?? getDefaultExpect()
|
|
1116
1548
|
};
|
|
1117
1549
|
if (!config?.context)
|
|
1118
1550
|
return base;
|
|
1119
|
-
const extra = await config.context(base);
|
|
1551
|
+
const extra = await config.context(base, resources);
|
|
1120
1552
|
return extra === base ? base : { ...base, ...extra };
|
|
1121
1553
|
},
|
|
1122
|
-
preloadCache: config?.cache?.getAll ? () => stepRunner.preload() : undefined,
|
|
1123
|
-
flushCache: config?.cache?.setMany ? () => stepRunner.flush() : undefined,
|
|
1124
1554
|
createSeederScope: ({ name, fresh, concurrent }) => {
|
|
1555
|
+
const stepRunner = requireStepRunner();
|
|
1125
1556
|
const stepScope = stepRunner.createScope({
|
|
1126
1557
|
seederName: name,
|
|
1127
1558
|
fresh,
|
|
@@ -1138,6 +1569,9 @@ function createSeederInstance(config) {
|
|
|
1138
1569
|
},
|
|
1139
1570
|
bannerName,
|
|
1140
1571
|
target: config?.target,
|
|
1572
|
+
setup: config?.setup,
|
|
1573
|
+
onFresh: config?.onFresh,
|
|
1574
|
+
teardown: config?.teardown,
|
|
1141
1575
|
onBeforeAll: config?.onBeforeAll,
|
|
1142
1576
|
onAfterAll: config?.onAfterAll
|
|
1143
1577
|
}, mergedOptions);
|
|
@@ -1168,21 +1602,49 @@ function hashName(name) {
|
|
|
1168
1602
|
}
|
|
1169
1603
|
return hash >>> 0;
|
|
1170
1604
|
}
|
|
1605
|
+
// src/map-with-limit.ts
|
|
1606
|
+
async function mapWithLimit(items, limit, fn) {
|
|
1607
|
+
if (Number.isNaN(limit) || limit < 1 || Number.isFinite(limit) && !Number.isInteger(limit)) {
|
|
1608
|
+
throw new RangeError(`Invalid limit (${String(limit)}): expected a positive integer or Infinity`);
|
|
1609
|
+
}
|
|
1610
|
+
const list = Array.from(items);
|
|
1611
|
+
const results = new Array(list.length);
|
|
1612
|
+
let next = 0;
|
|
1613
|
+
let failure;
|
|
1614
|
+
const worker = async () => {
|
|
1615
|
+
while (!failure && next < list.length) {
|
|
1616
|
+
const index = next++;
|
|
1617
|
+
try {
|
|
1618
|
+
results[index] = await fn(list[index], index);
|
|
1619
|
+
} catch (error) {
|
|
1620
|
+
failure ??= { error };
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
};
|
|
1624
|
+
await Promise.all(Array.from({ length: Math.min(limit, list.length) }, worker));
|
|
1625
|
+
if (failure)
|
|
1626
|
+
throw failure.error;
|
|
1627
|
+
return results;
|
|
1628
|
+
}
|
|
1171
1629
|
export {
|
|
1172
1630
|
CircularDependencyError,
|
|
1173
1631
|
DuplicateSeederError,
|
|
1174
1632
|
MissingDependencyError,
|
|
1175
1633
|
SeedTargetError,
|
|
1634
|
+
SeedUsageError,
|
|
1176
1635
|
UnknownSeederError,
|
|
1177
1636
|
colorize,
|
|
1178
1637
|
createDefineSeeder,
|
|
1179
1638
|
createSeederInstance,
|
|
1180
1639
|
createStepRunner,
|
|
1181
1640
|
describeTarget,
|
|
1182
|
-
|
|
1641
|
+
expect,
|
|
1183
1642
|
lazyFaker as faker,
|
|
1184
1643
|
formatDuration,
|
|
1644
|
+
isSeedUsageError,
|
|
1185
1645
|
isSeedingActive,
|
|
1646
|
+
mapWithLimit,
|
|
1186
1647
|
resolveDependencyOrder,
|
|
1187
|
-
runSeedersCore
|
|
1648
|
+
runSeedersCore,
|
|
1649
|
+
usageErrorSymbol
|
|
1188
1650
|
};
|