extensions/ExtensionHost.tstypescript
import { createEvents } from "../Events";
import type { EventsHandler } from "../Events";
import type { Globe } from "../Globe";
import type { Renderer } from "../renderer/Renderer";
import { version } from "../version";
import { loadExtension } from "./load";
import type { ILoadOptions } from "./load";
import { EXTENSION_API, getUsedExtensions, onUseExtension } from "./registry";
import { satisfies } from "./semver";
import type { ExtensionState, IExtension, IExtensionInfo } from "./types";

/**
 * Extension host parameters.
 * @property {IExtension[]} [extensions] - Extensions to add.
 * @property {string[] | boolean} [exclude] - Ids of the extensions from useExtension that are not added here,
 * true for all of them.
 */
export interface IExtensionHostParams {
    extensions?: IExtension[];
    exclude?: string[] | boolean;
}

/**
 * Options of {@link ExtensionHost.add}.
 * @property {boolean} [strict] - Don't activate an extension built for another openglobus version.
 */
export interface IAddExtensionOptions {
    strict?: boolean;
}

/**
 * Options of {@link ExtensionHost.load}.
 * @property {boolean} [strict] - Don't activate an extension built for another openglobus version.
 * @property {string} [integrity] - Hash of the module file, load fails if the file was changed on the server.
 * See {@link ILoadOptions}.
 * @property {object} [og] - Openglobus module of the app, import * as og from "@openglobus/og".
 */
export interface ILoadExtensionOptions extends IAddExtensionOptions, ILoadOptions {}

/**
 * Extension module in a {@link ExtensionHost.load} list.
 * @property {string} url - Module url.
 * @property {string} [integrity] - Hash of the module file, load fails if the file was changed on the server.
 * See {@link ILoadOptions}.
 */
export interface ILoadItem {
    url: string;
    integrity?: string;
}

type ExtensionHostEventsType = ["extension:ready", "extension:error", "extension:removed"];

class ExtensionRecord implements IExtensionInfo {
    public readonly id: string;
    public readonly extension: IExtension;
    public state: ExtensionState;
    public exports: any;
    public error: Error | null;
    public abort: AbortController;
    public strict: boolean;
    /** Added only because another extension requires it. */
    public auto: boolean;
    public settled: Promise<void>;
    public settle!: () => void;

    constructor(extension: IExtension, strict = false, auto = false) {
        this.id = extension.id;
        this.extension = extension;
        this.state = "registered";
        this.exports = undefined;
        this.error = null;
        this.abort = new AbortController();
        this.strict = strict;
        this.auto = auto;
        this.settled = new Promise<void>((resolve) => (this.settle = resolve));
    }

    public get required(): string[] {
        return requirements(this.extension).map(([id]) => id);
    }

    public get optional(): string[] {
        return Object.keys(this.extension.optional || {});
    }
}

// Required ids with version ranges, an extension object has no range
function requirements(ext: IExtension): [string, string][] {
    const req = ext.requires || {};
    return Array.isArray(req) ? req.map((d) => [d.id, ""]) : Object.entries(req);
}

function ogMismatch(r: ExtensionRecord): string | null {
    const og = r.extension.og;
    return og && !satisfies(version, og, true)
        ? `Extension "${r.id}" is built for openglobus ${og}, current is ${version}`
        : null;
}

/**
 * Extensions of a renderer. Every renderer has its own host, so two globes on the page
 * have independent extension states. Extensions are activated when the renderer is initialized,
 * so its scenes, the planet too, are already there.
 * @class
 * @example
 * const globe = new Globe({ target: "map", extensions: [hello] });
 * await globe.extensions.add(other);
 * // in activate(host)
 * host.globe?.planet.addLayer(layer);
 * globe.extensions.get("demo.other").exports;
 * await globe.extensions.remove("demo.other");
 * @param {Renderer} renderer - Renderer.
 */
export class ExtensionHost {
    public readonly renderer: Renderer;

    /**
     * Globe of the renderer, null when the renderer is made without Globe.
     * @public
     */
    public globe: Globe | null;

    /**
     * Events: "extension:ready", "extension:error", "extension:removed", the callback gets IExtensionInfo.
     * @public
     */
    public readonly events: EventsHandler<ExtensionHostEventsType>;

    protected _records: Map<string, ExtensionRecord>;
    protected _order: ExtensionRecord[];
    protected _pending: ExtensionRecord[];
    protected _exclude: string[] | boolean;
    protected _unuse: () => void;
    protected _initialized: boolean;
    protected _destroyed: boolean;

