All files / blong-gogo/src layerProxy.ts

86.54% Statements 283/327
71.92% Branches 41/57
85.71% Functions 6/7
86.54% Lines 283/327

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 3281x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 177x 177x 177x 177x 1x 90x 90x 90x       90x 90x 90x 177x 177x 83x 83x 83x 83x 83x 83x 187x 187x     187x 23x 23x 23x 11x 187x 187x 83x 187x 187x 187x 187x     187x     187x     187x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 187x 187x 187x 187x 162x 162x 162x 162x 162x 162x 162x 162x 162x         162x 22x 162x 140x 140x 140x 140x 162x 187x 187x 83x 77x 1x 1x 283x 283x 283x 283x 283x 283x 283x 283x 283x 283x 283x 283x 283x 283x 283x 283x 283x 283x 283x 283x 283x 551x 551x 551x 551x 551x 551x 551x 551x 551x 551x   551x   551x 283x 551x 268x 268x 268x 268x 268x 268x 268x 268x 268x 268x 268x 268x 268x 268x 266x 266x 76x 190x 190x 266x 266x 266x 380x 380x 380x 380x 380x 380x 380x 380x 380x 191x 380x 380x 266x 266x 266x 189x 189x 189x 189x 189x                                                     189x 189x 189x 189x 189x 189x 189x 89x 89x 89x 89x 89x 89x 44x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 89x 89x 89x 89x 89x 89x   45x 45x 45x 45x 189x 189x 189x 189x 266x 266x 77x 77x 77x 77x 77x 77x 77x 77x 77x 266x 266x 266x 268x 268x 551x 551x 283x 283x 283x  
import {
    kind,
    type Adapter,
    type IAdapterFactory,
    type IApiSchema,
    type IConfigRuntime,
    type IErrorFactory,
    type ILib,
    type IMeta,
    type IModuleConfig,
    type IObjectSchema,
} from '@feasibleone/blong/types';
import merge from 'ut-function.merge';
 
import createPort from './AdapterBase.ts';
import ConfigRuntime from './ConfigRuntime.ts';
import createHandlerProxy from './handlerProxy.ts';
import {methodId} from './lib.ts';
import type {IPort} from './Port.ts';
 
/**
 * Create the handler closure that is pushed into `where.methods[]`.
 *
 * This closure is invoked later by `Registry._createHandlers()` to assemble the
 * layerApi object, load libraries, and process handler/validation/api/model items.
 */
function createHandlerClosure(
    others: any[], // eslint-disable-line @typescript-eslint/no-explicit-any
    moduleConfigSlice: unknown,
    name: string,
    namespace: string,
    source: string,
    target: {result: {error: unknown; schema: unknown}},
    apiSchema: IApiSchema | undefined,
    configRuntime: IConfigRuntime | undefined,
): (params: {
    remote: (methodName: string) => () => unknown;
    lib: ILib;
    local: object;
    literals: unknown[];
    port: Adapter;
    attachCheckpoint?: (meta: IMeta) => void;
}) => Promise<void> {
    return async function ({
        remote,
        lib,
        local,
        literals,
        port,
        attachCheckpoint,
        ...rest
    }: {
        remote: (methodName: string) => () => unknown;
        lib: ILib;
        local: object;
        literals: unknown[];
        port: Adapter;
        attachCheckpoint?: (meta: IMeta) => void;
    }) {
        const mergedConfig = ConfigRuntime.mergeLayerConfig(
            moduleConfigSlice,
            port?.config?.[namespace],
        );
        const layerApi = {
            ...rest,
            config: mergedConfig,
            lib: new Proxy(lib, {
                get(target: ILib, functionName: string) {
                    const rec = target as unknown as Record<string, unknown>;
                    let fn: () => unknown;
                    return (
                        rec[functionName] ??
                        function (...params: unknown[]) {
                            fn ||= rec[functionName] as () => unknown;
                            if (!fn)
                                throw new Error(
                                    `Lib property '${functionName.toString()}' not found. Available properties are: ${Object.keys(
                                        rec,
                                    ).sort()}`,
                                );
                            return fn.apply(port, params as []);
                        }
                    );
                },
            }),
            handler: createHandlerProxy(local, port, remote, attachCheckpoint, lib, mergedConfig),
            errors: target.result.error,
            schema: target.result.schema,
        };
        for (let what of others) {
            switch (`${typeof what}:${kind(what)}`) {
                case 'object:lib':
                    merge(lib, what);
                    break;
                case 'function:lib':
                    what = await what(layerApi);
                    if (typeof what === 'function')
                        (lib as unknown as Record<string, unknown>)[what.name] = what;
                    else merge(lib, what);
            }
        }
        for (let what of others) {
            const kindOfWhat = kind(what);
            switch (`${typeof what}:${kindOfWhat}`) {
                case 'object:handler':
                case 'object:validation':
                    merge(local, what);
                    break;
                case 'function:api':
                    merge(local, await apiSchema!.schema(what(layerApi), source));
                    break;
                case 'object:schema':
                    if (target.result.schema) merge(target.result.schema as object, what as object);
                    break;
                case 'function:schema': {
                    configRuntime?.enterConfig();
                    try {
                        what = await what(layerApi);
                    } finally {
                        configRuntime?.exitConfig();
                    }
                    if (typeof what === 'object' && what !== null && target.result.schema)
                        merge(target.result.schema as object, what as object);
                    break;
                }
                case 'function:handler':
                case 'function:validation':
                case 'function:model':
                case 'function:fixture':
                    configRuntime?.enterConfig();
                    try {
                        what = await what(layerApi);
                    } finally {
                        configRuntime?.exitConfig();
                    }
                    const created = await (
                        port as unknown as {createHandlers?: (opts: unknown) => Promise<unknown>}
                    )?.createHandlers?.({
                        handlers: typeof what === 'function' ? [what] : what,
                        layerApi,
                        kind: kindOfWhat,
                    });
                    if (typeof what === 'function') {
                        (local as Record<string, unknown>)[methodId(what.name)] = what;
                    } else {
                        literals.push(what);
                        what = methodId(what);
                        merge(local, what);
                    }
                    Object.assign(local, methodId(created));
            }
        }
    };
}
 
