All files / core/blong-gogo/src Watch.ts

72.66% Statements 691/951
65.11% Branches 112/172
69.81% Functions 37/53
72.66% Lines 691/951

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 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 9521x 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 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2925x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2926x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 16x 19x 10x 10x 76x 76x 76x 76x 10x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 6x 96x 6x 5x 5x 5x 1x 1x 6x 1x 1x 1x 1x         6x 6x 6x 5x 5x 5x 5x 5x 5x     5x 5x 1x 1x 1x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x                 47x 47x 47x 47x 47x 47x 1x 1x 1x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 1x 1x 1x 47x 47x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 75x 75x 75x 75x 9x 9x 40x 40x 40x 9x 9x 9x 380x 380x 380x 9x 9x 9x 1x 1x 1x 25x 25x 1x 1x 1x 1x 1x 1x 1x 1x 1x 278x 278x 278x 278x 278x 278x 278x 278x             278x 278x 278x 278x 2x 2x 2x 2x 2x 2x 278x 278x 278x 1x 1x                         7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 736x 736x 736x 736x 736x 736x 736x 736x 736x 736x 736x 736x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x         7x 736x 736x 1x 7x 7x 7x   1x 1x 1x 1x 1x 1x 1x 1x 1x                             3112x 3076x 2566x 2566x 2565x 2518x 2518x               1x   2498x 2498x 7x 2498x 2498x 2498x 2498x 2498x   2498x 2498x 2498x 2498x 2498x 11x 11x 20x     20x 20x 20x 20x 20x                       20x 20x 20x 20x 20x       146x 146x   86x 86x         736x 736x 736x 90x 90x 90x 736x 736x 736x       736x 736x 736x 81x 81x 81x 736x 736x 736x 536x 536x 536x 736x 736x 736x       1095x 1095x 1095x 1095x 1095x 1095x 736x 736x 736x   736x 736x 736x 1095x 359x 359x 359x 359x 359x 356x 356x 280x 359x 278x 278x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 2x 2x 2x 2x             28x 28x 28x 76x 276x 276x 276x 276x 276x 276x 276x 276x 212x   276x 276x 276x 276x 276x   28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x                                                                               76x 76x 76x 76x 76x 76x 76x 76x 76x                                                                                               28x 28x 28x 28x 28x 28x 28x 28x 28x             28x                     28x 28x 28x             28x 28x 28x 28x 28x 28x             48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 28x 28x 28x 28x 48x 20x 20x 20x 20x 20x 20x 20x   20x 20x 20x 20x 25x 25x 25x 25x 25x 25x           25x 25x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 62x 62x 62x 62x           62x 62x 62x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 62x 62x 62x                                   62x                                 22x 22x 22x 22x 22x 22x 25x 25x 25x 25x 25x 1x 1x 24x 24x 24x 24x 24x 24x 24x 24x 2x 2x 2x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 1x 1x 41x       41x 1x  
import {withProgress} from '@feasibleone/blong-lib';
import {
    handler,
    Internal,
    kind,
    type ConfigDiff,
    type Handlers,
    type IAdapterRegistry,
    type IApiSchema,
    type IConfigRuntime,
    type IErrorFactory,
    type ILog,
    type IMeta,
    type IModuleConfig,
    type IObjectSchema,
    type IPlatformApi,
    type IRegistry,
    type IRemote,
    type IWatcher,
} from '@feasibleone/blong/types';
import type {Dirent} from 'node:fs';
import merge from 'ut-function.merge';
 
import layerProxy from './layerProxy.ts';
// The chain is server-side code — it pulls `node:assert` and the event emitter the test
// executor is built on — so only its types may be imported statically: a value import
// puts the chain in the browser's eager module graph, where linking its `node:events`
// import fails before a single handler runs. The Allure session is ended through a
// dynamic import for the same reason.
import type {IAllureRunOptions} from './chain.ts';
import {runInFlow, withStep} from './responseContext.ts';
 
export interface IWatch {
    start: (realm: IRegistry, remote: IRemote, configOverride: object) => Promise<void>;
    test: (tester: unknown) => Promise<void>;
    stop: () => Promise<void>;
    load: <T extends {result: unknown}>(
        config: {name: string; pkg: IModuleConfig['pkg']; base: string},
        isDirectory: boolean | Record<string, () => Promise<unknown>> | undefined,
        isFile: boolean | (() => Promise<unknown>) | undefined,
        ...path: string[]
    ) => Promise<(api: T) => T>;
    /** Attach a ConfigRuntime so config-file changes trigger in-process reloads */
    setConfigRuntime?(configRuntime: IConfigRuntime): void;
    /** Attach the registry objectSchema so hot-reload paths can pass it to layerProxy */
    setObjectSchema?(schema: IObjectSchema): void;
    /**
     * Structural snapshot of the handler folders/files discovered on disk.
     * Data-only so it can be returned straight from an API endpoint.
     */
    describe(): IWatchDescription;
}
 
