Reproducibility
An initialize() instance reproduces from one number: its clock. The clock and an optional salt determine every value the instance produces. By default, the clock is the time of the initialize() call, so each run varies, dates look realistic, and the clock alone replays the run.
The clock is the entropy
const { T, Fabricator, context } = initialize();
// ...fabricate, and if something fails:
context.clock; // log thisThe clock is recorded once per initialize() call and is part of every field's trace. So every run produces different data, and passing the logged number (milliseconds since the epoch) back reproduces that run exactly:
initialize(); // wall-clock instant of this call — the default
initialize({ clock: logged }); // replay a recorded run
initialize({ clock: new Date("2024-06-01") }); // pinned to that instantFor most instances, that is all you need. Nothing else needs configuring.
The clock is also what "now" means to fabricator. T.date.past, T.date.future, and any .as(produce) or T.opaque producer that reads clock from its context all use it. Pinning the clock freezes the dates, and since the clock is in every trace, it freezes the rest of the run too.
The only other setting is clock: "derived", which computes a fixed instant from the instance salt instead of reading the time. That instant can fall anywhere in the representable Date range, so an absurd date is expected, not a bug. Use it only when replay must not depend on the time at all.
A fork or wrap that doesn't set clock inherits its parent's. The exception is an explicit "derived" clock: fork({ salt: layer(...) }) without its own clock derives a new "now" from the combined salt.
Salt is optional
Most instances don't need a salt, for the reason above: the clock already varies every run and replays any of them.
Avoid a salt unless you need one, because it is a second value you have to record and pass back with the clock to reproduce a run. A salt is useful in these cases:
- Replay that doesn't depend on the time. Pair the salt with
clock: "derived"and the salt becomes the only value to record. The cost is an absurd "now", drawn from the wholeDaterange. - One construction that should draw different data from the rest of the instance. For this, you usually want a per-construction salt, not an instance-wide one.
- Setting a salt from outside the code. That's what env-var salting is for. It sets the salt only, and an unpinned
clockstill varies, so replay still needscontext.clock.
const { T, Fabricator, salt } = initialize({ salt: "1234" });Env-var salting
If initialize() gets no salt, FABRICATOR_SALT supplies one. If the variable is unset, the salt stays empty.
FABRICATOR_SALT=repro-1234 bun testThis sets a salt for a whole test run without changing any code.
That is why fabricator doesn't read the common SEED or RANDOM_SEED variables. Someone setting those expects a stable run, and a salt alone won't give them one unless the clock is derived. Setting fabricator's salt is a decision about fabricator, so it has its own variable.
Isolation between instances
Each initialize() call has its own generator and its own internal state. Separate instances never affect each other. That makes it safe for parallel tests to each use their own salt, and for two unrelated fabricators to run in the same process.
Construction order
Every instance has one construction counter. Each new Fabricator(...) takes the next number from it, no matter which module makes the call, so two constructions in a row never get identical data.
Adding, removing, or reordering a construction shifts the constructions after it on the same instance. fork and wrap each start a fresh counter, which is how an integration or a test keeps its work separate. Fields within one construction are keyed by their position in the schema, so editing the schema doesn't shift their siblings.
Salting one construction
new Fabricator(schema, { salt: "fixed-user" });This replaces the salt for one build and changes nothing else. The build still takes the next number from the instance's counter and still uses the instance's clock, the same as an unsalted build.
salt isn't special. new Fabricator(schema, options) accepts every field of a .trace, and each one you pass replaces that field. A salted build is an ordinary build that happens to draw different data from its neighbors.
So a salt does not hold one construction still. It still shifts, and is shifted by, the constructions around it. For a build with its own counter that nothing else on the instance can affect, use fork:
const forked = instance.fork({ salt: "fixed-user" });
new forked.Fabricator(schema); // its own counters, its own universeA plain salt replaces the instance's salt for that Fabricator, so the build no longer changes when the run is given a different salt. For an identity that should still change with the run, such as a schema's name or a test's id, wrap it in layer(...) to add to the salt instead:
import { layer } from "@ghostry/fabricator";
new Fabricator(schema, { salt: layer("some-identity") });This adds "some-identity" to the instance's salt ([...instance.salt, "some-identity"]) instead of replacing it, so the build still changes when the instance's salt does. See Composing instead of replacing: layer(...) for details, and Deriving a related instance: fork for the same idea applied to a whole instance.
Deriving a related instance: fork
initialize() creates an instance. fork creates a related one, based on the instance it is called on:
const base = initialize({ salt: "base" });
const A = base.fork({ salt: "A" });
A.salt; // ["A"] — replacedWhatever you pass to fork overrides the base, and whatever you leave out is inherited, including algorithm, types, limits, and clock. A fork can do everything an initialize() result can: it has its own Fabricator, its own combinatorial and coverage, and its own fork, so forks can be forked.
Use fork first. A fork is a configuration you hold as a value. You can pass it around, name it in a signature, keep it in a module, and build through it whenever you like. Each call through a fork uses that fork's configuration and nothing else, so you can tell what a call draws from by reading it. wrap gives that up in exchange for not having to pass the scope around, and is only worth it when you can't.
A fork inherits its base's clock as-is, whatever happens to the salt. The exception is an explicit clock: "derived", which is derived again from the fork's salt (see The clock is the entropy). So fork({ salt: layer(...) }) without its own clock gets a different derived clock than its base.
A fork's salt replaces the base's by default, as it does everywhere in fabricator. To add to the base's salt instead, use layer(...):
const forked = base.fork({ salt: layer("my-fork") });
forked.salt; // ["base", "my-fork"] — composedlayer works the same way in fork, wrap, and a single new Fabricator(schema, { salt }). See Composing instead of replacing: layer(...).
Composing instead of replacing: layer(...)
A plain salt always replaces whatever salt applied before. layer(salt) does the opposite: it adds to the salt already in effect.
import { initialize, layer } from "@ghostry/fabricator";
const base = initialize({ salt: "base" });
base.fork({ salt: "a" }).salt; // ["a"] — replaced
base.fork({ salt: layer("a") }).salt; // ["base", "a"] — composedlayer works the same everywhere a salt is accepted:
fork({ salt: layer(...) })adds to the instance's salt.wrap({ salt: layer(...) })adds to the salt of the instance it is called on, the same asfork(see below). Nested wraps through the enclosingscopekeep adding.new Fabricator(schema, { salt: layer(...) })adds to the instance's salt, or to an activewrap's salt if the build happens inside one. It applies to that one build only.
Use layer(...) when an identity, such as a test's name or a schema's name, should still change when the run's salt changes. The harness integration does this with each test's name for you. Use a plain salt for the opposite case: data that must stay the same no matter what.
When you cannot thread the scope: wrap
wrap makes a fork apply automatically to a block of code. Ordinary calls inside the block use it without you passing anything.
Use it when you can't reasonably get the scope to the code that needs it: a test body or callback you don't own, a deep call stack you don't want to pass a parameter through, or code already written against a destructured Fabricator. In those cases, wrap saves you from passing the scope. Everywhere else, use the scope the block is given or a fork you hold as a value. Explicit calls are easier to read.
The cost is that inside a wrap, the object you call through no longer tells you which configuration the call uses. That is exactly what wrap is for, not a flaw:
const { T, Fabricator, combinatorial, wrap } = initialize({ salt: "base" });
wrap({ salt: layer("a") }, (scope) => {
new Fabricator(T.number).fabricate(); // picks up the wrap automatically
new scope.Fabricator(T.number).fabricate(); // identical source, used explicitly
[...combinatorial(T.boolean)]; // also picks up the wrap
});wrap applies to builds on the instance it was called on and on that instance's ancestors. See Ambience governs the receiver and its ancestors. The block also gets the fork as scope. Use scope when being explicit is clearer, or when work has to outlive the block. A callback stored and called later runs outside the block, so only scope still carries the wrap's configuration.
A wrap builds on the instance it was called on, just like fork, whether or not another wrap is already open. So a nested wrap called through the enclosing scope adds to it, and one called through an instance from outside the block starts over:
wrap({ salt: layer("a") }, (scope) => {
scope.wrap({ salt: layer("b") }, (inner) => {
inner.salt; // [...base.salt, "a", "b"] — composed
});
wrap({ salt: layer("b") }, (inner) => {
inner.salt; // [...base.salt, "b"] — restated
});
});The second case matters because a destructured wrap is always bound to the instance it came from. To add to whatever is in effect when you don't have the enclosing scope, call through context.scope():
wrap({ salt: layer("a") }, () => {
context.scope().wrap({ salt: layer("b") }, (inner) => {
inner.salt; // [...base.salt, "a", "b"]
});
});scope is a function, not a property, so it is safe to destructure from context. A destructured scope still looks up the current scope each time you call it. The other members of context are getters, so destructuring or spreading them freezes their values. A frozen value is just out of date, but a frozen scope would silently build on the wrong instance. Destructuring context itself is fine, and is how these examples get it.
Ambience governs the receiver and its ancestors
A wrap applies to builds on the instance it was called on and on that instance's ancestors. It never applies to that instance's descendants, its siblings, or a different initialize(). If several wraps apply, the innermost one wins. If none apply, an instance uses its own configuration.
const A = base.fork({ salt: layer("A") });
const B = base.fork({ salt: layer("B") });
B.wrap({ salt: layer("b") }, () => {
new B.Fabricator(T.number); // [...base.salt, "B", "b"] — the receiver
new base.Fabricator(T.number); // [...base.salt, "B", "b"] — an ancestor
new A.Fabricator(T.number); // [...base.salt, "A"] — a sibling
});Look at the middle line. The call goes through base, but the configuration is B's wrap. A destructured Fabricator is bound to the instance it came from and is affected whenever that instance is. That is what lets it work without passing anything, and it is also why, inside a wrap, you can't tell from the call what it draws from. If that matters at a call site, build through a fork instead of using wrap.
A fork of the wrapped instance uses its own configuration, whether it was created before the wrap or during it. To carry a wrap's salt into a new fork, fork the scope: scope, or base.context.scope() if you don't have it:
base.wrap({ salt: layer("a") }, (scope) => {
const C = scope.fork({ salt: layer("C") });
new C.Fabricator(T.number); // [...base.salt, "a", "C"]
const D = base.fork({ salt: layer("C") });
new D.Fabricator(T.number); // [...base.salt, "C"] — no wrap layer
});What a wrap applies to depends on ancestry, not on how the wraps are nested. Below, B's wrap is opened inside base's wrap. B's wrap applies to base, because base is B's ancestor. The outer wrap's scope is a different descendant of base, not an ancestor of B, so it keeps its own configuration:
base.wrap({ salt: layer("a") }, (scope) => {
B.wrap({ salt: layer("b") }, () => {
new base.Fabricator(T.number); // [...base.salt, "B", "b"] — an ancestor of B
new scope.Fabricator(T.number); // [...base.salt, "a"] — not an ancestor of B
});
});context.depth counts the wraps that apply to an instance. Inside B's wrap, A.context.depth is 0 and B.context.depth is 1. A wrap's own scope is a descendant of the wrapped instance, so scope.context.depth is 0; the wrap's configuration is already its own.
The instance that initialize() returned gets no special treatment. A wrap is tied to whichever instance it was called on. If you fork an application-wide configuration and use that fork as your root, destructuring from it and never touching the original again, wraps on it work exactly the same. Forks of that fork are not affected and use their own configuration.
Lineage belongs to the instance, not to the carrier. a.root === b.root tells you whether two instances share a lineage, and two separate initialize() calls never see each other's wraps, even when given the same stack. initialize({ stack }) only chooses the carrier.
Async blocks
block can be async, and the wrap still applies after await:
await wrap({ salt: layer("a") }, async (scope) => {
new Fabricator(T.number).fabricate(); // wrapped
await something();
new Fabricator(T.number).fabricate(); // still wrapped
new scope.Fabricator(T.number).fabricate(); // wrapped, explicitly
});Two wraps running at the same time stay separate. Neither sees the other's salt, and neither leaks outside its own block.
This works because the wrap is carried by AsyncLocalStorage wherever node:async_hooks exists, which includes Node, Bun, and Deno. Nothing needs configuring. Fabricator picks the right carrier when it is imported.
Runtime support
A runtime without node:async_hooks, most likely a browser bundle, falls back to a synchronous carrier. Its wrap ends at the block's first await. Instead of letting a later build silently use the base instance, wrap rejects the block:
wrap({ salt: layer("a") }, async () => {}); // throws SynchronousStackErrorIt throws on any async block, even one that only uses scope, because wrap can't know whether later code will rely on the wrap. scope still works there. It is an ordinary Instance that doesn't depend on the wrap being active, so a synchronous block can hand scope to async work and the configuration lasts as long as needed.
To use async blocks on such a runtime, supply your own carrier that supports async:
initialize({ stack: someAsyncCarrier });context
instance.context reads the configuration in effect right now: the active wrap's, or the instance's own when no wrap applies.
wrap({ salt: layer("a") }, () => {
context.salt; // [...base.salt, "a"] — same as scope.salt, read ambiently
});It is a live view, not a snapshot. A context you got before a wrap reflects the wrap while it is active and goes back afterward.
Which field gets which randomness
There are two separate questions here, with the same answer:
"Does changing a field change what other fields produce?" No. Each field draws from its own stream, based on its position in the schema, such as its field name or tuple index. It never depends on how many fields came before it. Adding, removing, reordering, or renaming a field doesn't change any other field's randomness.
"Does skipping a draw change other fields?" Also no. Some fields only draw sometimes. An omittable field, for example, only draws its value when it decides the key is present. Skipping that draw only affects where that field is in its own stream on the next call. It can't affect any other field, because each field already has its own generator. That is why object.omittable, object.optional, nullable, and undefinable skip their inner draw when they don't need it: it costs nothing in reproducibility.
So editing a schema never changes unrelated fields, and neither does calling .fabricate() fewer times on a Fabricator you already built.
.trace
Every built Fabricator records where its randomness comes from in its trace property. This includes parts that never draw anything themselves, such as a bare T.object or T.always. That is what makes a nested part replayable.
const NameField = new Fabricator(T.string.whereby({ length: { max: 20 } }));
NameField.fabricate();
NameField.trace;
// { salt: [], clock: 1234567890000, path: [], kind: "string", ordinal: 0 }The trace has five fields, and together they determine that field's stream:
saltis the instance's salt, not anything specific to the field.clockis the instant this build treats as "now" (see The clock is the entropy). Every field's stream depends on it, not just date fields.pathis the field's position in its build. It is empty here because this Fabricator is the whole build. A nested field would have something like["address", "city"].kindis the field's primitive kind.ordinalis which build on the instance this is. It isnullforcombinatorialandcoveragebuilds, which don't take one.
new Fabricator(schema, trace) reproduces exactly what that schema produced as part of a larger build. Pass the part's own schema and its trace. The same sequence of .fabricate() calls then gives the same values, starting from the first draw.
Some kinds of value don't depend only on their own stream. For these, replay the parent instead:
- a
.refine()compute field:.fabricate()throws without the parent object - a
recursive.selfnode:.fabricate()throws without the enclosingT.recursive - an
.override()field: replaying the field's own schema gives the random value the parent threw away
Bring your own PRNG
initialize({ salt: "1234", algorithm: (seed) => myPrng(seed) });algorithm is a function that takes a seed and returns a () => number in [0, 1), a drop-in replacement for Math.random. The default is a built-in sfc32 generator.
The seed it receives is not your salt. It describes one whole field: salt, clock, path, kind, and ordinal. That is why every field in every build gets its own independent stream, and why a custom algorithm gets that independence for free. It is called once per field, with a different seed each time.
Output is not cryptographically secure. See Security.