    constructor(renderer: Renderer, params: IExtensionHostParams = {}) {
        this.renderer = renderer;
        this.globe = null;
        this.events = createEvents<ExtensionHostEventsType>([
            "extension:ready",
            "extension:error",
            "extension:removed"
        ]);
        this._records = new Map();
        this._order = [];
        this._pending = [];
        this._exclude = params.exclude || false;
        this._initialized = false;
        this._destroyed = false;

        this._start([...getUsedExtensions().filter((e) => this._isUsed(e)), ...(params.extensions || [])]);

        this._unuse = onUseExtension((e) => {
            if (this._isUsed(e)) this._start([e]);
        });
    }

    protected _isUsed(e: IExtension): boolean {
        return this._exclude !== true && !(Array.isArray(this._exclude) && this._exclude.includes(e.id));
    }

    /** @internal Activates the added extensions, called by the renderer on initialization. */
    public init() {
        if (this._initialized || this._destroyed) return;
        this._initialized = true;
        const pending = this._pending;
        this._pending = [];
        this._activateAll(pending);
    }

    /**
     * Adds and activates extensions, the promise resolves when they are active.
     * Adding an extension again does nothing.
     * @example
     * await globe.extensions.add(hello, { strict: true });
     * @public
     * @param {IExtension} extension - Extension.
     * @param {IAddExtensionOptions} [options] - strict doesn't activate an extension built for another openglobus version.
     * @returns {Promise<IExtensionInfo>} -
     */
    public add<T>(extension: IExtension<T>, options?: IAddExtensionOptions): Promise<IExtensionInfo<T>>;
    public add(extensions: IExtension[], options?: IAddExtensionOptions): Promise<IExtensionInfo[]>;
    public add(
        ext: IExtension | IExtension[],
        options: IAddExtensionOptions = {}
    ): Promise<IExtensionInfo | IExtensionInfo[]> {
        const list = Array.isArray(ext) ? ext : [ext];
        const records = this._start(list, options.strict);
        return Promise.all(records.map((r) => r.settled)).then(() => {
            for (const r of records) {
                if (r.state !== "active") {
                    throw r.error || new Error(`Extension "${r.id}" is ${r.state}`);
                }

                // It was added before without strict
                const og = options.strict && !r.strict && ogMismatch(r);
                if (og) {
                    throw new Error(og);
                }
            }
            return Array.isArray(ext) ? records : records[0];
        });
    }

    /**
     * Loads extension modules at runtime and adds them. Their "@openglobus/og" imports get the og of the app:
     * the og file the app runs, or options.og when og is bundled into the app.
     * Several modules are added together, so they are activated in the order of their requires.
     * @example
     * await globe.extensions.load("https://example.com/og-hello/index.js", { integrity: "sha384-..." });
     *
     * import * as og from "@openglobus/og";
     * await globe.extensions.load([rulerUrl, { url: profileUrl, integrity: "sha384-..." }], { og });
     * @public
     * @param {string | Array.<string | ILoadItem>} src - Module url or urls.
     * @param {ILoadExtensionOptions} [options] - integrity of a single module, og of the app, strict as in add.
     * @returns {Promise<IExtensionInfo>} -
     */
    public load<T = any>(src: string, options?: ILoadExtensionOptions): Promise<IExtensionInfo<T>>;
    public load(src: (string | ILoadItem)[], options?: ILoadExtensionOptions): Promise<IExtensionInfo[]>;
    public async load(
        src: string | (string | ILoadItem)[],
        options: ILoadExtensionOptions = {}
    ): Promise<IExtensionInfo | IExtensionInfo[]> {
        if (!Array.isArray(src)) {
            return this.add(await loadExtension(src, options), options);
        }
        const list = await Promise.all(
            src.map((s) =>
                typeof s === "string"
                    ? loadExtension(s, { og: options.og })
                    : loadExtension(s.url, { og: options.og, integrity: s.integrity })
            )
        );
        return this.add(list, options);
    }

    /**
     * Removes the extension, calls its deactivate.
     * @public
     * @param {string} id - Extension id.
     * @returns {Promise<void>} -
     */
    public remove(id: string): Promise<void> {
        const r = this._records.get(id);

        if (!r || r.state === "disposed") {
            return Promise.resolve();
        }

        const dependents = this._dependents(id);

        if (dependents.length) {
            return Promise.reject(new Error(`Extension "${id}" is required by ${dependents.join(", ")}`));
        }

        return Promise.resolve(this._dispose(r)).then(() => this._removeUnused(r));
    }

