Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

10.5 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file  api-baseline.test.ts — the rule that decides a broken API promise.
 *
 * It only fires the release AFTER a symbol is frozen, so without these it would
 * first be exercised on the day it had to be right.
 */
import { describe, it, expect } from 'vitest';
// @ts-expect-error — a repo tool, shipped as .mjs with no declarations
import { parseSnapshot, baselineFindings, isAdditiveMembers, UNCLAIMED } from '../lib/apiSnapshot.mjs';

type Entry = { kind: string; tier: string; deprecated: boolean; body: string };

function snapshot(...sections: string[]): Map<string, Entry> {
    return parseSnapshot(`# API surface — esengine/test\n\n${sections.join('\n\n')}\n`);
}

const sig = (heading: string, body: string) => `## ${heading}\n\`\`\`\n${body}\n\`\`\``;

describe('parseSnapshot', () => {
    it('reads the tier and the deprecation as separate axes', () => {
        const s = snapshot(
            sig('defineComponent — function @public', '(name: string): ComponentDef'),
            sig('oldThing — function @public @deprecated', '(): void'),
            sig('graph — const @beta', 'MaterialGraph'),
        );
        expect(s.get('defineComponent')).toMatchObject({ tier: 'public', deprecated: false });
        expect(s.get('oldThing')).toMatchObject({ tier: 'public', deprecated: true });
        expect(s.get('graph')).toMatchObject({ tier: 'beta', deprecated: false });
    });

    it('reads a snapshot written before the tiers existed as claiming nothing', () => {
        const s = snapshot(sig('Query — class', 'call ()'));
        expect(s.get('Query')?.tier).toBe(UNCLAIMED);
    });
});

describe('baselineFindings', () => {
    const frozen = snapshot(sig('Commands — class @public', 'spawn(): Entity'));

    it('passes when the frozen signature is untouched', () => {
        const now = snapshot(sig('Commands — class @public', 'spawn(): Entity'));
        expect(baselineFindings(frozen, now).failures).toEqual([]);
    });

    it('fails a removal that never went through @deprecated', () => {
        const now = snapshot(sig('Other — class @public', 'x(): void'));
        expect(baselineFindings(frozen, now).failures).toEqual([
            expect.stringContaining('Commands — removed while @public and never @deprecated'),
        ]);
    });

    it('allows a removal that was deprecated in the release before it', () => {
        const was = snapshot(sig('Commands — class @public @deprecated', 'spawn(): Entity'));
        expect(baselineFindings(was, snapshot()).failures).toEqual([]);
    });

    it('fails a changed signature', () => {
        const now = snapshot(sig('Commands — class @public', 'spawn(name: string): Entity'));
        expect(baselineFindings(frozen, now).failures).toEqual([
            expect.stringContaining('@public signature changed'),
        ]);
    });

    it('fails a kind change', () => {
        const now = snapshot(sig('Commands — interface @public', 'spawn(): Entity'));
        expect(baselineFindings(frozen, now).failures).toEqual([
            expect.stringContaining('class became a interface'),
        ]);
    });

    it('fails a thaw back to a weaker tier', () => {
        const now = snapshot(sig('Commands — class @public', 'spawn(): Entity')
            .replace('@public', '@beta'));
        expect(baselineFindings(frozen, now).failures).toEqual([
            expect.stringContaining('a freeze does not thaw'),
        ]);
    });

    it('notes but does not fail a @beta change', () => {
        const was = snapshot(sig('graph — const @beta', 'MaterialGraph'));
        const { failures, notes } = baselineFindings(was, snapshot());
        expect(failures).toEqual([]);
        expect(notes).toEqual([expect.stringContaining('@beta removed')]);
    });

    it('claims nothing about a symbol no release tiered', () => {
        const was = snapshot(sig('legacy — function', '(): void'));
        const { failures, notes } = baselineFindings(was, snapshot());
        expect(failures).toEqual([]);
        expect(notes).toEqual([]);
    });

    it('lets an @internal member change, because none was promised', () => {
        const was = snapshot(sig('Handle — class @public', 'get(): number\n@internal _raw: string'));
        const now = snapshot(sig('Handle — class @public', 'get(): number\n@internal _raw: number'));
        expect(baselineFindings(was, now).failures).toEqual([]);
    });

    it('still fails when a promised member beside an @internal one changes', () => {
        const was = snapshot(sig('Handle — class @public', 'get(): number\n@internal _raw: string'));
        const now = snapshot(sig('Handle — class @public', 'get(): string\n@internal _raw: string'));
        expect(baselineFindings(was, now).failures).toEqual([
            expect.stringContaining('@public signature changed'),
        ]);
    });
});

