feat(signals): recognise HTTP errors by brand, not by instanceof

A plugin published as its own package cannot import HttpError without depending on
core's version, and under CalVer no dependency range survives next month's beta. A
Symbol.for brand crosses copies, so a plugin throws a 429 core renders, while
importing nothing but types.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-09-16 22:25:50 -05:00
1 parent 73a4a9f6cd
commit e83d62cc1a
4 files changed
+107 -5

No files matched your search

+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';
+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' },
+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' }],
});
});
});