    protected _dependents(id: string): string[] {
        return [...this._records.values()]
            .filter(
                (d) =>
                    d.id !== id &&
                    d.state !== "failed" &&
                    d.state !== "disposed" &&
                    requirements(d.extension).some(([req]) => req === id)
            )
            .map((d) => d.id);
    }

    // Removes the extensions that were added only because r requires them
    protected async _removeUnused(r: ExtensionRecord) {
        const deps = Array.isArray(r.extension.requires) ? r.extension.requires : [];
        await Promise.all(
            deps.map((d) => {
                const dr = this._records.get(d.id);
                if (dr && dr.auto && !this._dependents(d.id).length) {
                    return this.remove(d.id).catch(() => {});
                }
            })
        );
    }

    /**
     * Returns true when the extension is active.
     * @public
     * @param {string} id - Extension id.
     * @returns {boolean} -
     */
    public has(id: string): boolean {
        return this._records.get(id)?.state === "active";
    }

    /**
     * Returns the extension info, exports is what activate returned.
     * @public
     * @param {string} id - Extension id.
     * @returns {IExtensionInfo | undefined} -
     */
    public get<T = any>(id: string): IExtensionInfo<T> | undefined {
        return this._records.get(id);
    }

    /**
     * Returns all added extensions.
     * @public
     * @returns {Array.<IExtensionInfo>} -
     */
    public list(): IExtensionInfo[] {
        return [...this._records.values()].filter((r) => r.state !== "disposed");
    }

    /**
     * @internal Removes all extensions in reverse order, called by the renderer on destroy.
     * An async deactivate is awaited before the next one.
     */
    public destroy(): Promise<void> {
        if (this._destroyed) return Promise.resolve();
        this._destroyed = true;
        this._unuse();
        this._pending = [];

        // Not active ones have nothing to deactivate
        this._records.forEach((r) => r.state !== "active" && this._dispose(r));

        let wait: Promise<void> | undefined;
        for (const r of [...this._order].reverse()) {
            wait = wait ? wait.then(() => this._dispose(r)) : this._dispose(r);
        }
        return Promise.resolve(wait);
    }

    protected _start(list: IExtension[], strict = false): ExtensionRecord[] {
        const fresh: ExtensionRecord[] = [];

        const start = (ext: IExtension, required: boolean): ExtensionRecord => {
            let r = this._records.get(ext.id);
            if (r && r.state !== "failed" && r.state !== "disposed") {
                // An extension that is already added is used as it is, e.g. another copy of the same package
                if (!required) {
                    r.auto = false;
                    if (r.extension.version !== ext.version) {
                        console.warn(
                            `Extension "${ext.id}" ${r.extension.version} is already added, ${ext.version} is not used`
                        );
                    }
                }
            } else {
                r = new ExtensionRecord(ext, strict, required);
                this._records.set(ext.id, r);
                fresh.push(r);

                if (Array.isArray(ext.requires)) {
                    ext.requires.forEach((d) => start(d, true));
                }
            }
            return r;
        };

        const records = list.map((ext) => start(ext, false));

        if (this._destroyed) {
            fresh.forEach((r) => this._fail(r, new Error("Renderer is destroyed")));
        } else if (this._initialized) {
            this._activateAll(fresh);
        } else {
            this._pending.push(...fresh);
        }

        return records;
    }

    protected _activateAll(list: ExtensionRecord[]) {
        const fresh = new Set(list);
        const records = (ids: string[]) =>
            ids.map((id) => this._records.get(id)).filter((d) => d !== undefined) as ExtensionRecord[];

        // What each extension waits for: the required ones, and the optional ones that don't wait for it
        const waits = new Map(list.map((r) => [r, records(r.required)]));
        const reaches = (from: ExtensionRecord, to: ExtensionRecord, seen = new Set<ExtensionRecord>()): boolean => {
            if (from === to) return true;
            if (seen.has(from)) return false;

            seen.add(from);

            return (waits.get(from) || []).some((d) => reaches(d, to, seen));
        };

        for (const r of list) {
            for (const d of records(r.optional)) {
                if (!reaches(d, r)) waits.get(r)!.push(d);
            }
        }

        // Dependencies start first, so the sync ones are active before their dependents
        const path: ExtensionRecord[] = [];
        const visit = (r: ExtensionRecord) => {
            if (!fresh.has(r)) return;
            const i = path.indexOf(r);
            if (i !== -1) {
                const cycle = [...path.slice(i), r].map((c) => c.id).join(" → ");
                path.slice(i).forEach((c) => {
                    fresh.delete(c);
                    this._fail(c, new Error(`Extension dependency cycle: ${cycle}`));
                });
                return;
            }

            path.push(r);
            waits.get(r)!.forEach(visit);
            path.pop();

            if (fresh.delete(r)) {
                this._wait(r, waits.get(r)!);
            }
        };
        list.forEach(visit);
    }

