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 | 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 11x 11x 11x 11x 11x 11x 11x 459x 172x 459x 172x 459x 287x 287x 287x 172x 172x 172x 172x 11x 11x 11x 11x 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 63x 63x 63x 63x 63x 63x 63x 63x 1197x 1160x 1197x 49x 1197x 1x 1x 1x 1x 1197x 33x 33x 1197x 63x 63x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 1x 1x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 11x 11x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 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 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 11x 172x 172x 172x 172x 11x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 34x 34x 34x 34x 63x 63x 63x 63x 63x 355x 355x 355x 355x 355x 355x 273x 107x 107x 107x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 107x 92x 92x 92x 269x 269x 269x 269x 269x 269x 269x 92x 92x 92x 92x 92x 24x 24x 24x 24x 24x 24x 24x 24x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 24x 92x 107x 273x 273x 273x 473x 473x 473x 473x 473x 473x 473x 129x 129x 129x 129x 11x 11x 11x 11x 11x 11x 129x 473x 344x 344x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 344x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 473x 273x 355x 63x 63x 63x 11x 11x 11x 63x 63x 63x 63x | import {
Internal,
browser as browserFactory,
kind,
orchestrator,
server as serverFactory,
type IApiSchema,
type IConfigRuntime,
type IErrorFactory,
type ILog,
type ILogger,
type IModuleConfig,
type IPlatformApi,
type IRegistry,
type Kind,
type Kinds,
type SolutionFactory,
} from '@feasibleone/blong/types';
import {Type, type TSchema} from 'typebox';
import merge from 'ut-function.merge';
import {methodParts} from './lib.ts';
import ConfigRuntime from './ConfigRuntime.ts';
import layerProxy from './layerProxy.ts';
import RealmImpl, {type IRealm} from './Realm.ts';
import type {IWatch} from './Watch.ts';
const LAYER_FILE = 'layer' as const;
/**
* An infrastructure item declaration with explicit dependencies.
* Items are topologically sorted before instantiation so that each item's
* dependencies are guaranteed to be available when it is created.
*/
interface InfraItem {
/** Infrastructure item name (becomes the key in the `api` object). */
name: string;
/** Names of other infrastructure items this one depends on. */
deps: string[];
/** Factory that returns the module (via dynamic import). */
load: () => Promise<unknown>;
}
/**
* Topological sort of infrastructure items by their declared dependencies.
* Throws if a cycle is detected.
*/
function topoSort(items: InfraItem[]): InfraItem[] {
const byName = new Map(items.map(item => [item.name, item]));
const sorted: InfraItem[] = [];
const visited = new Set<string>();
const visiting = new Set<string>();
function visit(item: InfraItem): void {
if (visited.has(item.name)) return;
if (visiting.has(item.name))
throw new Error(`Circular infrastructure dependency: ${item.name}`);
visiting.add(item.name);
for (const dep of item.deps) {
const depItem = byName.get(dep);
if (depItem) visit(depItem);
}
visiting.delete(item.name);
visited.add(item.name);
sorted.push(item);
}
for (const item of items) visit(item);
return sorted;
}
/** Well-known layer folder names and their default activation per kind */
const WELL_KNOWN_LAYERS: Record<string, {server?: object; browser?: object}> = {
api: {server: {default: true}, browser: {default: true}},
init: {server: {default: true}, browser: {default: true}},
'server/init': {server: {default: true}},
'server/api': {server: {integration: true}},
'browser/init': {browser: {default: true}},
'browser/api': {browser: {integration: true}},
error: {server: {integration: true}},
sim: {server: {integration: true}},
adapter: {server: {integration: true}},
orchestrator: {server: {integration: true}},
gateway: {server: {integration: true}},
browser: {server: {integration: true}},
backend: {browser: {integration: true}},
component: {browser: {integration: true}},
action: {browser: {integration: true}},
actions: {browser: {integration: true}},
test: {browser: {integration: true}},
'server/test': {server: {integration: true}},
'browser/test': {browser: {integration: true}},
};
/**
* Discover layer folders in a realm directory that are not already listed as children.
* Returns a map of folderName -> activation config.
*/
async function discoverLayerFolders(
{existsSync, join}: IPlatformApi,
base: string,
kind_: 'server' | 'browser',
explicitChildren: Set<string>,
): Promise<[string, object][]> {
const result: [string, object][] = [];
for (const name of Object.keys(WELL_KNOWN_LAYERS)) {
if (explicitChildren.has(name)) continue;
const layerFolder = join(base, name);
if (!existsSync(layerFolder)) continue;
const layerFile = join(base, name, `${LAYER_FILE}.${kind_}.ts`);
if (existsSync(layerFile)) {
// Read activation from layer.server.ts / layer.browser.ts
const mod = await import(layerFile).catch(() => null);
const activation = mod?.default ?? {default: true};
result.push([name, activation]);
} else if (name in WELL_KNOWN_LAYERS && WELL_KNOWN_LAYERS[name][kind_]) {
result.push([name, WELL_KNOWN_LAYERS[name][kind_]]);
}
}
return result;
}
/**
* Discover test method names from a realm's test/test/ folder.
* Imports each handler file with a null proxy to extract method names.
*/
async function discoverRealmTestMethods(
{existsSync, readdir, join, basename, extname}: IPlatformApi,
base: string,
): Promise<string[]> {
const testDir = join(base, 'test', 'test');
if (!existsSync(testDir)) return [];
const nullFn: unknown = new Proxy(
function () {
return nullFn;
} as unknown as object,
{
get(_, key) {
if (typeof key === 'symbol') return undefined;
return nullFn;
},
apply() {
return nullFn;
},
},
);
const files = (await readdir(testDir)).filter(
f => f.isFile() && /\.(ts|mts|js|mjs)$/i.test(f.name) && !f.name.startsWith('~'),
);
const methods: string[] = [];
for (const file of files) {
const filePath = join(testDir, file.name);
try {
const mod = await import(filePath);
const fn = mod?.default;
if (typeof fn === 'function') {
const result = fn({
lib: nullFn,
handler: nullFn,
errors: nullFn,
config: {},
remote: nullFn,
local: nullFn,
});
if (result && typeof result === 'object' && !Array.isArray(result)) {
for (const key of Object.keys(result)) methods.push(methodParts(key));
} else {
methods.push(methodParts(basename(file.name, extname(file.name))));
}
} else {
methods.push(methodParts(basename(file.name, extname(file.name))));
}
} catch {
methods.push(methodParts(basename(file.name, extname(file.name))));
}
}
return methods;
}
const System: symbol = Symbol('system');
export function system(original: {[key: symbol]: boolean}): void {
original[System] = true;
}
interface IConstructor {
new (config?: object, api?: object): object;
}
function activeConfigs<T extends TSchema>(
mod: IModuleConfig<T>,
configNames: string[],
platformConfigs: string[],
): (boolean | object)[] {
return (
(['default'] as string[])
.concat(configNames)
.concat(platformConfigs)
.map(name => (mod.config as unknown as Record<string, unknown>)?.[name])
.filter(Boolean) as (boolean | object)[]
).concat({pkg: mod.pkg, children: mod.children, url: mod.url});
}
export default async function loadRealm<T extends TSchema>(
platformApi: IPlatformApi,
def: SolutionFactory<T> & {[symbol: Kind]: Kinds},
name: string,
parentConfig: object | string,
configNames: string[],
api?: {
platform: IPlatformApi;
watch?: IWatch;
apiSchema?: IApiSchema;
error?: IErrorFactory;
port?: () => void;
log?: ILog;
registry?: IRegistry;
configRuntime?: IConfigRuntime;
} & {
[key: string]: {init?: () => Promise<unknown>};
},
rootKind?: 'server' | 'browser',
): Promise<IRegistry> {
const defKind = kind(def);
if (!rootKind) {
if (defKind === 'server' || defKind === 'browser') rootKind = defKind;
else if (defKind === 'solution') {
// Realm passed directly as root — wrap in a minimal suite for isolated testing
const realmMod = await def({type: Type});
const realmUrl = realmMod.url as string;
const realmFilePath = realmUrl.startsWith('file://') ? realmUrl.slice(7) : realmUrl;
const realmBase = platformApi.dirname(realmFilePath);
const realmFileName = platformApi.basename(realmFilePath);
const realmName = platformApi.basename(realmBase);
let pkg: {name: string; version: string} = realmMod.pkg || {
name: realmName,
version: '0.0.0',
};
if (platformApi.createRequire) {
try {
pkg = platformApi.createRequire(realmUrl)('./package.json') as {
name: string;
version: string;
};
} catch {}
}
const testMethods = await discoverRealmTestMethods(platformApi, realmBase);
const realmChild = Object.defineProperty(
async function () {
return {default: def};
},
'name',
{value: realmName, configurable: true},
);
if (realmFileName.startsWith('browser')) {
// Browser realm — wrap in a minimal browser suite
const wrapper = browserFactory((() => ({
url: '',
pkg,
children: [realmChild],
config: {
default: {remote: {canSkipSocket: true}, [realmName]: {}},
integration: {watch: {test: testMethods}},
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
})) as () => any);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return loadRealm(platformApi, wrapper as any, name, parentConfig, configNames);
} else {
// Server realm — single platform if no browser.ts alongside, else two-platform server half
const hasBrowser = platformApi.existsSync(
platformApi.join(realmBase, 'browser.ts'),
);
const wrapper = serverFactory(() => ({
url: '',
pkg,
children: [realmChild],
config: {
default: {
rpcServer: {port: 0},
gateway: {port: hasBrowser ? 8080 : 0},
[realmName]: {},
},
integration: hasBrowser
? {default: {}} // browser side handles watch.test and canSkipSocket
: {
default: {},
remote: {canSkipSocket: true},
watch: {test: testMethods},
},
},
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return loadRealm(platformApi, wrapper as any, name, parentConfig, configNames);
}
} else {
throw new Error(`Root realm must be of kind "server" or "browser", got "${defKind}"`);
}
}
const mod = await def({type: Type});
if (!('pkg' in mod) && platformApi.platform === 'server')
mod.pkg = platformApi.createRequire?.(mod.url)('./package.json');
const mergedConfig: {
name: string;
pkg: {name: string; version: string};
children: unknown[];
url: string;
base: string;
server: {
load: {logLevel: Parameters<ILog['logger']>[0]};
realm: {logLevel: Parameters<ILog['logger']>[0]};
};
browser: {
load: {logLevel: Parameters<ILog['logger']>[0]};
realm: {logLevel: Parameters<ILog['logger']>[0]};
};
kopi?: {realm?: unknown};
watch?: {configs?: object};
configs?: object;
configNames: string[];
} & {
[key: string]: unknown;
} = {
name,
pkg: {name, version: '0.0.0'},
children: [],
url: '',
base: '',
server: {
load: {
logLevel: 'warn' as Parameters<ILog['logger']>[0],
},
realm: {
logLevel: 'warn' as Parameters<ILog['logger']>[0],
},
},
browser: {
load: {
logLevel: 'warn' as Parameters<ILog['logger']>[0],
},
realm: {
logLevel: 'warn' as Parameters<ILog['logger']>[0],
},
},
kopi: undefined,
watch: undefined as {configs?: object} | undefined,
configs: undefined,
configNames: [] as string[],
};
const loadedConfigs = [];
let items:
| IModuleConfig['children']
| {
path: string;
name: string;
isFile?: () => Promise<unknown>;
isDirectory?: Record<string, () => Promise<unknown>>;
}[] = [];
if (!api) {
api = {
platform: platformApi,
} as unknown as typeof api;
loadedConfigs.push({
watch: {},
log: {},
apiSchema: {},
error: {},
registry: {},
port: {},
codec: {},
adapter: {},
orchestrator: {},
remote: {},
local: {},
rpcServer: {},
gateway: {},
restFs: {},
systemDebug: {},
});
items = topoSort([
{
name: 'log',
deps: [],
load: () =>
rootKind === 'browser' && globalThis.window
? import('./BrowserLog.ts')
: import('./Log.ts'),
},
{
name: 'apiSchema',
deps: ['log'],
load: () => import('./ApiSchema.ts'),
},
{
name: 'port',
deps: ['log'],
load: () => import('./Port.ts'),
},
{
name: 'error',
deps: ['log'],
load: () => import('./ErrorFactory.ts'),
},
{
name: 'watch',
deps: ['log'],
load: () => import('./Watch.ts'),
},
{
name: 'local',
deps: ['log'],
load: () => import('./Local.ts'),
},
{
name: 'resolution',
deps: ['log'],
load: () => import('./ResolutionLocal.ts'),
},
...(rootKind === 'browser'
? [
{
name: 'remote',
deps: ['log', 'local'],
load: () => import('./Remote.ts'),
},
{
name: 'registry',
deps: ['log', 'error', 'remote', 'local', 'watch', 'apiSchema'],
load: () => import('./Registry.ts'),
},
{
name: 'codec',
deps: ['log'],
load: () => import('./codec/browser.ts'),
},
{
name: 'orchestrator',
deps: ['log'],
load: () => import('./orchestrator/index.ts'),
},
{
name: 'adapter',
deps: ['log'],
load: () => import('./adapter/browser.ts'),
},
]
: [
{
name: 'remote',
deps: ['log', 'local'],
load: () => import('./RpcClient.ts'),
},
{
name: 'rpcServer',
deps: ['log'],
load: () => import('./RpcServer.ts'),
},
{
name: 'gateway',
deps: ['log'],
load: () => import('./Gateway.ts'),
},
{
name: 'restFs',
deps: ['log', 'gateway'],
load: () => import('./RestFs.ts'),
},
{
name: 'systemDebug',
deps: ['log', 'gateway', 'registry', 'rpcServer'],
load: () => import('./SystemDebug.ts'),
},
{
name: 'registry',
deps: [
'log',
'error',
'remote',
'rpcServer',
'gateway',
'local',
'watch',
'apiSchema',
],
load: () => import('./Registry.ts'),
},
{
name: 'codec',
deps: ['log'],
load: () => import('./codec/server.ts'),
},
{
name: 'orchestrator',
deps: ['log'],
load: () => import('./orchestrator/index.ts'),
},
{
name: 'adapter',
deps: ['log'],
load: () => import('./adapter/server.ts'),
},
]),
]).map(({name, load}) => {
const fn = load;
Object.defineProperty(fn, 'name', {value: name});
return fn;
});
}
loadedConfigs.push(...activeConfigs(mod, configNames, platformApi.configs));
const {loadedConfig, configRuntime} = await platformApi.loadConfig(parentConfig);
if (loadedConfig) loadedConfigs.push(loadedConfig);
ConfigRuntime.mergeModuleConfig(mergedConfig, ...loadedConfigs);
mergedConfig.configNames = configNames;
let logger: ILogger | undefined = api?.log?.logger(
mergedConfig[rootKind === 'browser' ? 'browser' : 'server']?.load?.logLevel,
{
name,
context: `${defKind}`,
},
);
if (typeof parentConfig === 'string' && mergedConfig.watch)
mergedConfig.watch.configs = mergedConfig.configs;
// Auto-discover layer folders not already listed in mod.children
const base = mergedConfig.url.startsWith('file://')
? platformApi.dirname(mergedConfig.url.slice(7))
: platformApi.dirname(mergedConfig.url);
mergedConfig.base = base;
const children = Array.isArray(mod.children) ? mod.children : [];
const extraChildren: (
| string
| {
path: string;
name: string;
isFile?: () => Promise<unknown>;
isDirectory?: Record<string, () => Promise<unknown>>;
}
)[] = [];
if (base && platformApi.platform === 'server') {
const explicitChildren = new Set(
children.filter(c => typeof c === 'string').map(c => platformApi.basename(c as string)),
);
const discoveredFolders = await discoverLayerFolders(
platformApi,
base,
rootKind,
explicitChildren,
);
for (const [folderName, activation] of discoveredFolders) {
if (!(folderName in mergedConfig))
merge(mergedConfig, {[platformApi.basename(folderName)]: activation});
extraChildren.push(`./${folderName}`);
}
}
if (mod.children && !Array.isArray(mod.children)) {
const globFolders: Record<string, Record<string, () => Promise<unknown>>> = {};
Object.entries(mod.children)
.sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
.forEach(([path, value]) => {
const segments = path.split('/');
if (segments[0] === '.') segments.shift();
if (segments.length >= 2) {
if (segments.length === 2) {
extraChildren.push({
name: segments[0],
path,
isFile: value,
});
} else {
const target = (globFolders[`${segments[0]}/${segments[1]}`] ||= {});
target[segments.join('/')] = value;
}
}
});
Object.entries(globFolders).forEach(([path, isDirectory]) => {
extraChildren.push({
name: path.split('/')[0],
path,
isDirectory,
});
});
}
let realm: IRealm;
for (let item of items.concat(children).concat(extraChildren)) {
if (typeof item === 'string' && platformApi.platform !== 'server') continue;
const itemName = typeof item === 'string' ? platformApi.basename(item) : item.name;
const config: Record<string, unknown> = mergedConfig[itemName] as Record<string, unknown>;
logger?.debug?.(
{$meta: {mtid: 'event', method: config ? 'child.load' : 'child.skip'}},
typeof item === 'string' ? item : item.name + '()',
);
if (config) {
if (typeof item === 'string') {
switch (defKind) {
case 'server':
case 'browser': {
const folderPath = item;
const fileName = folderPath.startsWith('.')
? platformApi.join(base, folderPath, `${defKind}.ts`)
: folderPath;
item = async () => {
try {
const mod = await import(fileName);
return mod.default ?? mod;
} catch (error) {
if (
!['ERR_MODULE_NOT_FOUND', 'MODULE_NOT_FOUND'].includes(
(error as {code?: string}).code ?? '',
)
)
throw error;
if (mergedConfig?.kopi?.realm) {
let destUrl = import.meta.resolve(fileName);
destUrl = destUrl.startsWith('file://')
? platformApi.dirname(destUrl.slice(7))
: destUrl;
if (
!platformApi.existsSync(
platformApi.join(destUrl, 'package.json'),
)
) {
const {createRealm} = await import('./kopi.ts');
await createRealm(destUrl, logger);
const mod = await import(fileName);
return mod.default ?? mod;
}
}
}
};
break;
}
default:
const loaded: unknown[] = [];
for (const dirEntry of await platformApi.scan(base, item))
loaded.push(
await api!.watch?.load(
mergedConfig,
dirEntry.isDirectory(),
dirEntry.isFile(),
base,
item,
dirEntry.name.toString(),
),
);
// Auto-provision a testDispatch orchestrator when the test/ folder
// has no testDispatch.ts and no layer.server.ts.
if (itemName === 'test' && platformApi.platform === 'server' && base) {
const testDir = platformApi.join(base, item as string);
const hasTestDispatch = platformApi.existsSync(
platformApi.join(testDir, 'testDispatch.ts'),
);
const hasLayerServer = platformApi.existsSync(
platformApi.join(testDir, 'layer.server.ts'),
);
if (!hasTestDispatch && !hasLayerServer) {
const realmName = mergedConfig.name;
const syntheticOrchestrator = orchestrator(() => ({
extends: 'orchestrator.dispatch' as const,
activation: {
default: {},
integration: {
namespace: ['test'],
imports: [/\.test$/],
},
},
}));
Object.defineProperty(syntheticOrchestrator, 'name', {
value: 'testDispatch',
configurable: true,
});
loaded.push(
Object.defineProperty(
(api: unknown) => {
(
api as Record<
string,
(...args: unknown[]) => unknown
>
)['testDispatch'](
syntheticOrchestrator,
realmName + '.testDispatch',
'auto-provisioned',
);
return api;
},
'name',
{value: 'testDispatch'},
),
);
}
}
item = async () => loaded.filter(Boolean);
}
} else if (platformApi.platform === 'browser' && 'path' in item) {
const loaded: unknown[] = [];
loaded.push(
await api!.watch?.load(mergedConfig, item.isDirectory, item.isFile, item.path),
);
item = async () => loaded.filter(Boolean);
}
const loadedModules = await (item as () => Promise<unknown[]>)();
for (const module of Array.isArray(loadedModules) ? loadedModules : [loadedModules]) {
const item = await module;
const fn = (item as {default?: unknown})?.default ?? item;
if (
typeof fn === 'function' &&
(fn.prototype instanceof Internal ||
(fn as unknown as Record<symbol, unknown>)[System])
) {
api![itemName] = new (fn as IConstructor)(config, api);
await api![itemName].init?.();
if (itemName === 'log')
logger = api!.log?.logger(
mergedConfig[rootKind === 'browser' ? 'browser' : 'server']?.load
?.logLevel,
{
name,
context: `${defKind}`,
},
);
} else if (
['solution', 'server', 'browser'].includes(kind(fn as Record<symbol, Kinds>))
) {
realm ||= new RealmImpl(mergedConfig, api!, rootKind);
realm.addModule(
itemName,
await loadRealm(
platformApi,
fn as Parameters<typeof loadRealm>[1],
itemName,
{[platformApi.platform]: mergedConfig[platformApi.platform], ...config},
configNames,
api,
rootKind,
),
);
} else if (typeof fn === 'function') {
realm ||= new RealmImpl(mergedConfig, api!, rootKind);
realm.addLayer(
itemName,
fn(
layerProxy(
api?.error,
api?.apiSchema,
api?.port,
mergedConfig as unknown as Parameters<typeof layerProxy>[3],
api?.configRuntime,
),
).result,
);
}
}
}
}
// Wire ConfigRuntime into Watch so config-file changes trigger in-process
// reload via ConfigRuntime.reload() instead of restarting the process.
if (configRuntime) {
api!.configRuntime = configRuntime;
api!.watch?.setConfigRuntime?.(configRuntime);
}
realm ||= new RealmImpl(mergedConfig, api!, rootKind);
if (!api?.registry) throw new Error('Registry not found in loaded modules');
return api.registry;
}
|