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.

9.4 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file  apiSnapshot.mjs — reading sdk/etc/*.api.md, and what a release promised.
 *
 * Pure text in, findings out: no compiler and no filesystem, so the rule that
 * decides whether a promise was broken can be tested directly instead of only
 * being observable the release after it was needed.
 */

/** Stability tiers, most-frozen first. A symbol carries exactly one. */
export const TIERS = ['public', 'beta', 'experimental', 'internal'];

/** What a snapshot heading says when no release named a tier for the symbol. */
export const UNCLAIMED = 'unclaimed';

/**
 * Parse a `<entry>.api.md` into `name -> { kind, tier, deprecated, body }`.
 * Snapshots written before the tiers existed carry no tag; those read as
 * {@link UNCLAIMED}, which is the truth about them — nothing was promised.
 */
export function parseSnapshot(text) {
    const out = new Map();
    for (const section of text.replace(/\r\n?/g, '\n').split(/^## /m).slice(1)) {
        const nl = section.indexOf('\n');
        const heading = nl < 0 ? section : section.slice(0, nl);
        const m = /^(\S+) — (\S+)(.*)$/.exec(heading);
        if (!m) continue;
        const [, name, kind, tags] = m;
        out.set(name, {
            kind,
            tier: new RegExp(`@(${TIERS.join('|')})\\b`).exec(tags)?.[1] ?? UNCLAIMED,
            deprecated: /@deprecated\b/.test(tags),
            body: (nl < 0 ? '' : section.slice(nl + 1)).trim(),
        });
    }
    return out;
}

/**
 * The part of a body that carries a promise. An `@internal` member is in the
 * shipped `.d.ts` and in the snapshot so it is visible, but it is not something
 * a release promised, so changing one is not breaking one.
 */
export function promisedBody(body) {
    return body.split('\n').filter((l) => !l.startsWith('@internal ')).join('\n');
}


/**
 * Whether `after` only ADDS optional members to `before` — an addition that
 * breaks nobody, since existing code constructs the value without the field.
 * A snapshot renders an optional member as `name: T | undefined`, and that
 * spelling is what makes the addition safe, so it is what this looks for.
 */
export function isAdditiveMembers(before, after) {
    const was = before.split('\n').filter(Boolean);
    const now = new Set(after.split('\n').filter(Boolean));
    if (was.some((line) => !now.has(line))) return false;
    const added = [...now].filter((line) => !was.includes(line));
    return added.length > 0 && added.every((line) => /:\s.*\|\s*undefined$/.test(line));
}

/**
 * A class that kept every member it had and gained more. Nobody implements a
 * class from outside, so a new member breaks no caller — unlike an interface,
 * where a required member is a demand on every implementor.
 */
export function isAddedClassMembers(before, after) {
    const was = before.split('\n').filter(Boolean);
    const now = new Set(after.split('\n').filter(Boolean));
    if (was.some((line) => !now.has(line))) return false;
    // Set against Set: a body may repeat a line, and comparing a deduplicated
    // size to a raw length reads an addition as no change.
    const wasSet = new Set(was);
    return [...now].some((line) => !wasSet.has(line));
}

/**
 * A function that kept every parameter it had and gained OPTIONAL ones at the
 * end: every call written against the old signature still compiles and means
 * the same thing, which is the whole of what @public promises. Prefix and
 * optional both — a required, changed or inserted parameter stays a failure.
 */
export function isAddedOptionalParam(before, after) {
    const parts = (s) => {
        // `<T>(a: number, b?: string): R` — the parameter list, and the rest.
        const open = s.indexOf('(');
        const close = s.lastIndexOf(')');
        if (open < 0 || close < open) return null;
        const params = s.slice(open + 1, close).trim();
        return {
            head: s.slice(0, open),
            tail: s.slice(close + 1),
            // Split on commas outside brackets, so `Map<a, b>` stays one.
            list: splitParams(params),
        };
    };
    const a = parts(before.trim());
    const b = parts(after.trim());
    if (a === null || b === null) return false;
    if (a.head !== b.head || a.tail !== b.tail) return false;
    if (b.list.length <= a.list.length) return false;
    if (a.list.some((p, i) => p !== b.list[i])) return false;
    return b.list.slice(a.list.length).every((p) => /^[A-Za-z_$][\w$]*\?\s*:/.test(p));
}

/** Top-level commas only: a parameter's own type may hold them. */
function splitParams(text) {
    const out = [];
    let depth = 0;
    let at = 0;
    for (let i = 0; i < text.length; i++) {
        const c = text[i];
        if ('<([{'.includes(c)) depth++;
        else if ('>)]}'.includes(c)) depth--;
        else if (c === ',' && depth === 0) { out.push(text.slice(at, i).trim()); at = i + 1; }
    }
    const last = text.slice(at).trim();
    if (last) out.push(last);
    return out;
}

/**
 * A string-literal union that kept every member and gained more. The direction
 * is the rule: every value that was legal still is, while a union that LOST one
 * stays a failure. A note rather than a pass, since an exhaustive switch over
 * the old set does stop compiling — a decision to take knowingly.
 */
export function isWidenedUnion(before, after) {
    // A snapshot body arrives inside a code fence; the union is what is between.
    const members = (s) => s.split('\n').filter((l) => !l.startsWith('```')).join(' ')
        .trim().split('|').map((p) => p.trim()).filter(Boolean);
    const was = members(before);
    const now = members(after);
    const literal = (p) => /^'[^']*'$/.test(p);
    if (was.length < 2 || !was.every(literal) || !now.every(literal)) return false;
    const set = new Set(now);
    return now.length > was.length && was.every((p) => set.has(p));
}