    protected _wait(r: ExtensionRecord, deps: ExtensionRecord[]) {
        const pending = deps.filter((d) => d.state === "registered" || d.state === "activating");

        if (pending.length) {
            Promise.all(pending.map((d) => d.settled)).then(() => this._activate(r));
        } else {
            this._activate(r);
        }
    }

    protected _check(r: ExtensionRecord): Error | null {
        const ext = r.extension;

        if (!ext.extensionApi || !satisfies(`${EXTENSION_API}.0.0`, ext.extensionApi)) {
            return new Error(
                `Extension "${r.id}" needs extension API ${ext.extensionApi}, openglobus has ${EXTENSION_API}`
            );
        }

        const og = ogMismatch(r);
        if (og) {
            if (r.strict) return new Error(og);
            console.warn(og);
        }

        for (const [id, range] of requirements(ext)) {
            const d = this._records.get(id);

            if (!d) {
                return new Error(`Extension "${r.id}" requires "${id}" ${range}, which is not added`);
            }

            if (d.state !== "active") {
                return new Error(`Extension "${r.id}" requires "${id}", which is ${d.state}`);
            }

            if (range && !satisfies(d.extension.version || "0.0.0", range, true)) {
                return new Error(`Extension "${r.id}" requires "${id}" ${range}, found ${d.extension.version}`);
            }
        }

        return null;
    }

    protected _activate(r: ExtensionRecord) {
        if (r.state !== "registered") return;

        const error = this._check(r);

        if (error) {
            this._fail(r, error);
            return;
        }

        r.state = "activating";

        let result: any;
        try {
            result = r.extension.activate(this, { signal: r.abort.signal });
        } catch (e) {
            this._fail(r, e);
            return;
        }

        if (result && typeof result.then === "function") {
            result.then(
                (exports: any) => this._ready(r, exports),
                (e: unknown) => this._fail(r, e)
            );
        } else {
            this._ready(r, result);
        }
    }

    protected _ready(r: ExtensionRecord, exports: any) {
        if (r.state !== "activating") {
            return;
        }

        r.state = "active";
        r.exports = exports;
        this._order.push(r);
        r.settle();

        this.events.dispatch(this.events["extension:ready"], r);
    }

    protected _fail(r: ExtensionRecord, e: unknown) {
        if (r.state === "disposed" || r.state === "failed") {
            return;
        }

        r.state = "failed";
        r.error = e instanceof Error ? e : new Error(String(e));
        console.error(`Extension "${r.id}" failed:`, r.error);
        r.settle();

        this.events.dispatch(this.events["extension:error"], r);
    }

    // Returns a promise only for an async deactivate
    protected _dispose(r: ExtensionRecord): Promise<void> | undefined {
        const wasActive = r.state === "active";
        r.state = "disposed";
        r.abort.abort();
        this._order = this._order.filter((o) => o !== r);
        this._pending = this._pending.filter((o) => o !== r);

        // The record stays until deactivate is done, so deactivate gets its exports with host.get(id)
        const finish = () => {
            if (this._records.get(r.id) === r) {
                this._records.delete(r.id);
            }

            r.settle();

            this.events.dispatch(this.events["extension:removed"], r);
        };

        let result: any;
        try {
            result = wasActive && r.extension.deactivate ? r.extension.deactivate(this) : undefined;
        } catch (e) {
            console.error(`Extension "${r.id}" deactivate error:`, e);
        }

        if (result && typeof result.then === "function") {
            return result.then(finish, (e: unknown) => {
                console.error(`Extension "${r.id}" deactivate error:`, e);
                finish();
            });
        }
        finish();
        return undefined;
    }
}