feat(plugin)!: a plugin is a named object, and app.boot() is public #96

Merged
chrnx merged 6 commits from feature/plugin-contract into develop 2026-09-17 03:47:22 +00:00
21 changed files with 507 additions and 97 deletions

No files matched your search

+45 -11
View File
@@ -8,7 +8,24 @@ npm treats versions as semver and semver forbids leading zeros.
## [Unreleased]
### Changed
### Breaking
- **A plugin is a named object.** `Plugin` is now `{ name, mount(api) }`; it was `(api) => void`.
The name that `plugin:mounted` reports came from `fn.name`, which is `""` for an arrow returned
straight from a factory, `"plugin"` for a `const`, and whatever a minifier leaves behind — so the
event that exists to report which plugins mounted reported none of them by name. The name is now
the author's word, a failed `mount` is reported as `plugin "<name>" failed to mount: …` with the
original error as its `cause`, and two plugins sharing a name fail `createApp`.
Migration is mechanical:
```diff
- const jwt = (options) => ({ scope }) => { scope.add(node); };
+ const jwt = (options) => ({
+ name: options.provides ?? 'jwt',
+ mount({ scope }) { scope.add(node); },
+ });
```
- **Mesh (alpha): only steps and routes can be exported.** `@Provider({ export: true })` now fails
the boot, with an error naming the provider and the replacement. A provider is a factory whose
@@ -28,6 +45,33 @@ npm treats versions as semver and semver forbids leading zeros.
**A teapot that boots today can stop booting**, and the replacement is mechanical: the exported
`@Provider` becomes a `@Step` that returns what the provider's value carried.
- **Mesh (alpha): the manifest carries step names.** `{ scopes: [{ token, scope }], routes }` is now
`{ steps: string[], routes }`. Every export is request-scope after the change above, so the
lifetime field had one possible value left and told a reader nothing. A manifest step that is not
a string is now rejected on arrival, rather than trusted because a peer sent it.
`MESH_PROTOCOL_VERSION` deliberately stays at `1`. Mesh is alpha behind `experimental: true`, both
peers ship from this repository, and there is no deployed pair of versions for a bump to protect —
it would spend the number on nobody. A stable wire would not get that option; alpha is exactly
what the word buys, and this is the last comfortable moment to use it.
### Added
- **`app.boot()`** runs the provider factories now instead of on the first request. `listen()`
always did this; `app.fetch`, `serveDeno`, `serveBun` and `edgeHandler` boot lazily, and the boot
memo keeps a rejection — so a bad key answered 500 on *every* request, from the runtime, without
reaching `onError`. `await app.boot()` before `Deno.serve`/`Bun.serve` turns that into a startup
failure. On workerd there is no startup outside a request, so calling it moves nothing.
- **Errors are recognised by brand.** `HttpError` and `ValidationError` now carry
`Symbol.for('green-tea.http-error')` and `Symbol.for('green-tea.validation-error')`, and
`isHttpError` checks the brand instead of `instanceof`. An error thrown by code holding a
different copy of core — a plugin package, an app that installed from npm and JSR both — now
renders with its own status instead of a 500. The exported `HttpErrorLike` type and the
`isValidationError` guard come with it. The string is the public protocol: code that imports only
types writes `Symbol.for('green-tea.http-error')` itself.
### Changed
- **Mesh (alpha): an unreachable teapot no longer stops a teacup from booting.** Blocking was never
caution, it was arithmetic: an app-scope value has to resolve *at boot*, because there is no later
to resolve it in. A step is nothing but later. The `bootTimeoutMs` grace still waits, since "the
@@ -55,16 +99,6 @@ npm treats versions as semver and semver forbids leading zeros.
connected mesh" rather than "local or mesh", the old wording having claimed a search that never
happened.
- **Mesh (alpha): the manifest carries step names.** `{ scopes: [{ token, scope }], routes }` is now
`{ steps: string[], routes }`. Every export is request-scope after the change above, so the
lifetime field had one possible value left and told a reader nothing. A manifest step that is not
a string is now rejected on arrival, rather than trusted because a peer sent it.
`MESH_PROTOCOL_VERSION` deliberately stays at `1`. Mesh is alpha behind `experimental: true`, both
peers ship from this repository, and there is no deployed pair of versions for a bump to protect —
it would spend the number on nobody. A stable wire would not get that option; alpha is exactly
what the word buys, and this is the last comfortable moment to use it.
## [26.9.0-beta.1] - 2026-09-04
### Added
+2 -2
View File
@@ -58,7 +58,7 @@ npm install busboy # multipart/form-data file uploads
- **One primitive for real-time.** Declare the transport — SSE, ndjson, or a WebSocket duplex — and return an `AsyncIterable`; backpressure and cleanup are handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
- **The same app runs on Node, Deno, Bun, and the edge.** One codebase, one import; you swap the entry point (`app.listen` → `serveDeno` / `serveBun` / `edgeHandler`) and nothing else. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere.
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe), `scope.add(...)` (extend its own scope) and `onShutdown(...)` (release what it opened). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
- **Plugins can't sabotage you.** A plugin is `{ name, mount(api) }`. It gets `bus.on(...)` (observe), `scope.add(...)` (extend its own scope) and `onShutdown(...)` (release what it opened). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
## Who does the work?
@@ -288,7 +288,7 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
**What a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what lets a teacup boot without its teapot: a remote step holds nothing between requests, so a teacup whose teapot never answers still starts once the `bootTimeoutMs` grace runs out — it warns and carries on. Be precise about what that means, because it is narrower than it sounds. A teapot that never connected sent no manifest, so nothing of it reached the graph: its routes **404** rather than `503`, since nothing was registered to match, and a local step that `@needs` one of its tokens **still fails the boot**, naming the teapot that did not connect. That failure is deliberate — it is the check that catches a typo in a token name, which no amount of waiting will fix. `503` is what you get from a teapot that connected and *later* died, where the link and its exports do exist. So what the change buys is the teacup that does *not* depend on that teapot starting anyway, rather than refusing over a dependency it never had. Keeping a *needed* token serving while its teapot is legitimately away is a known gap, not an oversight: the intended answer is the `expects` list in [the mesh degrade plan](./docs/plans/2026-08-18-mesh-degrade-plan.md), which is planned and not built.
**What is settled, and what is still moving.** Present state, not a roadmap and not the API freeze — this is spare-time work by one person, and a schedule it cannot keep would cost more than it earns. The **graph is the settled part**: `needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key have not changed since the beta hardening on 7 July, and `@Provider`, `@Step`, `@Route` and handler shapes still mean what they meant then — the decorator *set* has grown (`@Head`, `@Options`, `@Html`), which only ever adds. **Still moving:** the plugin API, which gained `onShutdown` this week; `createApp`'s options, which gain fields most months; and the pipeline context, which in July became one object mutated in place rather than copied per step — so a step that captured it now sees later steps' writes. **Alpha:** mesh, above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it.
**What is settled, and what is still moving.** Present state, not a roadmap and not the API freeze — this is spare-time work by one person, and a schedule it cannot keep would cost more than it earns. The **graph is the settled part**: `needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key have not changed since the beta hardening on 7 July, and `@Provider`, `@Step`, `@Route` and handler shapes still mean what they meant then — the decorator *set* has grown (`@Head`, `@Options`, `@Html`), which only ever adds. **Still moving:** the plugin API, which became `{ name, mount }` and gained `onShutdown`; `createApp`'s options, which gain fields most months; and the pipeline context, which in July became one object mutated in place rather than copied per step — so a step that captured it now sees later steps' writes. **Alpha:** mesh, above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it.
## Docs & development
+5 -2
View File
@@ -31,8 +31,11 @@ class UserController {
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
class ApiModule {}
const logger: Plugin = (api) => {
api.bus.on('request:step:enter', (p) => console.log(`-> ${p.name}`));
const logger: Plugin = {
name: 'step-logger',
mount(api) {
api.bus.on('request:step:enter', (p) => console.log(`-> ${p.name}`));
},
};
export const app = createApp({ modules: [ApiModule], plugins: [logger] });
+13 -1
View File
@@ -392,6 +392,7 @@ export function createApp(opts: {
close,
handleSignals,
ready,
boot: bootApp,
fetch: fetchFn,
upgrade: upgradeFn,
inspect,
@@ -600,8 +601,19 @@ function buildTeardownRegistry(
function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registry, teardown: TeardownRegistry): void {
const extraSteps: ScopeNode[] = [];
const scope: ScopeApi = { add: (node) => extraSteps.push(node) };
// The name is the plugin's identity in `plugin:mounted` and in a mount failure, so two of them
// make both ambiguous. Two instances of one plugin are legitimate — they differ by `provides`,
// and the convention derives the name from it (.specs/2026-09-15, rule 2).
const seen = new Set<string>();
for (const plugin of plugins ?? []) mountPlugin(plugin, bus, scope, (fn) => teardown.add(fn));
for (const plugin of plugins ?? []) {
if (seen.has(plugin.name)) {
throw new Error(`two plugins are named "${plugin.name}" — pass a different \`provides\` to one of them`);
}
seen.add(plugin.name);
mountPlugin(plugin, bus, scope, (fn) => teardown.add(fn));
}
for (const scopeNode of extraSteps) {
const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' };
+15
View File
@@ -59,6 +59,21 @@ export interface App {
* shares this same memoized step — calling both never resolves the graph twice.
*/
ready(): Promise<void>;
/**
* Boots the providers now, instead of on the first request.
*
* `listen()` already does this before it accepts a connection. Every other path — `app.fetch`,
* `app.upgrade`, `serveDeno`, `serveBun`, `edgeHandler` — boots lazily on the first request, and a
* provider that throws there fails *every* request, answered by the runtime with a 500 that never
* reaches `onError`. Calling this first turns that into a startup failure, which is where a bad
* key or an unreachable database belongs.
*
* Idempotent, and shares its memo with `listen()` and `fetch()`: calling both boots once. Unlike
* `ready()`, it does run provider factories.
*
* On workerd there is no startup outside a request, so calling it moves nothing.
*/
boot(): Promise<void>;
/** Web-Standards handler: run a Fetch API Request through the graph and return a Response (Node/Deno/Bun/edge). WS not included. */
fetch(request: Request): Promise<Response>;
/** Run a WebSocket upgrade through the graph using an adapter-provided socket (Deno/Bun/edge). Node uses its own listener path. */
+5
View File
@@ -56,7 +56,12 @@ export {
NotModified,
ValidationError,
TransportMismatchError,
HTTP_ERROR,
VALIDATION_ERROR,
isHttpError,
isValidationError,
} from './signals';
export type { HttpErrorLike } from './signals';
// Bus & flow
export { Bus } from './bus';
+22 -4
View File
@@ -37,8 +37,18 @@ export interface PluginApi {
*/
onShutdown(fn: TeardownFn): void;
}
/** A plugin: a function that wires itself up through the provided PluginApi. */
export type Plugin = (api: PluginApi) => void;
/**
* A plugin: a named object that wires itself up through the provided PluginApi.
*
* The name is a field rather than `fn.name` because `fn.name` cannot be relied on: an arrow
* returned straight from a factory has `""`, `const plugin = …` reports `"plugin"`, and a minifier
* rewrites both. The name is what `plugin:mounted` reports and what a failed mount is blamed on, so
* it has to be the author's word, not the bundler's.
*/
export interface Plugin {
readonly name: string;
mount(api: PluginApi): void;
}
/** Runs a plugin against a restricted API, then emits `plugin:mounted`. */
export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi, onShutdown: (fn: TeardownFn) => void): void {
@@ -53,6 +63,14 @@ export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi, onShutdow
// before could delay the process. It cannot delay it without bound — `close()`'s deadline still
// caps the whole shutdown.
const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope, onShutdown };
plugin(api);
bus.emit('plugin:mounted', { name: plugin.name || 'anonymous' });
try {
plugin.mount(api);
} catch (error) {
// Without the name this surfaces as somebody else's stack trace: mounting happens inside
// createApp, so the application sees a throw from a line it never wrote.
throw new Error(`plugin "${plugin.name}" failed to mount: ${(error as Error).message}`, { cause: error });
}
bus.emit('plugin:mounted', { name: plugin.name });
}
+35 -3
View File
@@ -1,11 +1,36 @@
import type { StandardIssue } from './standard-schema';
/**
* Brands, so an error is recognised across two copies of core — an app that installed one from npm
* and a plugin that brought another from JSR, or two npm versions npm could not dedupe.
* `instanceof` cannot do that: each copy has its own class identity.
*
* `Symbol.for` is registry-wide, so both copies resolve the same symbol. The *string* is the public
* protocol (`.specs/2026-09-15-plugin-ecosystem-design.md`, 1.2): a plugin that imports only types
* cannot import this constant, so it writes `Symbol.for('green-tea.http-error')` itself.
*
* `unique symbol` is required by TypeScript for a computed class field, and `Symbol.for` on a `const`
* satisfies it.
*/
export const HTTP_ERROR: unique symbol = Symbol.for('green-tea.http-error');
export const VALIDATION_ERROR: unique symbol = Symbol.for('green-tea.validation-error');
/** The shape core reads off a branded error. Anything carrying the brand should satisfy it. */
export interface HttpErrorLike {
status: number;
message: string;
body?: unknown;
headers?: Record<string, string>;
}
/**
* Error carrying an HTTP status code and optional response body. Base of all signals.
* A subclass needing response headers (e.g. `location`, `retry-after`) sets `headers`
* rather than requiring a special case in the error renderer.
*/
export class HttpError extends Error {
readonly [HTTP_ERROR] = true;
constructor(
readonly status: number,
message?: string,
@@ -47,6 +72,8 @@ export class Redirect extends HttpError {
/** 422 raised when request input fails Standard Schema validation. */
export class ValidationError extends HttpError {
readonly [VALIDATION_ERROR] = true;
constructor(
public issues: StandardIssue[],
public source: string,
@@ -68,7 +95,12 @@ export class TransportMismatchError extends HttpError {
}
}
/** Type guard: true if `error` is an {@link HttpError}. */
export function isHttpError(error: unknown): error is HttpError {
return error instanceof HttpError;
/** Type guard: true if `error` carries the HTTP-error brand — this copy's or another's. */
export function isHttpError(error: unknown): error is HttpErrorLike {
return typeof error === 'object' && error !== null && HTTP_ERROR in error;
}
/** Type guard: true if `error` carries the validation brand. */
export function isValidationError(error: unknown): error is ValidationError {
return typeof error === 'object' && error !== null && VALIDATION_ERROR in error;
}
+2 -2
View File
@@ -1,4 +1,4 @@
import { isHttpError, ValidationError } from './signals';
import { isHttpError, isValidationError } from './signals';
import type { TransformerFn } from './metadata';
import { flattenPath } from './standard-schema';
import type { Logger } from './logger';
@@ -35,7 +35,7 @@ export const JsonTransformer: TransformerFn = (value) => ({
* An `HttpError` carrying a `body` renders that payload instead of the default `{ error: message }`.
*/
export function errorToResponse(error: unknown): ErrorResponse {
if (error instanceof ValidationError) {
if (isValidationError(error)) {
return {
status: 422,
headers: { 'content-type': 'application/json' },
+59
View File
@@ -0,0 +1,59 @@
// test/app-boot.test.ts
import { describe, expect, it, vi } from 'vitest';
import { createApp, Get, Module, Route, needs } from '../src/index';
import type { Plugin } from '../src/index';
@Route('/')
class Ctl {
@Get('/x')
x(@needs('thing') thing: string) {
return { thing };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const plugin = (run: () => Promise<Record<string, unknown>>): Plugin => ({
name: 'thing',
mount({ scope }) {
scope.add({ kind: 'provider', name: 'thing', needs: [], provides: ['thing'], run });
},
});
describe('app.boot()', () => {
it('surfaces a failing provider instead of leaving it for the first request', async () => {
const app = createApp({ modules: [M], plugins: [plugin(async () => { throw new Error('bad key'); })] });
await expect(app.boot()).rejects.toThrow(/bad key/);
});
it('runs provider factories exactly once, and serves afterwards', async () => {
const run = vi.fn(async () => ({ thing: 'ok' }));
const app = createApp({ modules: [M], plugins: [plugin(run)] });
await app.boot();
await app.boot();
const response = await app.fetch(new Request('http://x/x'));
expect(run).toHaveBeenCalledTimes(1);
expect(await response.json()).toEqual({ thing: 'ok' });
});
// The memo keeps the rejection, which is exactly why a failed boot answers 500 for the life of
// the process instead of retrying. It is the documented behaviour, so it gets a test rather than
// a sentence: if it ever starts retrying, the guide in Task 7 becomes wrong.
it('keeps a failed boot failed', async () => {
const run = vi.fn(async () => {
throw new Error('bad key');
});
const app = createApp({ modules: [M], plugins: [plugin(run)] });
await expect(app.boot()).rejects.toThrow(/bad key/);
await expect(app.boot()).rejects.toThrow(/bad key/);
await expect(app.fetch(new Request('http://x/x'))).rejects.toThrow(/bad key/);
expect(run).toHaveBeenCalledTimes(1);
});
});
+6 -3
View File
@@ -66,9 +66,12 @@ describe('app.upgrade', () => {
it('emits request:step:enter/leave for ws steps, like HTTP routes do', async () => {
const seen: string[] = [];
const logger = (api: any) => {
api.bus.on('request:step:enter', (p: any) => seen.push(`enter:${p.name}`));
api.bus.on('request:step:leave', (p: any) => seen.push(`leave:${p.name}`));
const logger = {
name: 'ws-step-logger',
mount: (api: any) => {
api.bus.on('request:step:enter', (p: any) => seen.push(`enter:${p.name}`));
api.bus.on('request:step:leave', (p: any) => seen.push(`leave:${p.name}`));
},
};
const wsApp = createApp({ modules: [Tagged], plugins: [logger] });
const { socket, inbound, sent } = fakeSocket();
+32 -23
View File
@@ -56,7 +56,10 @@ test('ready() is a no-op on a non-mesh app, so one protocol works for both', asy
test('a logger plugin observes step:enter without mutating the chain', async () => {
const seen: string[] = [];
const logger = (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name));
const logger = {
name: 'step-logger',
mount: (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name)),
};
const app = createApp({ modules: [ApiModule], plugins: [logger] });
const server = await app.listen(0);
const port = (server.address() as any).port;
@@ -256,17 +259,20 @@ describe('per-route subgraph slicing', () => {
it('a side-effect step (provides: []) added by a plugin runs unconditionally', async () => {
// NB: @Step always provides exactly one token (always sliceable). provides:[] only arises via a plugin's scope.add.
const ran: string[] = [];
const observer = (api: any) =>
api.scope.add({
kind: 'step',
name: 'obs',
needs: [],
provides: [],
run: () => {
ran.push('obs');
return {};
},
});
const observer = {
name: 'side-effect-observer',
mount: (api: any) =>
api.scope.add({
kind: 'step',
name: 'obs',
needs: [],
provides: [],
run: () => {
ran.push('obs');
return {};
},
}),
};
@Route('/')
class Ctl {
@Get('/free') free() {
@@ -285,17 +291,20 @@ describe('per-route subgraph slicing', () => {
it('an always-run observer step receives its declared needs even when the route does not need them', async () => {
let seen: any;
const observer = (api: any) =>
api.scope.add({
kind: 'step',
name: 'audit',
needs: ['user'],
provides: [],
run: (ctx: any) => {
seen = ctx.user;
return {};
},
});
const observer = {
name: 'audit-observer',
mount: (api: any) =>
api.scope.add({
kind: 'step',
name: 'audit',
needs: ['user'],
provides: [],
run: (ctx: any) => {
seen = ctx.user;
return {};
},
}),
};
@Step({ provides: 'user', needs: [] })
class Auth {
run() {
+7 -4
View File
@@ -57,10 +57,13 @@ test('serveBun close() runs registered teardown', async () => {
const app = createApp({
modules: [M],
hooks: [{ onShutdown: () => void closed.push('hook') }],
plugins: [(api) => api.onShutdown(async () => {
await Bun.sleep(10);
closed.push('plugin');
})],
plugins: [{
name: 'teardown-probe',
mount: (api) => api.onShutdown(async () => {
await Bun.sleep(10);
closed.push('plugin');
}),
}],
});
const server = serveBun(app, { port: 0 });
+5 -2
View File
@@ -22,8 +22,11 @@ describe('reaching the bus', () => {
const fromOutside: string[] = [];
const fromPlugin: string[] = [];
const observer: Plugin = (api) => {
api.bus.on('request:end', (e) => fromPlugin.push(e.route ?? ''));
const observer: Plugin = {
name: 'bus-observer',
mount(api) {
api.bus.on('request:end', (e) => fromPlugin.push(e.route ?? ''));
},
};
@Module({ mountpoint: '/', controllers: [Ctl] })
+7 -4
View File
@@ -72,10 +72,13 @@ Deno.test('serveDeno close() runs registered teardown', async () => {
const app = createApp({
modules: [M],
hooks: [{ onShutdown: () => void closed.push('hook') }],
plugins: [(api) => api.onShutdown(async () => {
await new Promise((r) => setTimeout(r, 10));
closed.push('plugin');
})],
plugins: [{
name: 'teardown-probe',
mount: (api) => api.onShutdown(async () => {
await new Promise((r) => setTimeout(r, 10));
closed.push('plugin');
}),
}],
});
const server = serveDeno(app, { port: 0 });
+117
View File
@@ -0,0 +1,117 @@
// test/plugin-contract.test.ts
import { describe, expect, it, vi } from 'vitest';
import { createApp, Get, Module, Route, needs } from '../src/index';
import type { Plugin } from '../src/index';
@Route('/')
class Ctl {
@Get('/who')
who(@needs('who') who: string) {
return { who };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const provides = (name: string, value: string): Plugin => ({
name,
mount({ scope }) {
scope.add({ kind: 'provider', name, needs: [], provides: [name], run: async () => ({ [name]: value }) });
},
});
describe('the plugin contract', () => {
it('mounts an object plugin and its node reaches a handler', async () => {
const app = createApp({ modules: [M], plugins: [provides('who', 'jwt')] });
const response = await app.fetch(new Request('http://x/who'));
expect(await response.json()).toEqual({ who: 'jwt' });
});
it('names the plugin whose mount threw', () => {
const boom: Plugin = {
name: 'boom',
mount() {
throw new Error('no key');
},
};
expect(() => createApp({ modules: [M], plugins: [boom] })).toThrow(
/plugin "boom" failed to mount: no key/,
);
});
it('keeps the original error as the cause', () => {
const original = new Error('no key');
const boom: Plugin = {
name: 'boom',
mount() {
throw original;
},
};
try {
createApp({ modules: [M], plugins: [boom] });
expect.unreachable('createApp should have thrown');
} catch (error) {
expect((error as Error).cause).toBe(original);
}
});
// The two plugins provide *different* tokens, so nothing but the duplicate-name check can fail
// this. Two plugins providing the same token would also collide inside `setRunner`, which
// enforces unique node names already — and the test would pass without the new code.
it('refuses two plugins with the same name, even when they provide different tokens', () => {
const twin = (token: string): Plugin => ({
name: 'twin',
mount({ scope }) {
scope.add({ kind: 'provider', name: token, needs: [], provides: [token], run: async () => ({ [token]: 1 }) });
},
});
expect(() => createApp({ modules: [M], plugins: [twin('a'), twin('b')] })).toThrow(
/two plugins are named "twin"/,
);
});
// `plugin:mounted` means "this plugin is in". A plugin whose mount threw is not, and announcing
// it would put a name in the lifecycle stream for something that never registered anything.
it('does not announce a plugin whose mount threw', () => {
const seen = vi.fn();
const observer: Plugin = {
name: 'observer',
mount({ bus }) {
bus.on('plugin:mounted', seen);
},
};
const boom: Plugin = {
name: 'boom',
mount() {
throw new Error('no key');
},
};
expect(() => createApp({ modules: [M], plugins: [observer, boom] })).toThrow(/failed to mount/);
expect(seen).not.toHaveBeenCalledWith(expect.objectContaining({ name: 'boom' }));
});
it('reports the name on plugin:mounted', () => {
const seen = vi.fn();
// `createApp` takes no `bus` option, and the event
// fires during construction — so the observer has to be a plugin, listed first, because
// plugins mount in the order they are given.
const observer: Plugin = {
name: 'observer',
mount({ bus }) {
bus.on('plugin:mounted', seen);
},
};
createApp({ modules: [M], plugins: [observer, provides('who', 'jwt')] });
expect(seen).toHaveBeenCalledWith(expect.objectContaining({ name: 'who' }));
});
});
+28 -15
View File
@@ -10,9 +10,12 @@ test('plugin can observe via bus.on and add to its own scope', () => {
const added: string[] = [];
const scope: ScopeApi = { add: (n) => added.push(n.name) };
const logger: Plugin = (api) => {
api.bus.on('request:step:enter', () => {});
api.scope.add({ kind: 'step', name: 'log', needs: [], provides: [], run: () => ({}) });
const logger: Plugin = {
name: 'logger',
mount(api) {
api.bus.on('request:step:enter', () => {});
api.scope.add({ kind: 'step', name: 'log', needs: [], provides: [], run: () => ({}) });
},
};
const mounted = vi.fn();
@@ -26,8 +29,11 @@ test('plugin can observe via bus.on and add to its own scope', () => {
test('plugin api does NOT expose bus.emit', () => {
const bus = new Bus();
const scope: ScopeApi = { add: () => {} };
const plugin: Plugin = (api) => {
expect((api.bus as any).emit).toBeUndefined();
const plugin: Plugin = {
name: 'emit-probe',
mount(api) {
expect((api.bus as any).emit).toBeUndefined();
},
};
mountPlugin(plugin, bus, scope, noTeardown());
});
@@ -35,8 +41,11 @@ test('plugin api does NOT expose bus.emit', () => {
test('plugin can register a teardown, and it reaches the registry', () => {
const bus = new Bus();
const registered: TeardownFn[] = [];
const plugin: Plugin = (api) => {
api.onShutdown(() => {});
const plugin: Plugin = {
name: 'teardown-registrar',
mount(api) {
api.onShutdown(() => {});
},
};
mountPlugin(plugin, bus, { add: () => {} }, (fn) => registered.push(fn));
@@ -44,22 +53,26 @@ test('plugin can register a teardown, and it reaches the registry', () => {
expect(registered).toHaveLength(1);
});
// D3's no-break guarantee, asserted rather than assumed: `Plugin`'s signature did not change, so a
// plugin written before this capability existed must mount and behave exactly as it did.
test('a plugin that never calls onShutdown behaves exactly as before', () => {
// A plugin that opens nothing registers nothing: `onShutdown` is opt-in, and the teardown registry
// stays empty rather than collecting no-ops. (The shape guarantee this test used to assert went
// away with the move to `{ name, mount }` — see CHANGELOG, Breaking.)
test('a plugin that never calls onShutdown registers no teardown', () => {
const bus = new Bus();
const added: string[] = [];
const registered: TeardownFn[] = [];
const legacy: Plugin = (api) => {
api.bus.on('stream:open', () => {});
api.scope.add({ kind: 'provider', name: 'thing', needs: [], provides: ['thing'], run: () => ({}) });
const quiet: Plugin = {
name: 'quiet',
mount(api) {
api.bus.on('stream:open', () => {});
api.scope.add({ kind: 'provider', name: 'thing', needs: [], provides: ['thing'], run: () => ({}) });
},
};
const mounted = vi.fn();
bus.on('plugin:mounted', mounted);
mountPlugin(legacy, bus, { add: (n) => added.push(n.name) }, (fn) => registered.push(fn));
mountPlugin(quiet, bus, { add: (n) => added.push(n.name) }, (fn) => registered.push(fn));
expect(added).toEqual(['thing']);
expect(mounted).toHaveBeenCalled();
expect(mounted).toHaveBeenCalledWith(expect.objectContaining({ name: 'quiet' }));
expect(registered).toHaveLength(0);
});
+65
View File
@@ -0,0 +1,65 @@
// test/signals-brand.test.ts
import { describe, expect, it } from 'vitest';
import { errorToResponse } from '../src/transformers';
import { HttpError, ValidationError, isHttpError, isValidationError } from '../src/signals';
// What a plugin published from another package throws: it never imported core, so it is not an
// `instanceof` anything of ours. The brand is the whole contract — see .specs/2026-09-15, 1.2.
const HTTP_ERROR = Symbol.for('green-tea.http-error');
class ForeignTooManyRequests extends Error {
readonly [HTTP_ERROR] = true;
readonly status = 429;
constructor(
message: string,
readonly headers: Record<string, string>,
) {
super(message);
}
}
describe('the error brand', () => {
it('renders a foreign branded error with its own status and headers', () => {
const response = errorToResponse(new ForeignTooManyRequests('slow down', { 'retry-after': '30' }));
expect(response.status).toBe(429);
expect(response.headers['retry-after']).toBe('30');
expect(JSON.parse(response.body)).toEqual({ error: 'slow down' });
});
it('recognises a foreign branded error through the guard', () => {
expect(isHttpError(new ForeignTooManyRequests('slow down', {}))).toBe(true);
});
it("still recognises core's own errors", () => {
expect(isHttpError(new HttpError(418, 'teapot'))).toBe(true);
expect(isValidationError(new ValidationError([], 'body'))).toBe(true);
expect(isValidationError(new HttpError(418, 'teapot'))).toBe(false);
});
it('does not claim an unbranded error', () => {
expect(isHttpError(new Error('plain'))).toBe(false);
expect(isHttpError(null)).toBe(false);
expect(isHttpError({ status: 429 })).toBe(false);
});
it('renders a foreign validation error as 422 with its issues', () => {
const foreign = Object.assign(new Error('Validation failed'), {
[Symbol.for('green-tea.http-error')]: true,
[Symbol.for('green-tea.validation-error')]: true,
status: 422,
source: 'body',
issues: [{ path: ['email'], message: 'required' }],
});
const response = errorToResponse(foreign);
expect(response.status).toBe(422);
expect(JSON.parse(response.body)).toEqual({
error: 'Validation failed',
source: 'body',
issues: [{ path: 'email', message: 'required' }],
});
});
});
+26 -14
View File
@@ -17,11 +17,14 @@ class Ctl {
describe('shutdown teardown', () => {
it('awaits a plugin onShutdown before close() resolves', async () => {
const order: string[] = [];
const plugin: Plugin = (api) => {
api.onShutdown(async () => {
await new Promise((r) => setTimeout(r, 20));
order.push('plugin torn down');
});
const plugin: Plugin = {
name: 'slow-teardown',
mount(api) {
api.onShutdown(async () => {
await new Promise((r) => setTimeout(r, 20));
order.push('plugin torn down');
});
},
};
@Module({ mountpoint: '/', controllers: [Ctl] })
@@ -135,11 +138,14 @@ describe('shutdown teardown', () => {
it('logs a failing teardown, runs the rest, and still resolves', async () => {
const logger = silentLogger();
const closed: string[] = [];
const plugin: Plugin = (api) => {
api.onShutdown(() => {
throw new Error('teardown boom');
});
api.onShutdown(() => void closed.push('survivor'));
const plugin: Plugin = {
name: 'failing-teardown',
mount(api) {
api.onShutdown(() => {
throw new Error('teardown boom');
});
api.onShutdown(() => void closed.push('survivor'));
},
};
@Module({ mountpoint: '/', controllers: [Ctl] })
@@ -153,8 +159,11 @@ describe('shutdown teardown', () => {
});
it('does not let a hanging teardown push close() past its deadline', async () => {
const plugin: Plugin = (api) => {
api.onShutdown(() => new Promise<void>(() => {})); // never settles
const plugin: Plugin = {
name: 'hanging-teardown',
mount(api) {
api.onShutdown(() => new Promise<void>(() => {})); // never settles
},
};
@Module({ mountpoint: '/', controllers: [Ctl] })
@@ -199,8 +208,11 @@ describe('shutdown teardown', () => {
it('drains only once when close() is called twice', async () => {
let runs = 0;
const plugin: Plugin = (api) => {
api.onShutdown(() => void runs++);
const plugin: Plugin = {
name: 'counting-teardown',
mount(api) {
api.onShutdown(() => void runs++);
},
};
@Module({ mountpoint: '/', controllers: [Ctl] })
+10 -6
View File
@@ -26,8 +26,8 @@ const prometheusText: TransformerFn = (value) => ({
body: String(value),
});
// A plugin split into named functions rather than one inline arrow: `Plugin` alone types the
// arrow, and nothing typed its argument.
// A plugin split into named functions rather than one inline `mount`: `Plugin` types the object,
// and `PluginApi`/`ScopeApi`/`ScopeNode` type what the pieces receive.
function subscribe(api: PluginApi): void {
api.bus.on('request:end', () => {});
api.onShutdown(flush);
@@ -40,9 +40,12 @@ function contribute(scope: ScopeApi): void {
scope.add(node);
}
const metricsPlugin: Plugin = (api) => {
subscribe(api);
contribute(api.scope);
const metricsPlugin: Plugin = {
name: 'metrics',
mount(api) {
subscribe(api);
contribute(api.scope);
},
};
// createApp({ hooks }) — declared as a value, which is the point of the option.
@@ -59,7 +62,8 @@ const encoder: StreamEncoder = {
test('every extension point is typeable from the package barrel', () => {
expect(prometheusText('x').body).toBe('x');
expect(typeof metricsPlugin).toBe('function');
expect(typeof metricsPlugin.mount).toBe('function');
expect(metricsPlugin.name).toBe('metrics');
expect(hooks).toHaveLength(1);
expect(renderError(new Error('boom'), {} as never)?.status).toBe(500);
expect(encoder.encode(1)).toBe('1');
+1 -1
View File
@@ -3,7 +3,7 @@
"target": "es2017",
"module": "commonjs",
"moduleResolution": "node",
"lib": ["es2020"],
"lib": ["es2020", "es2022.error"],
"declaration": true,
"outDir": "dist",
"rootDir": ".",