plantr 2.2.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 +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +383 -221
- package/dist/src/cli.d.ts.map +1 -1
- package/dist/src/create-seeder-instance.d.ts +76 -10
- 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/formatting.d.ts +16 -0
- 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 +39 -8
- 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 +7 -0
- package/dist/src/types.d.ts.map +1 -1
- package/index.ts +5 -0
- package/package.json +1 -1
- package/readme.md +161 -21
- package/src/cli.ts +4 -13
- package/src/create-seeder-instance.ts +119 -21
- package/src/dependency-resolver.ts +5 -4
- package/src/errors.ts +29 -0
- package/src/formatting.ts +32 -1
- package/src/map-with-limit.ts +48 -0
- package/src/run-seeders.ts +304 -205
- package/src/signals.ts +54 -0
- package/src/step.ts +30 -4
- package/src/types.ts +7 -0
package/dist/index.js
CHANGED
|
@@ -4,29 +4,43 @@ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
|
4
4
|
// src/cli.ts
|
|
5
5
|
import { parseArgs } from "node:util";
|
|
6
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
|
+
|
|
7
21
|
// src/dependency-resolver.ts
|
|
8
|
-
class CircularDependencyError extends
|
|
22
|
+
class CircularDependencyError extends SeedUsageError {
|
|
9
23
|
constructor(cycle) {
|
|
10
24
|
super(`Circular dependency detected in seeders: ${cycle.join(" -> ")} -> ${cycle[0] ?? ""}`);
|
|
11
25
|
this.name = "CircularDependencyError";
|
|
12
26
|
}
|
|
13
27
|
}
|
|
14
28
|
|
|
15
|
-
class MissingDependencyError extends
|
|
29
|
+
class MissingDependencyError extends SeedUsageError {
|
|
16
30
|
constructor(seeder, missingDep) {
|
|
17
31
|
super(`Seeder "${seeder}" depends on "${missingDep}" which does not exist`);
|
|
18
32
|
this.name = "MissingDependencyError";
|
|
19
33
|
}
|
|
20
34
|
}
|
|
21
35
|
|
|
22
|
-
class DuplicateSeederError extends
|
|
36
|
+
class DuplicateSeederError extends SeedUsageError {
|
|
23
37
|
constructor(name) {
|
|
24
38
|
super(`Two seeders are named "${name}"; seeder names must be unique`);
|
|
25
39
|
this.name = "DuplicateSeederError";
|
|
26
40
|
}
|
|
27
41
|
}
|
|
28
42
|
|
|
29
|
-
class UnknownSeederError extends
|
|
43
|
+
class UnknownSeederError extends SeedUsageError {
|
|
30
44
|
constructor(name, known) {
|
|
31
45
|
super(`Unknown seeder "${name}". Registered seeders: ${known.join(", ") || "(none)"}`);
|
|
32
46
|
this.name = "UnknownSeederError";
|
|
@@ -146,6 +160,9 @@ function inspectValue(value, options) {
|
|
|
146
160
|
}
|
|
147
161
|
return nodeInspect(value, { colors: options?.colors ?? false });
|
|
148
162
|
}
|
|
163
|
+
function formatError(error, options) {
|
|
164
|
+
return isSeedUsageError(error) ? error.message : inspectValue(error, options);
|
|
165
|
+
}
|
|
149
166
|
var colors = {
|
|
150
167
|
reset: "\x1B[0m",
|
|
151
168
|
bold: "\x1B[1m",
|
|
@@ -240,7 +257,7 @@ function printErrors(results) {
|
|
|
240
257
|
for (const result of failed) {
|
|
241
258
|
const where = result.failedStep ? ` in step "${result.failedStep}"` : "";
|
|
242
259
|
console.log(colorize(`❌ Seeder "${result.name}" failed${where}:`, "red"));
|
|
243
|
-
const details =
|
|
260
|
+
const details = formatError(result.error, { colors: supportsColor() });
|
|
244
261
|
for (const line of details.split(`
|
|
245
262
|
`))
|
|
246
263
|
console.log(` ${line}`);
|
|
@@ -254,6 +271,20 @@ function printErrors(results) {
|
|
|
254
271
|
console.log("");
|
|
255
272
|
}
|
|
256
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
|
+
}
|
|
257
288
|
function printSeederHeader(name, index, total, description) {
|
|
258
289
|
const seederIndex = `[${index + 1}/${total}]`;
|
|
259
290
|
const headerLine = `━━━ ${seederIndex} ${name} ${"━".repeat(Math.max(0, 50 - name.length - seederIndex.length))}`;
|
|
@@ -361,8 +392,40 @@ function exitSeeding() {
|
|
|
361
392
|
state[key] = next > 0;
|
|
362
393
|
}
|
|
363
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
|
+
|
|
364
427
|
// src/run-seeders.ts
|
|
365
|
-
class SeedTargetError extends
|
|
428
|
+
class SeedTargetError extends SeedUsageError {
|
|
366
429
|
constructor(label) {
|
|
367
430
|
super(`Refusing to seed ${label}: it is not a local database. Pass allowRemote (CLI: --allow-remote) to seed it on purpose.`);
|
|
368
431
|
this.name = "SeedTargetError";
|
|
@@ -413,7 +476,8 @@ async function runSeedersCore(seeders, config, options = {}) {
|
|
|
413
476
|
only,
|
|
414
477
|
fresh = false,
|
|
415
478
|
allowRemote = false,
|
|
416
|
-
concurrency = 1
|
|
479
|
+
concurrency = 1,
|
|
480
|
+
handleSignals = true
|
|
417
481
|
} = options;
|
|
418
482
|
if (Number.isNaN(concurrency) || concurrency < 1 || Number.isFinite(concurrency) && !Number.isInteger(concurrency)) {
|
|
419
483
|
throw new RangeError(`Invalid concurrency (${String(concurrency)}): expected a positive integer or Infinity`);
|
|
@@ -447,7 +511,46 @@ async function runSeedersCore(seeders, config, options = {}) {
|
|
|
447
511
|
const outputs = {};
|
|
448
512
|
const failedSeeders = new Set;
|
|
449
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
|
+
};
|
|
450
548
|
enterSeeding();
|
|
549
|
+
const unregisterSignals = handleSignals ? onTerminationSignal(async () => {
|
|
550
|
+
interrupted = true;
|
|
551
|
+
printCleanupErrors(await runCleanup());
|
|
552
|
+
}) : () => {};
|
|
553
|
+
let bodyError;
|
|
451
554
|
try {
|
|
452
555
|
if (verbose) {
|
|
453
556
|
printStartBanner({
|
|
@@ -461,218 +564,233 @@ async function runSeedersCore(seeders, config, options = {}) {
|
|
|
461
564
|
if (config.onBeforeAll) {
|
|
462
565
|
await config.onBeforeAll();
|
|
463
566
|
}
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
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];
|
|
468
598
|
}
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
const
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
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 ?? []
|
|
479
610
|
};
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
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
|
-
}
|
|
611
|
+
if (verbose) {
|
|
612
|
+
if (concurrent) {
|
|
613
|
+
printConcurrentComplete(name, durationMs, true);
|
|
614
|
+
} else {
|
|
615
|
+
printSeederComplete(durationMs, true);
|
|
502
616
|
}
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
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);
|
|
523
637
|
}
|
|
524
|
-
return false;
|
|
525
638
|
}
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
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);
|
|
545
660
|
}
|
|
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;
|
|
661
|
+
continue;
|
|
553
662
|
}
|
|
554
663
|
}
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
const dependents = new Map;
|
|
558
|
-
for (const name of orderedNames) {
|
|
559
|
-
remainingDeps.set(name, 0);
|
|
560
|
-
dependents.set(name, []);
|
|
664
|
+
if (verbose) {
|
|
665
|
+
printSeederHeader(name, i, orderedNames.length, seeder.description);
|
|
561
666
|
}
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
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
|
-
}
|
|
667
|
+
const ok = await executeSeeder(name);
|
|
668
|
+
if (!ok && !continueOnFailure) {
|
|
669
|
+
break;
|
|
571
670
|
}
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
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);
|
|
582
687
|
}
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
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;
|
|
697
|
+
}
|
|
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;
|
|
587
718
|
}
|
|
588
719
|
}
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
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);
|
|
601
750
|
}
|
|
602
751
|
}
|
|
603
|
-
return ready.splice(bestIdx, 1)[0];
|
|
604
752
|
};
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
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);
|
|
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;
|
|
631
761
|
} else {
|
|
632
|
-
|
|
762
|
+
markSettled(name);
|
|
633
763
|
}
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
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
|
-
}
|
|
764
|
+
schedule();
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
if (inFlight === 0 && (stopped || interrupted || ready.length === 0)) {
|
|
768
|
+
resolve();
|
|
769
|
+
}
|
|
770
|
+
};
|
|
771
|
+
schedule();
|
|
772
|
+
});
|
|
672
773
|
}
|
|
774
|
+
if (printResults) {
|
|
775
|
+
printResultsTable(results);
|
|
776
|
+
printErrors(results);
|
|
777
|
+
printSummary(results, performance.now() - runStartTime, concurrency);
|
|
778
|
+
}
|
|
779
|
+
} catch (error) {
|
|
780
|
+
bodyError = { error };
|
|
673
781
|
} finally {
|
|
782
|
+
const cleanupErrors = await runCleanup();
|
|
783
|
+
unregisterSignals();
|
|
674
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
|
+
}
|
|
675
791
|
}
|
|
792
|
+
if (bodyError)
|
|
793
|
+
throw bodyError.error;
|
|
676
794
|
const hasFailure = results.some((r) => r.status === "failed");
|
|
677
795
|
if (hasFailure) {
|
|
678
796
|
return {
|
|
@@ -689,13 +807,6 @@ async function runSeedersCore(seeders, config, options = {}) {
|
|
|
689
807
|
}
|
|
690
808
|
|
|
691
809
|
// src/cli.ts
|
|
692
|
-
var USAGE_ERRORS = new Set([
|
|
693
|
-
"CircularDependencyError",
|
|
694
|
-
"MissingDependencyError",
|
|
695
|
-
"DuplicateSeederError",
|
|
696
|
-
"UnknownSeederError",
|
|
697
|
-
"SeedTargetError"
|
|
698
|
-
]);
|
|
699
810
|
function formatSeedersList(seeders) {
|
|
700
811
|
if (seeders.length === 0)
|
|
701
812
|
return "No seeders registered.";
|
|
@@ -717,7 +828,8 @@ ${colorize("Arguments:", "white", "bold")}
|
|
|
717
828
|
${colorize("Options:", "white", "bold")}
|
|
718
829
|
--only a,b Same as naming the seeders
|
|
719
830
|
--fresh Ignore and overwrite cached steps of the named seeders
|
|
720
|
-
(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
|
|
721
833
|
--concurrency, -c <n> Run up to <n> independent seeders in parallel (default: 1)
|
|
722
834
|
--continue-on-failure Keep running seeders that do not depend on a failed one
|
|
723
835
|
--allow-remote Seed a database that is not local
|
|
@@ -843,8 +955,7 @@ ${colorize("\uD83C\uDF31 Dry Run", "cyan", "bold")} ${colorize(`(${order.length}
|
|
|
843
955
|
});
|
|
844
956
|
return success ? 0 : 1;
|
|
845
957
|
} catch (error) {
|
|
846
|
-
|
|
847
|
-
console.error(colorize(usage ? error.message : inspectValue(error), "red"));
|
|
958
|
+
console.error(colorize(formatError(error), "red"));
|
|
848
959
|
return 1;
|
|
849
960
|
}
|
|
850
961
|
}
|
|
@@ -1234,7 +1345,7 @@ function canonicalStringify(value) {
|
|
|
1234
1345
|
return `{${parts.join(",")}}`;
|
|
1235
1346
|
}
|
|
1236
1347
|
function createStepRunner(config) {
|
|
1237
|
-
const { cache, log = true } = config ?? {};
|
|
1348
|
+
const { cache, log = true, aroundStep } = config ?? {};
|
|
1238
1349
|
const scopeStorage = new AsyncLocalStorage;
|
|
1239
1350
|
let fallbackScope = {
|
|
1240
1351
|
seederName: config?.seederName ?? "",
|
|
@@ -1287,6 +1398,11 @@ function createStepRunner(config) {
|
|
|
1287
1398
|
const useCache = options?.useCache === true;
|
|
1288
1399
|
const startTime = performance.now();
|
|
1289
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();
|
|
1290
1406
|
try {
|
|
1291
1407
|
let result;
|
|
1292
1408
|
let wasCached = false;
|
|
@@ -1306,7 +1422,7 @@ function createStepRunner(config) {
|
|
|
1306
1422
|
result = stored;
|
|
1307
1423
|
wasCached = true;
|
|
1308
1424
|
} else {
|
|
1309
|
-
result = await
|
|
1425
|
+
result = await run();
|
|
1310
1426
|
const entry = version === undefined ? { __plantr: 1, value: result } : { __plantr: 1, version, value: result };
|
|
1311
1427
|
preloaded?.set(cacheKey, entry);
|
|
1312
1428
|
if (cache.setMany) {
|
|
@@ -1320,9 +1436,9 @@ function createStepRunner(config) {
|
|
|
1320
1436
|
warnedNoCache = true;
|
|
1321
1437
|
print(`${prefix}${colorize("⚠ Cache not configured, running without cache", "yellow")}`);
|
|
1322
1438
|
}
|
|
1323
|
-
result = await
|
|
1439
|
+
result = await run();
|
|
1324
1440
|
} else {
|
|
1325
|
-
result = await
|
|
1441
|
+
result = await run();
|
|
1326
1442
|
}
|
|
1327
1443
|
if (wasCached)
|
|
1328
1444
|
scope.record.cachedSteps.push(description);
|
|
@@ -1357,12 +1473,15 @@ function createSeederInstance(config) {
|
|
|
1357
1473
|
const resolveBaseFaker = () => customFaker ?? getDefaultFaker();
|
|
1358
1474
|
const customExpect = config?.expect;
|
|
1359
1475
|
const fakerSeed = config?.fakerSeed;
|
|
1476
|
+
const seedPerStep = fakerSeed !== undefined && config?.fakerSeedScope === "step";
|
|
1360
1477
|
const defaultConcurrency = config?.concurrency;
|
|
1361
1478
|
const runInternal = async (seeders, options, bannerName) => {
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
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
|
+
};
|
|
1366
1485
|
const fakerStorage = new AsyncLocalStorage2;
|
|
1367
1486
|
const resolveActiveFaker = () => {
|
|
1368
1487
|
const slot = fakerStorage.getStore();
|
|
@@ -1408,20 +1527,32 @@ function createSeederInstance(config) {
|
|
|
1408
1527
|
});
|
|
1409
1528
|
const mergedOptions = defaultConcurrency !== undefined && options?.concurrency === undefined ? { ...options, concurrency: defaultConcurrency } : options ?? {};
|
|
1410
1529
|
return runSeedersCore(seeders, {
|
|
1411
|
-
|
|
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) => {
|
|
1412
1544
|
const base = {
|
|
1413
1545
|
faker: scopedFaker,
|
|
1414
|
-
step:
|
|
1546
|
+
step: requireStepRunner().step,
|
|
1415
1547
|
expect: customExpect ?? getDefaultExpect()
|
|
1416
1548
|
};
|
|
1417
1549
|
if (!config?.context)
|
|
1418
1550
|
return base;
|
|
1419
|
-
const extra = await config.context(base);
|
|
1551
|
+
const extra = await config.context(base, resources);
|
|
1420
1552
|
return extra === base ? base : { ...base, ...extra };
|
|
1421
1553
|
},
|
|
1422
|
-
preloadCache: config?.cache?.getAll ? () => stepRunner.preload() : undefined,
|
|
1423
|
-
flushCache: config?.cache?.setMany ? () => stepRunner.flush() : undefined,
|
|
1424
1554
|
createSeederScope: ({ name, fresh, concurrent }) => {
|
|
1555
|
+
const stepRunner = requireStepRunner();
|
|
1425
1556
|
const stepScope = stepRunner.createScope({
|
|
1426
1557
|
seederName: name,
|
|
1427
1558
|
fresh,
|
|
@@ -1438,6 +1569,9 @@ function createSeederInstance(config) {
|
|
|
1438
1569
|
},
|
|
1439
1570
|
bannerName,
|
|
1440
1571
|
target: config?.target,
|
|
1572
|
+
setup: config?.setup,
|
|
1573
|
+
onFresh: config?.onFresh,
|
|
1574
|
+
teardown: config?.teardown,
|
|
1441
1575
|
onBeforeAll: config?.onBeforeAll,
|
|
1442
1576
|
onAfterAll: config?.onAfterAll
|
|
1443
1577
|
}, mergedOptions);
|
|
@@ -1468,11 +1602,36 @@ function hashName(name) {
|
|
|
1468
1602
|
}
|
|
1469
1603
|
return hash >>> 0;
|
|
1470
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
|
+
}
|
|
1471
1629
|
export {
|
|
1472
1630
|
CircularDependencyError,
|
|
1473
1631
|
DuplicateSeederError,
|
|
1474
1632
|
MissingDependencyError,
|
|
1475
1633
|
SeedTargetError,
|
|
1634
|
+
SeedUsageError,
|
|
1476
1635
|
UnknownSeederError,
|
|
1477
1636
|
colorize,
|
|
1478
1637
|
createDefineSeeder,
|
|
@@ -1482,7 +1641,10 @@ export {
|
|
|
1482
1641
|
expect,
|
|
1483
1642
|
lazyFaker as faker,
|
|
1484
1643
|
formatDuration,
|
|
1644
|
+
isSeedUsageError,
|
|
1485
1645
|
isSeedingActive,
|
|
1646
|
+
mapWithLimit,
|
|
1486
1647
|
resolveDependencyOrder,
|
|
1487
|
-
runSeedersCore
|
|
1648
|
+
runSeedersCore,
|
|
1649
|
+
usageErrorSymbol
|
|
1488
1650
|
};
|