Skip to content
Logo

Writing extensions

An extension is an object passed to initialize. It is one of two kinds, told apart by kind:

  • A producer claims identities: its library's schemas become usable as block identities, and it produces their values.
  • An observer claims nothing, and only runs code around each testing block, like a helper recording which blocks ran.

Both have a name, used in error messages, and a frame, which runs once for each testing block.

Observers

import type { Extension } from "@ghostry/extern";
 
const recorder = (): Extension => ({
  kind: "observer",
  name: "recorder",
  *frame() {
    record("entered");
    yield {};
  },
});

An observer leaves every block behaving exactly as it would with no extension.

Producers

A producer says which identities it claims with supports, and yields a produce function that makes their values:

import type { Extension, TypeLambda } from "@ghostry/extern";
 
interface MyLambda extends TypeLambda {
  readonly Out: MySchema<this["In"]>;
}
 
const myExtension = (): Extension<MyLambda> => ({
  kind: "producer",
  name: "my-library",
  supports: (identity) => isMySchema(identity),
  *frame() {
    yield { produce: (identity, named) => buildFrom(identity, named) };
  },
});

produce receives the identity and the block's name, when it has one. Use the name, so two differently named blocks over one identity get different values.

supports and the lambda (see Type lambdas) must agree: an identity supports accepts at runtime should be one the lambda accepts in types, and the other way around.

A producer may also set unmocked: "error", so its blocks throw NotMockedError without a mock, as other blocks do. The default, "produce", makes them produce a value.

Extension<SomeLambda> is a producer, and a bare Extension is an observer. A producer without supports, an observer with unmocked, or a producer whose frame yields no produce doesn't compile.

Frames

A frame is a generator with one yield. Everything before it is setup, the testing block runs at the yield, and everything after it is teardown:

const profiler = (): Extension => ({
  kind: "observer",
  name: "profiler",
  *frame() {
    const started = performance.now();
 
    const outcome = yield {};
 
    report(performance.now() - started, outcome.ok);
  },
});

The yield evaluates to the block's outcome: { ok: true }, or { ok: false, error }.

Setup and teardown are one function, so a finally after the yield runs on every path: the block passed, the block failed, or your own setup threw before it ran:

*frame() {
  const connection = pool.acquire();
  try {
    yield { produce: buildFrom(connection) };
  } finally {
    pool.release(connection);
  }
}

Use try/finally, not try/catch. Extern resumes the frame with the outcome instead of throwing into it, so a catch around the yield never runs. An extension sees a failure, but can't intercept or replace it.

Async frames

An async function* frame works, and makes the testing block return a promise. That's the only way for a synchronous block with asynchronous teardown to report when it's done. A synchronous generator can't await its teardown.

Running the block inside something

When the block must run inside something the extension opens, like an AsyncLocalStorage scope or a library's own wrap, yield a wrapper instead of a session. The wrapper receives body, and must call it exactly once, with the session, and return its value unchanged:

*frame() {
  yield (body) => library.wrap(options, (scoped) => body({ produce: from(scoped) }));
}

That's how a scoped value reaches produce with no variable in between. Teardown still runs inside the wrapper, so a scope it opened is live after the yield.

Returning body's value unchanged is what keeps extern.testing synchronous for a synchronous body. A wrapper that awaits makes every testing block on the instance return a promise.

Several extensions

Each extension's frame encloses the next, in the order they were passed to initialize, so all of them are open when the block runs. Teardown runs innermost first, and an outer frame waits for an inner async one.

A teardown that throws doesn't stop the others. Every failure is collected into one CleanupFailedError, with an errors list, innermost first. It's thrown when the block passed, and only logged when the block failed, so the block's own error is the one reported.

Mistakes that throw

Three mistakes would otherwise skip teardown with no error, so they throw instead:

  • ExtensionFrameResultError: frame returned something other than a generator, as a plain function does.
  • ExtensionFrameSessionError: the frame yielded neither a session nor a wrapper.
  • ExtensionFrameYieldError: the frame yielded a second time. There's one block, so there's one yield.

Type lambdas

A producer widens which identities its instance accepts with a type lambda: an interface mapping In, the produced type, to Out, the identity type. Apply sets In and reads Out back, using this["In"] inside the interface.

interface MyLambda extends TypeLambda {
  readonly Out: MySchema<this["In"]>;
}

Several extensions' lambdas form a union, which is how they combine with nothing else needed. Three rules:

  1. this["In"] must go through a named generic type. MySchema<this["In"]> resolves, but { produces?: this["In"] } doesn't.
  2. Out must be narrow. Key it on a nominal marker, like a branded symbol, that only your library's values carry. A loose shape like { build: () => this["In"] } accepts any object with a build method, and claims identities that aren't yours.
  3. Lambdas must not overlap. When two lambdas match one identity, TypeScript picks the produced type by its own inference, whatever the order of the extensions, so extern can't make its choice agree. Using such an identity throws AmbiguousIdentityError.

Offering produce(({ via }) => …)

The callback form of produce appears only when your lambda also extends HandleLambda, which maps an identity, Of, to what the callback receives, Handle:

import type { HandleLambda, TypeLambda } from "@ghostry/extern";
 
interface MyLambda extends TypeLambda, HandleLambda {
  readonly Out: MySchema<this["In"]>;
  readonly Handle: MyBuilderFor<this["Of"]>;
}

HandleLambda is a separate interface on purpose. If TypeLambda declared Handle, every lambda would inherit it as unknown, and one handle-less extension would turn via into unknown for every identity on the instance.

Only your extension can build a handle, so extern passes the caller's callback to produce as its third argument, using, for you to call:

produce: (identity, named, using) => {
  const built = buildFrom(identity, named);
  return using === undefined ? built.value() : using(built);
},

With no Handle declared, using is never passed, and produce() is still available without a callback.