/** Handler folders/files discovered from disk, keyed by their owning realm. */
export interface IWatchDescription {
    folders: Array<{group: string; realm: string; dir: string}>;
    files: Array<{file: string; realm: string}>;
    layerFiles: Array<{file: string; realm: string}>;
}
 
interface ITestContext {
    test: (name: string, fn: (t: unknown) => void | Promise<void>) => unknown;
}
const isYaml = (filename: string): boolean => /\.ya?ml$/i.test(filename);
const isJSON = (filename: string): boolean => /\.jsonl?$/i.test(filename);
const isCode = (filename: string): boolean => /(?<!\.d)\.m?(t|j)sx?$/i.test(filename);
const isLayerActivation = (filename: string): boolean =>
    /^layer\.(server|browser)\.[mc]?[tj]sx?$/i.test(filename);
const isConfig = (filename: string): boolean => /^config\.[mc]?[tj]sx?$/i.test(filename);
const isPlay = (filename: string): boolean => /\.play\.[mc]?[tj]sx?$/i.test(filename);
const isTest = (filename: string): boolean => /\.test\.[mc]?[tj]sx?$/i.test(filename);
/**
 * The handler-group factory a folder may hold for typing its injected libraries.
 *
 * `handlerGroup.ts` defines the `handler` its siblings import (`handlerGroup<L>()`),
 * so it is a plain module — no default export the loader could classify — and it
 * must not be loaded as a handler, nor reported as a plain module in a group.
 */
const isHandlerGroup = (filename: string): boolean =>
    /^handlerGroup\.[mc]?[tj]sx?$/i.test(filename);
 
/** The predicate above, exported so a test pins the convention (like `affectedNamespaces`). */
export {isHandlerGroup};
 
const prefixRE: RegExp = /(?:\d+-)?(.*)/;
 
/**
 * The name a test group is displayed by: `test.meter.flow` reads as `meter flow`.
 *
 * The group's handler may name itself instead (`group("gateway meter flow")`), which
 * is what the handler's own reader sees; this is the name to fall back to.
 */
function groupName(method: string): string {
    return method.replace(/^test\./, '').replace(/\./g, ' ');
}
 
interface IConfig {
    enabled: boolean;
    test: string;
    ignored: string[];
    configs: string[];
    logLevel: Parameters<ILog['logger']>[0];
    /** Allure reporting options, as the framework config supplies them. */
    allure?: IAllureRunOptions;
}
 
// ---------------------------------------------------------------------------
// affectedNamespaces
// ---------------------------------------------------------------------------
 
/**
 * Given a diff and the set of known port names (e.g. `"realm.adapter.db"`),
 * return the subset of port names whose config sub-tree changed.
 *
 * A port named `"realm.adapter.db"` is considered affected if any diff key
 * starts with `"realm.adapter.db."` or equals `"realm.adapter.db"`.
 */
export function affectedNamespaces(diff: ConfigDiff, portNames: Iterable<string>): Set<string> {
    const affected = new Set<string>();
    for (const portName of portNames) {
        for (const diffKey of diff.keys()) {
            if (diffKey === portName || diffKey.startsWith(portName + '.')) {
                affected.add(portName);
                break;
            }
        }
    }
    return affected;
}
 
/**
 * The port surface a config reload needs — `IRegistry`, narrowed so the reload
 * loop can be driven with fakes (see `Watch.test.ts`).
 */
export interface IReloadablePort {
    /** Zero-downtime path: the port reconfigures itself. */
    configChanged?(diff: ConfigDiff, next: unknown, prev: unknown): Promise<void> | void;
    stop(): Promise<void> | void;
    start(configOverride: object): Promise<void> | void;
    ready(): Promise<void> | void;
}
 
export interface IReloadRegistry {
    ports: {keys: () => Iterable<string>};
    getPort(id: string): Promise<IReloadablePort | undefined>;
    createPort(id: string): Promise<IReloadablePort | undefined>;
    /**
     * The log component, when the process has one.
     *
     * It is not a port, so nothing in the port pipeline above would ever reach it — and it owns
     * switches that are *configuration*: `log.calls` decides whether the flow ledger, and so every
     * flow page and every diagram, sees anything at all. A value that could only change at start-up
     * is a value an operator cannot use on the process that is misbehaving, so the same reload that
     * reconfigures a port asks the log once. The component compares what it is given and does
     * nothing when its own block did not move (`@@D-941`).
     */
    logComponent?: {
        configChanged?(diff: ConfigDiff, next: unknown, prev: unknown): Promise<void> | void;
    };
}
 
