import * as validation from "@jet/environment/json/validation";
import { LegacyRuntime } from "@jet/environment/runtime";
export class AppStoreRuntime extends LegacyRuntime {
    constructor(dispatcher, objectGraph) {
        super(dispatcher, objectGraph, {});
    }
    exportingService(name, service) {
        this.wrapServiceInValidation(service);
        const existingService = this.serviceWithName(name) || {};
        const newService = {
            ...existingService,
            ...service,
        };
        return super.exportingService(name, newService);
    }
    // eslint-disable-next-line @typescript-eslint/ban-types
    exportingServiceName(name, functionName, implementation) {
        const service = {};
        service[functionName] = implementation;
        this.exportingService(name, service);
    }
    wrapServiceInValidation(service) {
        for (const memberName of Object.keys(service)) {
            const serviceFunction = service[memberName];
            // For every service route function that we find, we're going
            // to wrap it in a thunk so that we can attach validation
            // incidents to it before it's returned back to native code.
            if (serviceFunction instanceof Function) {
                // Using a regular function here because we want to forward
                // `this` as well as our arguments to the wrapped function.
                service[memberName] = function validationThunk(...args) {
                    // Execute the function
                    const returnValue = serviceFunction.apply(this, args);
                    // Ensure we record validation incidents after the fact
                    if (returnValue instanceof Promise) {
                        return returnValue.then((value) => {
                            validation.recordValidationIncidents(value);
                            return value;
                        });
                    }
                    else {
                        // This would be a violation of the calling convention,
                        // but I guess we might as well consume the incidents.
                        validation.recordValidationIncidents(returnValue);
                        return returnValue;
                    }
                };
            }
        }
    }
}
//# sourceMappingURL=runtime.js.map