/**
 * A const that kept its released type and gained readonly properties beside it:
 * `F` became `(F) & { readonly A: 0; ... }`. The value is still everything `F`
 * was, so every use written against the release still compiles; the addition is
 * a namespace hung on the same value (`MouseButton(0)` and `MouseButton.Left`).
 * A changed `F`, or anything but readonly properties on the right, stays a failure.
 */
export function isAddedConstMembers(before, after) {
    const body = (s) => s.split('\n').filter((l) => !l.startsWith('```')).join(' ').trim();
    const was = body(before);
    const now = body(after);
    const prefix = `(${was}) & {`;
    if (!now.startsWith(prefix) || !now.endsWith('}')) return false;
    const members = now.slice(prefix.length, -1).split(';').map((m) => m.trim()).filter(Boolean);
    return members.length > 0 && members.every((m) => /^readonly [A-Za-z_$][\w$]*: [^;{}]+$/.test(m));
}

/**
 * Compare one entry against its released self. Only @public carries a promise,
 * so only @public produces a failure; @beta is noted because "may adjust" should
 * still read as a decision someone made rather than a silent edit.
 */
export function baselineFindings(was, now) {
    const failures = [];
    const notes = [];
    for (const [name, before] of was) {
        const after = now.get(name);
        if (before.tier === 'public') {
            if (!after) {
                // Deprecated for a release first is exactly what earns a removal.
                if (before.deprecated) continue;
                failures.push(`${name} — removed while @public and never @deprecated`);
            } else if (after.tier !== 'public') {
                failures.push(`${name} — @public at baseline, now @${after.tier}; a freeze does not thaw`);
            } else if (after.kind !== before.kind) {
                failures.push(`${name} — @public ${before.kind} became a ${after.kind}`);
            } else if (promisedBody(after.body) !== promisedBody(before.body)) {
                if (before.kind === 'interface'
                    && isAdditiveMembers(promisedBody(before.body), promisedBody(after.body))) {
                    notes.push(`${name} — @public interface gained an optional member`);
                } else if (before.kind === 'type'
                    && isWidenedUnion(promisedBody(before.body), promisedBody(after.body))) {
                    notes.push(`${name} — @public union gained a member`);
                } else if (before.kind === 'function'
                    && isAddedOptionalParam(promisedBody(before.body), promisedBody(after.body))) {
                    notes.push(`${name} — @public function gained an optional parameter`);
                } else if (before.kind === 'const'
                    && isAddedConstMembers(promisedBody(before.body), promisedBody(after.body))) {
                    notes.push(`${name} — @public const gained readonly properties`);
                } else if (before.kind === 'class'
                    && isAddedClassMembers(promisedBody(before.body), promisedBody(after.body))) {
                    notes.push(`${name} — @public class gained a member`);
                } else {
                    failures.push(`${name} — @public signature changed`);
                }
            }
        } else if (before.tier === 'beta') {
            if (!after) notes.push(`${name} — @beta removed`);
            else if (promisedBody(after.body) !== promisedBody(before.body)) {
                notes.push(`${name} — @beta signature changed`);
            }
        }
    }
    return { failures, notes };
}