/**
 * Apply a config reload to the ports the diff affects.
 *
 * A port that implements `configChanged` is asked to reconfigure itself — the
 * zero-downtime path, which is what keeps an in-flight request or an expensive
 * connection alive. A port that does not is stopped and started again with the
 * current override. A port the diff does not name is not touched at all, which is
 * the property that makes a log-level change safe: it must not cost a database
 * pool.
 *
 * Returns the number of ports the loop reached, and reports each one through
 * `onReloaded` so the caller's progress view can follow it.
 */
export async function applyConfigReload(
    registry: IReloadRegistry,
    affected: Iterable<string>,
    diff: ConfigDiff,
    next: object,
    prev: object,
    configOverride: object,
    onPortError: (error: unknown) => void = () => undefined,
    onReloaded?: (done: number, total: number) => void,
): Promise<number> {
    const total = [...affected].length;
    let reloaded = 0;
    for (const portId of affected) {
        const portInstance = await registry.getPort(portId);
        if (portInstance) {
            if (typeof portInstance.configChanged === 'function') {
                try {
                    await portInstance.configChanged(diff, next, prev);
                } catch (error) {
                    onPortError(error);
                }
            } else {
                await portInstance.stop();
                const fresh = await registry.createPort(portId);
                if (fresh) {
                    await fresh.start(configOverride);
                    await fresh.ready();
                }
            }
        }
        reloaded += 1;
        onReloaded?.(reloaded, total);
    }
    // After the ports, so a change that both a port and the log care about reaches the port first:
    // the log is the thing that reports what happened, and a report written before the switch it
    // describes would read as if nothing had changed.
    try {
        await registry.logComponent?.configChanged?.(diff, next, prev);
    } catch (error) {
        onPortError(error);
    }
    return reloaded;
}
 