export default function layerProxy(
    errors: IErrorFactory | undefined,
    objectSchema: IObjectSchema | undefined,
    apiSchema: IApiSchema | undefined,
    port: (() => void) | undefined,
    moduleConfig: {
        pkg: IModuleConfig['pkg'];
        base: string;
        configNames?: string[];
    } & {
        [name: string]: object;
    },
    configRuntime?: IConfigRuntime,
): {result: {error: unknown; schema: unknown}; feature: unknown} {
    return new Proxy(
        {
            error: errors?.register.bind(errors),
            result: {error: errors?.get(), schema: objectSchema},
            feature() {},
        },
        {
            get(
                target: {
                    error: unknown;
                    result: {error: unknown; schema: unknown};
                    feature: unknown;
                },
                name: string,
                receiver: unknown,
            ) {
                switch (name) {
                    case 'utPort':
                        return port;
                    case 'registerErrors':
                        return target.error;
                    case 'result':
                        return target.result;
                    default:
                        return (fn: unknown, namespace: string, source: string) => {
                            type Where = {
                                methods: unknown[];
                                port?: unknown;
                                source?: string;
                                config?: unknown;
                            };
                            const resultRecord = target.result as Record<string, Where>;
                            const where: Where = (resultRecord[name] ??= {methods: [], source});
                            const targetRec = target as unknown as Record<
                                string,
                                ((fn: unknown) => void) | undefined
                            >;
                            if (targetRec[name]) merge(where, targetRec[name]!(fn));
                            else {
                                const fnArr: unknown[] = Array.isArray(fn)
                                    ? fn
                                    : fn != null
                                      ? [fn]
                                      : [];
                                const [ports, others] = fnArr.reduce(
                                    (prev: [unknown[], unknown[]], item: unknown) => {
                                        if (
                                            (port &&
                                                (item as {prototype?: unknown}).prototype instanceof
                                                    port) ||
                                            ['adapter', 'orchestrator'].includes(
                                                kind(item as unknown as Parameters<typeof kind>[0]),
                                            )
                                        )
                                            prev[0].push(item);
                                        else prev[1].push(item);
                                        return prev;
                                    },
                                    [[], []] as [unknown[], unknown[]],
                                ) as [unknown[], unknown[]];
                                ports.forEach(what => {
                                    if (
                                        what &&
                                        port &&
                                        (what as {prototype?: unknown}).prototype instanceof port
                                    ) {
                                        where.port = async (
                                            {
                                                id,
                                                ...portApi
                                            }: Parameters<IAdapterFactory>[0] & {id: string},
                                            configOverride: object,
                                        ) => {
                                            const config = {
                                                ...moduleConfig?.[name],
                                                id,
                                                pkg: moduleConfig.pkg,
                                            };
                                            const port = new (what as unknown as IPort)({
                                                ...portApi,
                                                config: configOverride
                                                    ? merge({}, config, configOverride)
                                                    : config,
                                                configBase: moduleConfig.base,
                                            });
                                            await (
                                                port as unknown as {init: () => Promise<void>}
                                            ).init();
                                            return port;
                                        };
                                        (where.port as unknown as {config: unknown}).config =
                                            moduleConfig?.[name];
                                    } else if (
                                        what &&
                                        ['adapter', 'orchestrator'].includes(
                                            kind(what as unknown as Parameters<typeof kind>[0]),
                                        )
                                    ) {
                                        where.port = async (
                                            api: Parameters<IAdapterFactory>[0] & {id: string},
                                            configOverride: object,
                                        ) => {
                                            const {id} = api;
                                            if (!id)
                                                return (what as IAdapterFactory)(
                                                    api as Parameters<IAdapterFactory>[0],
                                                );
                                            // Assign `handlers` directly onto the api object rather
                                            // than creating a spread copy.  AdapterBase stores
                                            // `_api = api`, and Registry.ts sets
                                            // `api.attachHandlers = fn` *after* this factory
                                            // returns.  Keeping the same object reference ensures
                                            // that assignment is visible to `_api.attachHandlers`
                                            // when `start()` is called later.
                                            (api as unknown as Record<string, unknown>).handlers =
                                                what;
                                            const port = await createPort(
                                                api as unknown as Parameters<typeof createPort>[0],
                                                moduleConfig.base,
                                                moduleConfig.configNames,
                                            );
                                            const config = {
                                                ...moduleConfig?.[name],
                                                id,
                                                pkg: moduleConfig.pkg,
                                            };
                                            await port.init(
                                                configOverride
                                                    ? merge({}, config, configOverride)
                                                    : config,
                                            );
                                            return port;
                                        };
                                        (where.port as unknown as {config: unknown}).config =
                                            moduleConfig?.[name];
                                    }
                                });
                                if (others.length)
                                    where.methods.push(
                                        createHandlerClosure(
                                            others as unknown[],
                                            moduleConfig[name],
                                            name,
                                            namespace,
                                            source,
                                            target,
                                            apiSchema,
                                            configRuntime,
                                        ),
                                    );
                            }
                            return receiver;
                        };
                }
            },
        },
    );
}