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

70.5% Statements 576/817
68.09% Branches 111/163
69.38% Functions 34/49
70.5% Lines 576/817

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 8181x 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 2144x 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 9x 11x 4x 4x 4x 11x 9x 5x 5x 1x 1x 1x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 174x 174x 174x 174x 174x 35x 132x 132x 132x 35x 35x 35x 35x 35x 35x 35x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 35x 174x 35x 35x 35x 35x 35x 1x 1x 1x 35x 35x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 58x 58x 58x 58x   6x 108x 108x 108x 6x 6x 6x 318x 318x 318x 6x 6x 6x 6x 6x 6x     6x 6x 6x 6x 6x 6x 6x 6x 6x 554x 554x 554x 554x 554x 554x 554x 554x     6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x         6x 6x 6x                                                                             1x 1x 481x 481x 481x 481x 481x 481x 481x 481x 481x 481x 481x 481x     481x 481x 481x 481x 481x 481x 481x 481x 481x 481x     96x 96x 96x 96x 96x 96x 96x 96x   96x                     96x 96x 96x 96x 96x       96x 1x         1952x 1920x 1462x 1462x 1461x 1461x                                                                                                       481x 481x 481x 24x 24x 24x 52x 52x 24x 24x 24x 24x 481x 481x 481x 36x 36x 36x 481x 481x 481x       481x 481x 481x         481x 481x 347x 347x 347x 481x 481x 481x       1163x 1163x 1163x 1163x 1163x 1163x 481x 481x 481x   481x 481x 481x 1163x 682x 682x 682x 682x 682x 679x 612x 682x 583x 583x   583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 554x 554x 583x 583x 66x 66x 66x 66x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 583x 552x 552x 552x 552x 552x 532x   552x 552x 552x 552x 552x 552x 552x 552x 552x 552x 583x 682x 99x 99x 66x 66x 66x 66x 66x 66x 66x 66x 66x                                                     66x 66x               24x 24x 24x       24x 24x               24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x                     132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 24x 24x 24x 24x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 102x 102x 102x 102x 102x 102x 102x   102x 102x 102x 102x 102x 102x 102x 102x 102x 102x 102x 102x 102x 102x 96x 96x 96x 96x 96x 96x 96x 102x 102x 102x 102x 102x                                                   96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x     6x               1x 1x 24x 24x 24x 24x 24x 24x                 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x           53x 53x 21x 21x 21x 21x 21x 21x 21x 21x 53x 53x 53x 21x 21x 21x 21x 21x         21x 21x 24x 24x 24x 24x 24x 1x 1x 23x 23x 23x 23x 23x 23x 23x 23x 2x 2x 2x 2x 2x 2x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 1x 1x 32x       32x 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';
import {runInFlow} from './semanticContext.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);
 
const prefixRE: RegExp = /(?:\d+-)?(.*)/;
 
interface IConfig {
    enabled: boolean;
    test: string;
    ignored: string[];
    configs: string[];
    logLevel: Parameters<ILog['logger']>[0];
}
 
// ---------------------------------------------------------------------------
// 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;
}
 
export default class Watch extends Internal implements IWatch {
    #config: IConfig = {
        enabled: false,
        test: '',
        ignored: [],
        configs: [],
        logLevel: 'debug',
    };
 
    #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) &&
                    !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) {
                this.log?.error?.(
                    'Error loading ' +
                        filename +
                        ' ; probably a generic source code was put in a handler group folder',
                );
                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)) &&
                !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) => {
                            (api as Record<string, (...args: unknown[]) => unknown>)[itemName](
                                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.log?.warn?.({
                $meta: {mtid: 'event', method: 'watch.config.reload'},
                message: 'ConfigRuntime not attached; config change ignored',
            });
            return;
        }

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

        this.log?.info?.({
            $meta: {mtid: 'event', method: 'watch.config.reload'},
            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 () => {
                for (const portId of affected) {
                    const portInstance = await registry.getPort(portId);
                    if (portInstance) {
                        if (typeof portInstance['configChanged'] === 'function') {
                            // Adapter supports the configChanged hook — zero-downtime update
                            try {
                                await portInstance['configChanged'](diff, next, prev);
                            } catch (error) {
                                this.log?.error?.(error);
                            }
                        } else {
                            // Fallback: stop and restart the port with the current configOverride
                            await portInstance.stop();
                            const fresh = await registry.createPort(portId);
                            if (fresh) {
                                await fresh.start(configOverride);
                                await fresh.ready();
                            }
                        }
                    }
                    reloaded += 1;
                }
            })(),
            {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.log?.error?.(error));
        fsWatcher.on('all', async (event, filename) => {
            try {
                filename = this.#platform.resolve(filename);
                this.log?.info?.(
                    {
                        $meta: {mtid: 'event', method: `watch.reload.${event}`},
                    },
                    filename,
                );
                await this._reloadUnit(registry, configOverride, filename);
            } catch (error) {
                this.log?.error?.(error);
            }
        });
    }
 
    public async start(
        registry: IRegistry,
        remote: IRemote,
        configOverride: object,
    ): Promise<void> {
        if (this.#config.enabled)
            this.log?.debug?.({
                $meta: {mtid: 'event', method: 'watch.start'},
                dir: 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 chain = await (
                        await import('./chain.ts')
                    ).default(test as ITestContext, this.log);
 
                    const steps = await Promise.all(
                        ([] as string[]).concat(this.#config.test).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.
                            const meta: IMeta = {mtid: 'event', method};
                            const result = await runInFlow(meta, method, () =>
                                remote.remote(method)({}, meta),
                            );
                            if (Array.isArray(result) && !('name' in result)) {
                                Object.defineProperty(result, 'name', {
                                    value: method.replace(/^test\./, '').replace(/\./g, ' '),
                                    configurable: true,
                                });
                            }
                            return result;
                        }),
                    );
                    let executed = 0;
                    await withProgress(
                        this.log,
                        'run test groups',
                        (async () => {
                            await Promise.all(
                                steps.map(async step => {
                                    await chain(step as Parameters<typeof chain>[0]);
                                    executed += 1;
                                }),
                            );
                        })(),
                        {getProgress: () => ({done: executed, total: steps.length})},
                    );
                } catch (error) {
                    this.log?.error?.(error);
                    done?.(error);
                    return;
                }
                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.log?.info?.(
                {$meta: {mtid: 'event', method: 'watch.test.none'}},
                'no test groups configured on this platform; nothing to run',
            );
            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();
        }
    }
}