export default class Watch extends Internal implements IWatch {
    #config: IConfig = {
        enabled: false,
        test: '',
        ignored: [],
        configs: [],
        logLevel: 'debug',
        allure: undefined,
    };
 
    #handlerFolders: Map<string, {name: string; pkg: IModuleConfig['pkg']; base: string}> =
        new Map();
    #handlerFiles: Map<string, {name: string; pkg: IModuleConfig['pkg']; base: string}> = new Map();
    #layerFiles: Map<string, {name: string; pkg: IModuleConfig['pkg']; base: string}> = new Map();
    /**
     * Every code file discovered inside a handler folder, mapped to its realm.
     * Kept separate from `#handlerFiles` (which drives hot-reload decisions and
     * is deliberately populated only for single-file loads) so introspection can
     * report the full file set without changing reload behaviour.
     */
    #discoveredFiles: Map<string, string> = new Map();
    #watchers: IWatcher[] = [];
    #port: () => unknown;
    #error: IErrorFactory;
    #objectSchema: IObjectSchema;
    #apiSchema: IApiSchema;
    #emit: EventTarget = new EventTarget();
    #configRuntime: IConfigRuntime | null = null;
    #platform: IPlatformApi;
 
    public constructor(
        config: IConfig,
        {
            error,
            log,
            port,
            apiSchema,
            objectSchema,
            platform,
        }: {
            error: IErrorFactory;
            log: ILog;
            port: () => unknown;
            apiSchema: IApiSchema;
            objectSchema: IObjectSchema;
            platform: IPlatformApi;
        },
    ) {
        super({log});
        this.merge(this.#config, config);
        this.#port = port;
        this.#error = error;
        this.#apiSchema = apiSchema;
        this.#objectSchema = objectSchema;
        this.#platform = platform;
    }
 
    /** Attach the registry objectSchema so hot-reload paths can pass it to layerProxy */
    public setObjectSchema(schema: IObjectSchema): void {
        this.#objectSchema = schema;
    }
 
    /**
     * Structural snapshot of what is loaded from disk.
     *
     * Group ids follow the same convention the loader registers with
     * (`<realm>.<folder>`, see `_loadHandlers`). Paths are made relative to the
     * process cwd so the result is stable across machines.
     */
    public describe(): IWatchDescription {
        const relative = (file: string): string => this.#platform.relative('.', file);
        const folderEntries = Array.from(this.#handlerFolders.entries()).map(([dir, config]) => ({
            group: `${config.name}.${this.#platform.basename(dir)}`,
            realm: config.name,
            dir: relative(dir),
        }));
        const toFiles = (map: Map<string, {name: string}>): Array<{file: string; realm: string}> =>
            Array.from(map.entries()).map(([file, config]) => ({
                file: relative(file),
                realm: config.name,
            }));
        return {
            folders: folderEntries,
            files: Array.from(this.#discoveredFiles.entries()).map(([file, realm]) => ({
                file: relative(file),
                realm,
            })),
            layerFiles: toFiles(this.#layerFiles),
        };
    }
 
    /** Attach a ConfigRuntime so config-file changes trigger in-process reloads */
    public setConfigRuntime(configRuntime: IConfigRuntime): void {
        this.#configRuntime = configRuntime;
    }
 
    /**
     * Validates handler name matches filename and sets name property for anonymous handlers
     * @param item The handler item to validate
     * @param filename The file path
     * @param expectedName The expected handler name based on filename
     * @returns The handler name (either explicit or derived from filename)
     */
    private _validateAndSetHandlerName(
        item: {name?: string},
        filename: string,
        expectedName?: string,
    ): string {
        const actualName = item['name'] && item['name'] !== 'default' ? item['name'] : null;
 
        // For files defining a single handler, report error on name mismatch
        if (kind(item) === 'handler' && actualName && actualName !== expectedName) {
            throw new Error(
                `Handler name mismatch in '${filename}': ` +
                    `function is named '${actualName}' but file is named '${expectedName}.ts'. ` +
                    `Either rename the function to '${expectedName}' or rename the file to '${actualName}.ts'.`,
            );
        }
 
        const name = actualName || expectedName;
        // Ensure handler name property is set for anonymous handlers
        if (kind(item) === 'handler' && !actualName) {
            Object.defineProperty(item, 'name', {
                value: name,
                configurable: true,
                enumerable: false,
            });
        }
 
        return name!;
    }
 
    private async _generate(files: {filename: string; name: string}[], dir: string): Promise<void> {
        const [schema, names] = files.reduce(
            (prev, {filename, name}) => {
                const schema = this.#platform
                    .readFileSync(filename)
                    .toString()
                    .match(
                        /^(\/\*\*((?!\*\/\n).)*\*\/\n)?type Handler = \(((?!(>|}|>});?\n).)*(>|}|>});?\n/ms,
                    )?.[0];
                return schema
                    ? [
                          [...prev[0], schema.replace('type Handler = (', `type ${name} = (`)],
                          [...prev[1], name],
                      ]
                    : prev;
            },
            [[] as string[], [] as string[]],
        );
        const codeGen = '@sinclair/typebox-codegen';
        const {Formatter, TypeScriptToTypeBox} = await import(/* @vite-ignore */ codeGen);
        if (schema.length)
            this.#platform.writeFileSync(
                this.#platform.join(dir, '~.schema.ts'),
                Formatter.Format(`import {validationHandlers} from '@feasibleone/blong';
            import { Type, type Static } from 'typebox';
 
            ${TypeScriptToTypeBox.Generate(schema.sort().join('\n'), {useTypeBoxImport: false}).trim()}
 
            export default validationHandlers({
                ${names.sort().join(',\n')}
            });
 
            declare module '@feasibleone/blong' {
                interface ISchema {
                    ${names
                        .map(
                            name =>
                                `${name}(params: Parameters<${name}>[0], $meta: IMeta): ReturnType<${name}>;`,
                        )
                        .join('\n')}
                }
            }
 
        `),
            );
    }
 
    private async _loadHandlers(
        directory: true | Record<string, () => Promise<unknown>> | undefined,
        config: {
            name: string;
            pkg: IModuleConfig['pkg'];
            base: string;
            configNames?: string[];
            namespace?: Record<string, object>;
            [other: string]: unknown;
        },
        ...path: string[]
    ): Promise<<T>(api: T) => T> {
        const dir = this.#platform.join(...path);
        const handlers: unknown[] = [];
        const validations: unknown[] = [];
        const apis: unknown[] = [];
        const libs: unknown[] = [];
        const assets: unknown[] = [];
        const handlerFilenames: {filename: string; name: string}[] = [];
        let latest = 0;
        const isFile = () => true;
        const isDirectory = () => false;
        const allFiles =
            directory === true
                ? await this.#platform.scan(dir)
                : Object.keys(directory ?? {}).map(path => ({
                      name: this.#platform.basename(path),
                      isFile,
                      isDirectory,
                  }));
        // if (directory !== true) debugger;
        const configFile = allFiles.find(entry => entry.isFile() && isConfig(entry.name));
        if (configFile) {
            const configFilePath = this.#platform.join(dir, configFile.name);
            const loaded = (
                await import(
                    /* @vite-ignore */ this.#config.enabled
                        ? configFilePath + '?' + Date.now()
                        : configFilePath
                )
            ).default;
            const folderName = this.#platform.basename(dir);
            const mutableConfig = config;
            const configNames = mutableConfig.configNames ?? [];
            const folderConfig =
                loaded &&
                typeof loaded === 'object' &&
                typeof loaded.default === 'object' &&
                loaded.default !== null
                    ? merge(
                          {},
                          ...['default', ...configNames].map(name => loaded[name]).filter(Boolean),
                      )
                    : (loaded ?? {});
            const namespaceOverride = mutableConfig?.namespace?.[folderName] ?? {};
            mutableConfig[folderName] = merge({}, folderConfig, namespaceOverride);
        }
        const handlerFiles = allFiles
            .sort()
            .filter(
                entry =>
                    entry.isFile() &&
                    isCode(entry.name) &&
                    !isLayerActivation(entry.name) &&
                    !isConfig(entry.name) &&
                    !isHandlerGroup(entry.name) &&
                    !isPlay(entry.name) &&
                    !isTest(entry.name),
            );
        await this.#apiSchema?.generateDir(dir, handlerFiles as Dirent[]);
        for (const handlerEntry of handlerFiles) {
            const filename = this.#platform.join(dir, handlerEntry.name);
            if (
                directory === true &&
                handlerEntry.name === '~.schema.ts' &&
                this.#platform.statSync(filename).mtime.getTime() < latest &&
                handlerFilenames.length
            )
                await this._generate(handlerFilenames, dir);
            if (directory === true && (await this.#apiSchema.generateFile(filename))) continue;
            const item =
                directory === true
                    ? (
                          await import(
                              /* @vite-ignore */ this.#config.enabled
                                  ? filename + '?' + Date.now()
                                  : filename
                          )
                      ).default
                    : ((await directory![filename]()) as {default: unknown}).default;
            if (!item) {
                // Declared rather than levelled (`@@T-710`): the identifier names what happened, so an
                // operator can raise it on its own instead of raising every line the framework writes.
                this.signal?.frameworkSourceEmpty?.({file: filename});
                continue;
            }
            const expectedName = this.#platform.basename(
                filename,
                this.#platform.extname(filename),
            );
            this.#discoveredFiles.set(filename, config.name);
            const name = expectedName;
            (kind(item) === 'validation'
                ? validations
                : kind(item) === 'api'
                  ? apis
                  : kind(item) === 'lib'
                    ? libs
                    : handlers
            ).push(item);
            if (kind(item) === 'handler') {
                if (directory === true)
                    latest = Math.max(latest, this.#platform.statSync(filename).mtime.getTime());
                handlerFilenames.push({name, filename});
            }
        }
        const assetFiles = allFiles.filter(
            entry => entry.isFile() && (isYaml(entry.name) || isJSON(entry.name)),
        );
        for (const assetFile of assetFiles) {
            const filename = this.#platform.join(dir, assetFile.name);
            assets.push(
                handler(() => ({
                    assets: {[this.#platform.basename(filename)]: `file://${filename}`},
                })),
            );
        }
        this.#handlerFolders.set(dir, config);
        return api => {
            const apiAny = api as Record<string, (...args: unknown[]) => unknown>;
            if (validations.length)
                apiAny[this.#platform.basename(dir) + '.validation'](
                    [...libs, ...validations],
                    config.name + '.' + this.#platform.basename(dir) + '.validation',
                    this.#platform.relative('.', dir),
                );
            if (apis.length)
                apiAny[this.#platform.basename(dir) + '.api'](
                    [...libs, ...apis],
                    config.name + '.' + this.#platform.basename(dir) + '.api',
                    this.#platform.relative('.', dir),
                );
            if (assets.length)
                apiAny[this.#platform.basename(dir) + '.asset'](
                    assets,
                    config.name + '.' + this.#platform.basename(dir) + '.asset',
                    this.#platform.relative('.', dir),
                );
            if (handlers.length)
                apiAny[this.#platform.basename(dir)](
                    [...libs, ...handlers],
                    config.name + '.' + this.#platform.basename(dir),
                    this.#platform.relative('.', dir),
                );
            return api;
        };
    }

    public async load<T extends {result: unknown}>(
        config: {name: string; pkg: IModuleConfig['pkg']; base: string},
        isDirectory: boolean | Record<string, () => Promise<unknown>> | undefined,
        isFile: boolean | object | undefined,
        ...path: string[]
    ): Promise<(api: T) => T> {
        if (isDirectory) {
            return this._loadHandlers(
                isDirectory === true
                    ? true
                    : (isDirectory as Record<string, () => Promise<unknown>>),
                config,
                ...path,
            );
        } else if (isFile) {
            // if (isFile !== true) debugger;
            const filename = this.#platform.join(...path);
            if (
                isCode(filename) &&
                !isLayerActivation(this.#platform.basename(filename)) &&
                !isHandlerGroup(this.#platform.basename(filename)) &&
                !isPlay(this.#platform.basename(filename)) &&
                !isTest(this.#platform.basename(filename))
            ) {
                const item =
                    typeof isFile === 'function'
                        ? (await isFile()).default
                        : (
                              await import(
                                  /* @vite-ignore */
                                  this.#config.enabled ? filename + '?' + Date.now() : filename
                              )
                          ).default;
                // A module without a default export is a plain module shared by
                // the group's handlers (e.g. `account.ts`, `accessModel.ts`), not
                // a handler — the loader ignores it.
                if (!item) return (api: T) => api;
                const expectedName = this.#platform
                    .basename(filename, this.#platform.extname(filename))
                    .match(prefixRE)?.[1];
                const itemName = this._validateAndSetHandlerName(item, filename, expectedName);
                if (kind(item) === 'handler') {
                    this.#handlerFiles.set(filename, config);
                    return Object.defineProperty(
                        (api: T) => {
                            (api as Record<string, (...args: unknown[]) => unknown>)[itemName](
                                [item],
                                config.name + '.' + itemName,
                                this.#platform.relative('.', filename),
                            );
                            return api;
                        },
                        'name',
                        {value: itemName},
                    );
                } else {
                    this.#layerFiles.set(filename, config);
                    return Object.defineProperty(
                        (api: T) => {
                            // A declared vocabulary is routed by *what it is*, not by the file it is
                            // written in. `lukaot/error.ts` is a vocabulary and the folder's `error.ts`
                            // is an error map, so keying off the file name alone handed the declaration
                            // to the error factory, which read its `signal` member as an error type and
                            // demanded a message for it (`@@T-717`).
                            const route = kind(item) === 'vocabulary' ? 'vocabulary' : itemName;
                            (api as Record<string, (...args: unknown[]) => unknown>)[route](
                                typeof item === 'function' &&
                                    !['adapter', 'orchestrator'].includes(kind(item))
                                    ? item(api)
                                    : item,
                                config.name + '.' + itemName,
                                this.#platform.relative('.', filename),
                            );
                            return api;
                        },
                        'name',
                        {value: itemName},
                    );
                }
            }
        }
        return (api: T) => api;
    }
 
    /**
     * In-process config reload pipeline:
     *  1. Ask ConfigRuntime to reload and compute the diff
     *  2. Emit a structured log event with the diff scope
     *  3. For each affected port: call configChanged if present, else stop+start
     *  4. Trigger test re-run
     */
    private async _reloadConfig(registry: IRegistry, configOverride: object): Promise<void> {
        if (!this.#configRuntime) {
            // No ConfigRuntime attached — nothing to do (graceful degradation)
            this.signal?.frameworkConfigDetached?.();
            return;
        }

        const prev = this.#configRuntime.rawSnapshot;
        const diff: ConfigDiff = await this.#configRuntime.reload();

        this.signal?.frameworkConfigReloaded?.({changed: Array.from(diff.keys())});

        if (diff.size === 0) return;

        const affected = affectedNamespaces(diff, registry.ports.keys());
        const next = this.#configRuntime.snapshot;

        let reloaded = 0;
        await withProgress(
            this.log,
            'reload config',
            (async () => {
                await applyConfigReload(
                    registry as unknown as IReloadRegistry,
                    affected,
                    diff,
                    next,
                    prev,
                    configOverride,
                    error => this.signal?.frameworkConfigReloadFailed?.({error}),
                    done => {
                        reloaded = done;
                    },
                );
            })(),
            {getProgress: () => ({done: reloaded, total: affected.size})},
        );

        this.#emit.dispatchEvent(new Event('test'));
    }
 
    /**
     * Common reload unit: re-import a changed file, re-wrap via layerProxy,
     * replace in registry, and signal tests.
     *
     * This unifies the three reload paths (layer file, single handler file,
     * handler folder) into a single abstraction.
     */
    private async _reloadUnit(
        registry: IRegistry,
        configOverride: object,
        filename: string,
    ): Promise<void> {
        type LayerResult = {
            result: Record<string, {methods: unknown[]; source?: string; port?: unknown}>;
        };
        type ModuleConfig = Parameters<typeof layerProxy>[4];
        // Path 1: Layer file changed — recreate and restart the port
        const layerConfig = this.#layerFiles.get(filename);
        if (layerConfig) {
            const id = this.#platform.basename(filename, this.#platform.extname(filename));
            const proxy = layerProxy(
                this.#error,
                this.#objectSchema,
                this.#apiSchema,
                this.#port,
                layerConfig as unknown as ModuleConfig,
            );
            const loadFn = (await this.load(layerConfig, false, true, filename)) as (
                api: LayerResult,
            ) => LayerResult;
            const item = loadFn(proxy as unknown as LayerResult).result[id];
            registry.ports.set(layerConfig.name + '.' + id, item.port as IAdapterRegistry);
            const port = await registry.createPort(layerConfig.name + '.' + id);
            if (!port) return;
            await port.start(configOverride);
            await port.ready();
            await registry.connected();
            this.#emit.dispatchEvent(new Event('test'));
            return;
        }

        // Path 2: Config file changed
        if (this.#config.configs.includes(filename)) {
            await this._reloadConfig(registry, configOverride);
            return;
        }

        // Path 3a: Single handler file changed
        let config = this.#handlerFiles.get(filename);
        if (config) {
            const importProxyCallback = await this.load(config, false, true, filename);
            const name = importProxyCallback.name;
            const cbResult = (importProxyCallback as unknown as (api: LayerResult) => LayerResult)(
                layerProxy(
                    this.#error,
                    this.#objectSchema,
                    this.#apiSchema,
                    this.#port,
                    config as unknown as ModuleConfig,
                ) as unknown as LayerResult,
            );
            await registry.replaceHandlers(
                config.name + '.' + name,
                cbResult.result[name].methods as Handlers,
            );
        } else {
            // Path 3b: Handler folder changed — reload entire folder
            const dir = this.#platform.dirname(filename);
            config = this.#handlerFolders.get(dir);
            if (config) {
                const handlers = (await this._loadHandlers(true, config, dir))(
                    layerProxy(
                        this.#error,
                        this.#objectSchema,
                        this.#apiSchema,
                        this.#port,
                        config as unknown as ModuleConfig,
                    ) as unknown as LayerResult,
                ) as unknown as LayerResult;
                await registry.replaceHandlers(
                    config.name + '.' + this.#platform.basename(dir),
                    handlers.result[this.#platform.basename(dir)].methods as Handlers,
                );
                if (handlers.result[this.#platform.basename(dir) + '.validation'])
                    await registry.replaceHandlers(
                        config.name + '.' + this.#platform.basename(dir) + '.validation',
                        handlers.result[this.#platform.basename(dir) + '.validation']
                            .methods as Handlers,
                    );
            }
        }
        await registry.connected();
        this.#emit.dispatchEvent(new Event('test'));
    }
 
    private _watch(registry: IRegistry, configOverride: object): void {
        const fsWatcher = this.#platform.watch?.(
            Array.from(this.#handlerFolders.keys())
                .map(folder => [
                    `${folder}/*.ts`,
                    `${folder}/*.yaml`,
                    `${folder}/*.sql`,
                    `${folder}/*.html`,
                ])
                .flat()
                .concat(Array.from(this.#handlerFiles.keys()))
                .concat(Array.from(this.#layerFiles.keys()))
                .concat(this.#config.configs),
            {
                cwd: '.',
                ignoreInitial: true,
                ignored: ['.git/**', 'node_modules/**', 'dist/**', ...(this.#config.ignored || [])],
            },
        );
        if (!fsWatcher) return;
        this.#watchers.push(fsWatcher);
        fsWatcher.on('error', error => this.signal?.frameworkWatchFailed?.({error}));
        fsWatcher.on('all', async (event, filename) => {
            try {
                filename = this.#platform.resolve(filename);
                this.signal?.frameworkWatchFileChanged?.({file: filename, event});
                await this._reloadUnit(registry, configOverride, filename);
            } catch (error) {
                this.signal?.frameworkWatchReloadFailed?.({file: filename, error});
            }
        });
    }
 
    public async start(
        registry: IRegistry,
        remote: IRemote,
        configOverride: object,
    ): Promise<void> {
        if (this.#config.enabled)
            this.signal?.frameworkWatchStarted?.({
                folders: Array.from(this.#handlerFolders.keys())
                    .concat(Array.from(this.#handlerFiles.keys()))
                    .concat(Array.from(this.#layerFiles.keys()))
                    .map(folder => this.#platform.relative('.', folder)),
            });
        if (this.#config.test) {
            this.#emit.addEventListener('test', async (event: Event) => {
                const {done, test} = ((event as CustomEvent).detail ?? {}) as {
                    done?: (error?: unknown) => void;
                    test?: unknown;
                };
                try {
                    const groups = ([] as string[]).concat(this.#config.test);
                    let executed = 0;
                    await withProgress(
                        this.log,
                        'run test groups',
                        Promise.all(
                            groups.map(async method => {
                                // Nothing above a test group minted a flow, so each group is
                                // an entry of its own. The groups run in parallel, so one
                                // flow for the whole run would interleave unrelated
                                // scenarios into a single diagram; a flow per group gives
                                // one scenario per flow, which is what there is to draw.
                                //
                                // The flow wraps the *execution*, not just the dispatch: a
                                // group answers with its steps and they run afterwards, so a
                                // flow that ended with the dispatch covered nothing but the
                                // call that built the scenario - the calls the scenario made
                                // were then made in no flow at all, and the observed flow the
                                // run was supposed to leave behind never existed.
                                const meta: IMeta = {mtid: 'event', method};
                                // The chain is built per group because it carries the
                                // group's wire name: Allure labels come from it, and the
                                // result's own name is the group's display name, which is
                                // set on the steps just below.
                                const chain = await (
                                    await import('./chain.ts')
                                ).default(test as ITestContext, this.log, {
                                    method,
                                    allure: this.#config.allure,
                                    // The Allure integration writes files, which a browser
                                    // platform has nowhere to do: the platform is handed over
                                    // so the chain can explain the report a browser run asked
                                    // for and cannot have, instead of failing to import its
                                    // way to the same end once per group.
                                    platform: this.#platform.platform,
                                });
                                await runInFlow(meta, method, async () => {
                                    const steps = await remote.remote(method)({}, meta);
                                    if (Array.isArray(steps) && !('name' in steps)) {
                                        Object.defineProperty(steps, 'name', {
                                            value: groupName(method),
                                            configurable: true,
                                        });
                                    }
                                    // The group's display name is also the flow's *phase*: a
                                    // sequence that runs a whole scenario reads as one band, and
                                    // the band is what tells a reader which scenario it is.
                                    const named =
                                        typeof steps === 'object' && steps !== null
                                            ? (steps as {name?: unknown})
                                            : undefined;
                                    const phase =
                                        typeof named?.name === 'string'
                                            ? named.name
                                            : groupName(method);
                                    await withStep(phase, () =>
                                        chain(steps as Parameters<typeof chain>[0]),
                                    );
                                });
                                executed += 1;
                            }),
                        ),
                        {getProgress: () => ({done: executed, total: groups.length})},
                    );
                } catch (error) {
                    this.signal?.frameworkTestGroupFailed?.({error});
                    done?.(error);
                    return;
                } finally {
                    // The results directory belongs to the run, not to any one group,
                    // so the session closes once every group has reported. The chain is
                    // imported here rather than at the top of the file so that a
                    // platform which never runs a group never links it.
                    await (await import('./chain.ts'))
                        .endAllureSession()
                        .catch(error => this.signal?.frameworkAllureSessionFailed?.({error}));
                }
                done?.();
            });
        }
        if (this.#config.enabled) this._watch(registry, configOverride);
 
        await registry.connected();
    }
 
    public async test(framework: unknown): Promise<void> {
        // `test()` settles only when the `start()`-registered listener calls `done`, and
        // that listener is registered only when test groups are declared. Waiting for it
        // unconditionally hangs the whole run with no output at all — a silent wait, which
        // is exactly what a suite that loads a platform without test groups (a browser
        // platform in a tap run, say) used to get. Report it and return: nothing to run is
        // not an error, it just has to be said out loud.
        const groups = ([] as string[]).concat(this.#config.test ?? []);
        if (groups.length === 0) {
            this.signal?.frameworkWatchNoTests?.();
            return;
        }
        return new Promise<void>((resolve, reject) => {
            // this.#emit.emit('test', error => (error ? reject(error) : resolve()), framework);
            this.#emit.dispatchEvent(
                new CustomEvent('test', {
                    detail: {
                        done: (error?: unknown) => (error ? reject(error) : resolve()),
                        test: framework,
                    },
                }),
            );
        });
    }
 
    public async stop(): Promise<void> {
        while (this.#watchers.length) {
            const watcher = this.#watchers.pop();
            await watcher?.close();
        }
    }
}