describe('an interface that gains an optional member', () => {
    const was = snapshot(sig('Options — interface @public', 'name: string | undefined'));

    it('is not a broken promise: nothing that compiled stops compiling', () => {
        const now = snapshot(sig('Options — interface @public',
            'name: string | undefined\ntouches: Touches | undefined'));
        const { failures, notes } = baselineFindings(was, now);
        expect(failures).toEqual([]);
        expect(notes.join()).toMatch(/optional member/);
    });

    it('still fails when the added member is required', () => {
        const now = snapshot(sig('Options — interface @public',
            'name: string | undefined\ntouches: Touches'));
        expect(baselineFindings(was, now).failures).toHaveLength(1);
    });

    it('still fails when an existing member changed', () => {
        const now = snapshot(sig('Options — interface @public',
            'name: number | undefined\ntouches: Touches | undefined'));
        expect(baselineFindings(was, now).failures).toHaveLength(1);
    });

    it('still fails when a member was dropped', () => {
        const now = snapshot(sig('Options — interface @public', 'touches: Touches | undefined'));
        expect(baselineFindings(was, now).failures).toHaveLength(1);
    });

    it('is not additive when nothing was added', () => {
        expect(isAdditiveMembers('a: string | undefined', 'a: string | undefined')).toBe(false);
    });
});

/**
 * Nobody implements a class from outside, so a class that GAINS a member breaks
 * no caller — unlike an interface, where a required member is a demand on every
 * implementor. Losing or changing one is still a broken promise.
 */
describe('a @public class that gained a member', () => {
    const body = (...members: string[]) => members.join('\n');
    const was = sig('World — class @public', body(
        'get: (e: Entity, c: Def) => Data',
        'set: (e: Entity, c: Def, d: Data) => void',
    ));
    const changed = (b: string) =>
        baselineFindings(snapshot(was), snapshot(sig('World — class @public', b)));

    it('is a note, not a broken promise', () => {
        const { failures, notes } = changed(body(
            'get: (e: Entity, c: Def) => Data',
            'set: (e: Entity, c: Def, d: Data) => void',
            'update: (e: Entity, c: Def, edit: (d: Data) => void) => void',
        ));
        expect(failures).toEqual([]);
        expect(notes.join(' ')).toMatch(/class gained a member/);
    });

    it('is still broken when a member is REMOVED', () => {
        expect(changed(body('get: (e: Entity, c: Def) => Data')).failures)
            .toEqual(['World — @public signature changed']);
    });

    it('is still broken when a member CHANGED while another was added', () => {
        expect(changed(body(
            'get: (e: Entity, c: Def, extra: number) => Data',
            'set: (e: Entity, c: Def, d: Data) => void',
            'update: (e: Entity, c: Def, edit: (d: Data) => void) => void',
        )).failures).toEqual(['World — @public signature changed']);
    });

    it('does not fire for an interface, where a required member is a demand', () => {
        const iface = sig('Shape — interface @public', body('a: number'));
        const { failures } = baselineFindings(
            snapshot(iface),
            snapshot(sig('Shape — interface @public', body('a: number', 'b: string'))),
        );
        expect(failures).toEqual(['Shape — @public signature changed']);
    });
});

/**
 * A trailing OPTIONAL parameter breaks no call that was written, which is the
 * whole of what @public promises. Every other edit to a signature does break
 * one, so the rule has to be a prefix rule and not "the strings differ".
 */
describe('a @public function that gained an optional parameter', () => {
    const was = sig('defineEvent — function @public', '<T>(name: string): EventDef<T>');
    const changed = (body: string) =>
        baselineFindings(snapshot(was), snapshot(sig('defineEvent — function @public', body)));

    it('is a note, not a broken promise', () => {
        const { failures, notes } = changed('<T>(name: string, payload?: T & object): EventDef<T>');
        expect(failures).toEqual([]);
        expect(notes.join(' ')).toMatch(/gained an optional parameter/);
    });

    it('is still broken when the new parameter is REQUIRED', () => {
        expect(changed('<T>(name: string, payload: T & object): EventDef<T>').failures)
            .toEqual(['defineEvent — @public signature changed']);
    });

    it('is still broken when an existing parameter changed', () => {
        expect(changed('<T>(name: number, payload?: T): EventDef<T>').failures)
            .toEqual(['defineEvent — @public signature changed']);
    });

    it('is still broken when the return type changed', () => {
        expect(changed('<T>(name: string, payload?: T): EventDef<unknown>').failures)
            .toEqual(['defineEvent — @public signature changed']);
    });

    it('is still broken when a parameter was inserted rather than appended', () => {
        expect(changed('<T>(payload?: T, name: string): EventDef<T>').failures)
            .toEqual(['defineEvent — @public signature changed']);
    });

    /** A type parameter list is not a parameter list; a comma inside one must
     *  not split a parameter either. */
    it('reads a parameter whose own type carries a comma', () => {
        const wide = sig('f — function @public', '(a: Map<string, number>): void');
        const wider = sig('f — function @public', '(a: Map<string, number>, b?: number): void');
        expect(baselineFindings(snapshot(wide), snapshot(wider)).failures).toEqual([]);
    });
});