@brud/kernel 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (286) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +63 -2
  3. package/dist/index.d.ts +15 -0
  4. package/dist/index.js +13 -0
  5. package/dist/serviceModules/events.d.ts +1 -0
  6. package/dist/serviceModules/events.js +1 -0
  7. package/dist/serviceModules/exposedApiRegistry.d.ts +1 -0
  8. package/dist/serviceModules/exposedApiRegistry.js +1 -0
  9. package/dist/serviceModules/identityRegistry.d.ts +1 -0
  10. package/dist/serviceModules/identityRegistry.js +1 -0
  11. package/dist/serviceModules/interception.d.ts +1 -0
  12. package/dist/serviceModules/interception.js +1 -0
  13. package/dist/serviceModules/parser.d.ts +1 -0
  14. package/dist/serviceModules/parser.js +1 -0
  15. package/dist/serviceModules/router.d.ts +1 -0
  16. package/dist/serviceModules/router.js +1 -0
  17. package/dist/serviceModules/wasmCage.d.ts +1 -0
  18. package/dist/serviceModules/wasmCage.js +1 -0
  19. package/dist/services/Events/contracts/IEventsService.d.ts +64 -0
  20. package/dist/services/Events/contracts/IEventsService.js +1 -0
  21. package/dist/services/Events/contracts/errors.d.ts +31 -0
  22. package/dist/services/Events/contracts/errors.js +40 -0
  23. package/dist/services/Events/contracts/index.d.ts +3 -0
  24. package/dist/services/Events/contracts/index.js +3 -0
  25. package/dist/services/Events/contracts/tokens.d.ts +2 -0
  26. package/dist/services/Events/contracts/tokens.js +2 -0
  27. package/dist/services/Events/descriptor/EventsDescriptor.d.ts +9 -0
  28. package/dist/services/Events/descriptor/EventsDescriptor.js +56 -0
  29. package/dist/services/Events/descriptor/tokens.d.ts +1 -0
  30. package/dist/services/Events/descriptor/tokens.js +1 -0
  31. package/dist/services/Events/index.d.ts +4 -0
  32. package/dist/services/Events/index.js +4 -0
  33. package/dist/services/Events/orchestrator/EventsService.d.ts +51 -0
  34. package/dist/services/Events/orchestrator/EventsService.js +339 -0
  35. package/dist/services/Events/orchestrator/index.d.ts +2 -0
  36. package/dist/services/Events/orchestrator/index.js +2 -0
  37. package/dist/services/Events/orchestrator/limits.d.ts +22 -0
  38. package/dist/services/Events/orchestrator/limits.js +33 -0
  39. package/dist/services/Events/serviceModule.d.ts +2 -0
  40. package/dist/services/Events/serviceModule.js +5 -0
  41. package/dist/services/ExposedApiRegistry/contracts/IExposedApiRegistry.d.ts +56 -0
  42. package/dist/services/ExposedApiRegistry/contracts/IExposedApiRegistry.js +1 -0
  43. package/dist/services/ExposedApiRegistry/contracts/errors.d.ts +132 -0
  44. package/dist/services/ExposedApiRegistry/contracts/errors.js +195 -0
  45. package/dist/services/ExposedApiRegistry/contracts/index.d.ts +9 -0
  46. package/dist/services/ExposedApiRegistry/contracts/index.js +4 -0
  47. package/dist/services/ExposedApiRegistry/contracts/policy.d.ts +90 -0
  48. package/dist/services/ExposedApiRegistry/contracts/policy.js +169 -0
  49. package/dist/services/ExposedApiRegistry/contracts/registrant.d.ts +37 -0
  50. package/dist/services/ExposedApiRegistry/contracts/registrant.js +36 -0
  51. package/dist/services/ExposedApiRegistry/contracts/types.d.ts +133 -0
  52. package/dist/services/ExposedApiRegistry/contracts/types.js +73 -0
  53. package/dist/services/ExposedApiRegistry/descriptor/ExposedApiRegistryDescriptor.d.ts +44 -0
  54. package/dist/services/ExposedApiRegistry/descriptor/ExposedApiRegistryDescriptor.js +58 -0
  55. package/dist/services/ExposedApiRegistry/descriptor/tokens.d.ts +8 -0
  56. package/dist/services/ExposedApiRegistry/descriptor/tokens.js +8 -0
  57. package/dist/services/ExposedApiRegistry/index.d.ts +6 -0
  58. package/dist/services/ExposedApiRegistry/index.js +5 -0
  59. package/dist/services/ExposedApiRegistry/orchestrator/ExposedApiRegistryService.d.ts +68 -0
  60. package/dist/services/ExposedApiRegistry/orchestrator/ExposedApiRegistryService.js +452 -0
  61. package/dist/services/ExposedApiRegistry/orchestrator/index.d.ts +2 -0
  62. package/dist/services/ExposedApiRegistry/orchestrator/index.js +1 -0
  63. package/dist/services/ExposedApiRegistry/serviceModule.d.ts +10 -0
  64. package/dist/services/ExposedApiRegistry/serviceModule.js +20 -0
  65. package/dist/services/ExposedApiRegistry/storage/protection.d.ts +21 -0
  66. package/dist/services/ExposedApiRegistry/storage/protection.js +35 -0
  67. package/dist/services/ExposedApiRegistry/storage/scopeRecord.d.ts +45 -0
  68. package/dist/services/ExposedApiRegistry/storage/scopeRecord.js +178 -0
  69. package/dist/services/IdentityRegistry/contracts/errors.d.ts +88 -0
  70. package/dist/services/IdentityRegistry/contracts/errors.js +128 -0
  71. package/dist/services/IdentityRegistry/contracts/index.d.ts +5 -0
  72. package/dist/services/IdentityRegistry/contracts/index.js +3 -0
  73. package/dist/services/IdentityRegistry/contracts/types.d.ts +77 -0
  74. package/dist/services/IdentityRegistry/contracts/types.js +18 -0
  75. package/dist/services/IdentityRegistry/descriptor/descriptor.d.ts +36 -0
  76. package/dist/services/IdentityRegistry/descriptor/descriptor.js +44 -0
  77. package/dist/services/IdentityRegistry/descriptor/tokens.d.ts +8 -0
  78. package/dist/services/IdentityRegistry/descriptor/tokens.js +8 -0
  79. package/dist/services/IdentityRegistry/index.d.ts +11 -0
  80. package/dist/services/IdentityRegistry/index.js +6 -0
  81. package/dist/services/IdentityRegistry/orchestrator/IdentityRegistryService.d.ts +47 -0
  82. package/dist/services/IdentityRegistry/orchestrator/IdentityRegistryService.js +240 -0
  83. package/dist/services/IdentityRegistry/serviceModule.d.ts +10 -0
  84. package/dist/services/IdentityRegistry/serviceModule.js +24 -0
  85. package/dist/services/IdentityRegistry/storage/registryDocument.d.ts +55 -0
  86. package/dist/services/IdentityRegistry/storage/registryDocument.js +235 -0
  87. package/dist/services/Interception/contracts/IInterceptionService.d.ts +155 -0
  88. package/dist/services/Interception/contracts/IInterceptionService.js +12 -0
  89. package/dist/services/Interception/contracts/errors.d.ts +26 -0
  90. package/dist/services/Interception/contracts/errors.js +35 -0
  91. package/dist/services/Interception/contracts/index.d.ts +3 -0
  92. package/dist/services/Interception/contracts/index.js +3 -0
  93. package/dist/services/Interception/contracts/tokens.d.ts +2 -0
  94. package/dist/services/Interception/contracts/tokens.js +2 -0
  95. package/dist/services/Interception/descriptor/InterceptionDescriptor.d.ts +9 -0
  96. package/dist/services/Interception/descriptor/InterceptionDescriptor.js +50 -0
  97. package/dist/services/Interception/descriptor/tokens.d.ts +1 -0
  98. package/dist/services/Interception/descriptor/tokens.js +1 -0
  99. package/dist/services/Interception/index.d.ts +4 -0
  100. package/dist/services/Interception/index.js +4 -0
  101. package/dist/services/Interception/orchestrator/InterceptionService.d.ts +40 -0
  102. package/dist/services/Interception/orchestrator/InterceptionService.js +343 -0
  103. package/dist/services/Interception/orchestrator/index.d.ts +1 -0
  104. package/dist/services/Interception/orchestrator/index.js +1 -0
  105. package/dist/services/Interception/serviceModule.d.ts +2 -0
  106. package/dist/services/Interception/serviceModule.js +5 -0
  107. package/dist/services/Parser/contracts/IParserService.d.ts +21 -0
  108. package/dist/services/Parser/contracts/IParserService.js +1 -0
  109. package/dist/services/Parser/contracts/errors.d.ts +25 -0
  110. package/dist/services/Parser/contracts/errors.js +33 -0
  111. package/dist/services/Parser/contracts/index.d.ts +4 -0
  112. package/dist/services/Parser/contracts/index.js +1 -0
  113. package/dist/services/Parser/contracts/types.d.ts +42 -0
  114. package/dist/services/Parser/contracts/types.js +1 -0
  115. package/dist/services/Parser/descriptor/ParserDescriptor.d.ts +23 -0
  116. package/dist/services/Parser/descriptor/ParserDescriptor.js +50 -0
  117. package/dist/services/Parser/descriptor/tokens.d.ts +8 -0
  118. package/dist/services/Parser/descriptor/tokens.js +8 -0
  119. package/dist/services/Parser/index.d.ts +8 -0
  120. package/dist/services/Parser/index.js +8 -0
  121. package/dist/services/Parser/orchestrator/ParserService.d.ts +20 -0
  122. package/dist/services/Parser/orchestrator/ParserService.js +105 -0
  123. package/dist/services/Parser/orchestrator/index.d.ts +1 -0
  124. package/dist/services/Parser/orchestrator/index.js +1 -0
  125. package/dist/services/Parser/parser/indexSynthesis.d.ts +11 -0
  126. package/dist/services/Parser/parser/indexSynthesis.js +13 -0
  127. package/dist/services/Parser/parser/parameters.d.ts +14 -0
  128. package/dist/services/Parser/parser/parameters.js +89 -0
  129. package/dist/services/Parser/parser/scanner.d.ts +48 -0
  130. package/dist/services/Parser/parser/scanner.js +156 -0
  131. package/dist/services/Parser/parser/syntax.d.ts +30 -0
  132. package/dist/services/Parser/parser/syntax.js +34 -0
  133. package/dist/services/Parser/serviceModule.d.ts +2 -0
  134. package/dist/services/Parser/serviceModule.js +5 -0
  135. package/dist/services/Router/bootOptions.d.ts +2 -0
  136. package/dist/services/Router/bootOptions.js +2 -0
  137. package/dist/services/Router/contracts/IRouterService.d.ts +43 -0
  138. package/dist/services/Router/contracts/IRouterService.js +1 -0
  139. package/dist/services/Router/contracts/caller.d.ts +6 -0
  140. package/dist/services/Router/contracts/caller.js +6 -0
  141. package/dist/services/Router/contracts/errors.d.ts +67 -0
  142. package/dist/services/Router/contracts/errors.js +90 -0
  143. package/dist/services/Router/contracts/index.d.ts +8 -0
  144. package/dist/services/Router/contracts/index.js +4 -0
  145. package/dist/services/Router/contracts/kind.d.ts +7 -0
  146. package/dist/services/Router/contracts/kind.js +10 -0
  147. package/dist/services/Router/contracts/registrant.d.ts +23 -0
  148. package/dist/services/Router/contracts/registrant.js +13 -0
  149. package/dist/services/Router/contracts/types.d.ts +110 -0
  150. package/dist/services/Router/contracts/types.js +1 -0
  151. package/dist/services/Router/descriptor/RouterDescriptor.d.ts +32 -0
  152. package/dist/services/Router/descriptor/RouterDescriptor.js +92 -0
  153. package/dist/services/Router/descriptor/tokens.d.ts +9 -0
  154. package/dist/services/Router/descriptor/tokens.js +9 -0
  155. package/dist/services/Router/index.d.ts +4 -0
  156. package/dist/services/Router/index.js +4 -0
  157. package/dist/services/Router/orchestrator/RouterService.d.ts +93 -0
  158. package/dist/services/Router/orchestrator/RouterService.js +457 -0
  159. package/dist/services/Router/orchestrator/index.d.ts +2 -0
  160. package/dist/services/Router/orchestrator/index.js +1 -0
  161. package/dist/services/Router/serviceModule.d.ts +4 -0
  162. package/dist/services/Router/serviceModule.js +22 -0
  163. package/dist/services/WasmCage/index.d.ts +7 -0
  164. package/dist/services/WasmCage/index.js +4 -0
  165. package/dist/services/WasmCage/scripts/prepin.d.ts +1 -0
  166. package/dist/services/WasmCage/scripts/prepin.js +38 -0
  167. package/dist/services/WasmCage/serviceModule.d.ts +12 -0
  168. package/dist/services/WasmCage/serviceModule.js +18 -0
  169. package/dist/services/WasmCage/src/caged.d.ts +121 -0
  170. package/dist/services/WasmCage/src/caged.js +460 -0
  171. package/dist/services/WasmCage/src/descriptor.d.ts +47 -0
  172. package/dist/services/WasmCage/src/descriptor.js +56 -0
  173. package/dist/services/WasmCage/src/native.d.ts +29 -0
  174. package/dist/services/WasmCage/src/native.js +66 -0
  175. package/dist/services/WasmCage/src/nativeDigests.d.ts +9 -0
  176. package/dist/services/WasmCage/src/nativeDigests.js +15 -0
  177. package/dist/services/WasmCage/src/package.d.ts +36 -0
  178. package/dist/services/WasmCage/src/package.js +122 -0
  179. package/dist/services/shared/canonicalJson.d.ts +29 -0
  180. package/dist/services/shared/canonicalJson.js +93 -0
  181. package/dist/services/shared/documentStore.d.ts +16 -0
  182. package/dist/services/shared/documentStore.js +98 -0
  183. package/dist/src/bootstrap/bootKernelInternal.d.ts +19 -0
  184. package/dist/src/bootstrap/bootKernelInternal.js +633 -0
  185. package/dist/src/bootstrap/bootTypes.d.ts +113 -0
  186. package/dist/src/bootstrap/bootTypes.js +1 -0
  187. package/dist/src/bootstrap/config/index.d.ts +3 -0
  188. package/dist/src/bootstrap/config/index.js +2 -0
  189. package/dist/src/bootstrap/config/integrity.d.ts +45 -0
  190. package/dist/src/bootstrap/config/integrity.js +92 -0
  191. package/dist/src/bootstrap/config/parse.d.ts +15 -0
  192. package/dist/src/bootstrap/config/parse.js +81 -0
  193. package/dist/src/bootstrap/config/pathWriteGuard.d.ts +20 -0
  194. package/dist/src/bootstrap/config/pathWriteGuard.js +349 -0
  195. package/dist/src/bootstrap/config/types.d.ts +41 -0
  196. package/dist/src/bootstrap/config/types.js +15 -0
  197. package/dist/src/bootstrap/hardcore.d.ts +212 -0
  198. package/dist/src/bootstrap/hardcore.js +312 -0
  199. package/dist/src/bootstrap/hardcoreServices.d.ts +10 -0
  200. package/dist/src/bootstrap/hardcoreServices.js +258 -0
  201. package/dist/src/bootstrap/index.d.ts +13 -0
  202. package/dist/src/bootstrap/index.js +7 -0
  203. package/dist/src/bootstrap/loaded.d.ts +30 -0
  204. package/dist/src/bootstrap/loaded.js +45 -0
  205. package/dist/src/bootstrap/packageRequirements.d.ts +26 -0
  206. package/dist/src/bootstrap/packageRequirements.js +52 -0
  207. package/dist/src/bootstrap/reload.d.ts +44 -0
  208. package/dist/src/bootstrap/reload.js +45 -0
  209. package/dist/src/bootstrap/seal.d.ts +32 -0
  210. package/dist/src/bootstrap/seal.js +101 -0
  211. package/dist/src/contracts/accessBroker.d.ts +53 -0
  212. package/dist/src/contracts/accessBroker.js +1 -0
  213. package/dist/src/contracts/brudOperation.d.ts +20 -0
  214. package/dist/src/contracts/brudOperation.js +20 -0
  215. package/dist/src/contracts/callChain.d.ts +161 -0
  216. package/dist/src/contracts/callChain.js +19 -0
  217. package/dist/src/contracts/capability.d.ts +26 -0
  218. package/dist/src/contracts/capability.js +26 -0
  219. package/dist/src/contracts/capabilitySet.d.ts +23 -0
  220. package/dist/src/contracts/capabilitySet.js +72 -0
  221. package/dist/src/contracts/container.d.ts +17 -0
  222. package/dist/src/contracts/container.js +8 -0
  223. package/dist/src/contracts/context.d.ts +19 -0
  224. package/dist/src/contracts/context.js +1 -0
  225. package/dist/src/contracts/contextContract.d.ts +132 -0
  226. package/dist/src/contracts/contextContract.js +274 -0
  227. package/dist/src/contracts/dispatchView.d.ts +21 -0
  228. package/dist/src/contracts/dispatchView.js +1 -0
  229. package/dist/src/contracts/handler.d.ts +21 -0
  230. package/dist/src/contracts/handler.js +1 -0
  231. package/dist/src/contracts/index.d.ts +26 -0
  232. package/dist/src/contracts/index.js +9 -0
  233. package/dist/src/contracts/kernel.d.ts +60 -0
  234. package/dist/src/contracts/kernel.js +1 -0
  235. package/dist/src/contracts/lifecycle.d.ts +59 -0
  236. package/dist/src/contracts/lifecycle.js +1 -0
  237. package/dist/src/contracts/manifest.d.ts +180 -0
  238. package/dist/src/contracts/manifest.js +334 -0
  239. package/dist/src/contracts/pipeline.d.ts +8 -0
  240. package/dist/src/contracts/pipeline.js +1 -0
  241. package/dist/src/contracts/policy.d.ts +75 -0
  242. package/dist/src/contracts/policy.js +77 -0
  243. package/dist/src/contracts/registry.d.ts +7 -0
  244. package/dist/src/contracts/registry.js +1 -0
  245. package/dist/src/contracts/serviceDescriptor.d.ts +67 -0
  246. package/dist/src/contracts/serviceDescriptor.js +1 -0
  247. package/dist/src/contracts/serviceToken.d.ts +36 -0
  248. package/dist/src/contracts/serviceToken.js +16 -0
  249. package/dist/src/engine/BrudKernel.d.ts +120 -0
  250. package/dist/src/engine/BrudKernel.js +395 -0
  251. package/dist/src/engine/ExecutionPipeline.d.ts +13 -0
  252. package/dist/src/engine/ExecutionPipeline.js +62 -0
  253. package/dist/src/engine/KernelAccessBroker.d.ts +47 -0
  254. package/dist/src/engine/KernelAccessBroker.js +107 -0
  255. package/dist/src/engine/KernelRegistry.d.ts +14 -0
  256. package/dist/src/engine/KernelRegistry.js +33 -0
  257. package/dist/src/engine/OperationRegistry.d.ts +9 -0
  258. package/dist/src/engine/OperationRegistry.js +18 -0
  259. package/dist/src/engine/ServiceContainer.d.ts +13 -0
  260. package/dist/src/engine/ServiceContainer.js +53 -0
  261. package/dist/src/engine/callChain.d.ts +68 -0
  262. package/dist/src/engine/callChain.js +175 -0
  263. package/dist/src/engine/dag.d.ts +2 -0
  264. package/dist/src/engine/dag.js +34 -0
  265. package/dist/src/engine/errors.d.ts +26 -0
  266. package/dist/src/engine/errors.js +52 -0
  267. package/dist/src/engine/index.d.ts +11 -0
  268. package/dist/src/engine/index.js +8 -0
  269. package/dist/src/engine/state.d.ts +1 -0
  270. package/dist/src/engine/state.js +1 -0
  271. package/dist/src/validation/jsonSchema/compile.d.ts +8 -0
  272. package/dist/src/validation/jsonSchema/compile.js +386 -0
  273. package/dist/src/validation/jsonSchema/index.d.ts +3 -0
  274. package/dist/src/validation/jsonSchema/index.js +2 -0
  275. package/dist/src/validation/jsonSchema/jsonValue.d.ts +29 -0
  276. package/dist/src/validation/jsonSchema/jsonValue.js +190 -0
  277. package/dist/src/validation/jsonSchema/pattern.d.ts +28 -0
  278. package/dist/src/validation/jsonSchema/pattern.js +155 -0
  279. package/dist/src/validation/jsonSchema/types.d.ts +71 -0
  280. package/dist/src/validation/jsonSchema/types.js +15 -0
  281. package/package.json +59 -4
  282. package/services/WasmCage/native/brud-wasm-cage.darwin-arm64.node +0 -0
  283. package/services/WasmCage/native/brud-wasm-cage.darwin-x64.node +0 -0
  284. package/services/WasmCage/native/brud-wasm-cage.linux-arm64-gnu.node +0 -0
  285. package/services/WasmCage/native/brud-wasm-cage.linux-x64-gnu.node +0 -0
  286. package/services/WasmCage/native/brud-wasm-cage.win32-x64-msvc.node +0 -0
@@ -0,0 +1,633 @@
1
+ import { createCapabilitySet } from '../contracts/capabilitySet.js';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { dirname, isAbsolute, relative as relativePath, resolve as resolvePath } from 'node:path';
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
+ import { ContextContract, ContextContractError, } from '../contracts/contextContract.js';
7
+ import { admitParticipantManifest } from '../contracts/manifest.js';
8
+ import { BrudKernel } from '../engine/BrudKernel.js';
9
+ import { LifecycleStateError } from '../engine/errors.js';
10
+ import { checkSeal } from './seal.js';
11
+ import { abandonment, culpritOf, LoadedParticipantFailure } from './loaded.js';
12
+ import { KernelReloadError, refuseFrozenChange } from './reload.js';
13
+ import { acceptConfigChange, protectConfigFile, recordConfigRead, releaseConfigProtection, verifyConfigIntegrity, } from './config/integrity.js';
14
+ import { lineOf, parseBrudConfig } from './config/parse.js';
15
+ import { PackageRequirementsError, readPackageRequirements } from './packageRequirements.js';
16
+ import { buildHardcoreBootEntries, invokeHardcoreBootHooks, verifyHardcoreServices, } from './hardcore.js';
17
+ import { HARDCORE_SERVICES } from './hardcoreServices.js';
18
+ import { BrudConfigError, } from './config/types.js';
19
+ /** Root the `kernel:` module prefix resolves from (`packages/kernel/`). */
20
+ const KERNEL_PACKAGE_ROOT = new URL('../../', import.meta.url);
21
+ /** Fallback diagnostic sink used when the host does not supply one. */
22
+ const DEFAULT_KERNEL_LOGGER = {
23
+ warn: (message, meta) => {
24
+ console.warn(message, meta ?? {});
25
+ },
26
+ };
27
+ /** Returns the boot-policy hook exported by a module, if any. */
28
+ function pinBootPoliciesHook(moduleValue) {
29
+ if (!isRecord(moduleValue) || typeof moduleValue.pinBootPolicies !== 'function') {
30
+ return undefined;
31
+ }
32
+ return moduleValue.pinBootPolicies;
33
+ }
34
+ /** Returns the boot-registrant hook exported by a module, if any. */
35
+ function registerBootRegistrantsHook(moduleValue) {
36
+ if (!isRecord(moduleValue) || typeof moduleValue.registerBootRegistrants !== 'function') {
37
+ return undefined;
38
+ }
39
+ return moduleValue.registerBootRegistrants;
40
+ }
41
+ /**
42
+ * Reads, validates, composes, and boots a kernel from `brud.config.json`.
43
+ *
44
+ * @param configPath - Path to the config file.
45
+ * @param options - Generic options bag and logger.
46
+ */
47
+ export async function bootKernel(configPath, options) {
48
+ return startTolerant(configPath, options, {
49
+ ...(options.options === undefined ? {} : { options: options.options }),
50
+ ...(options.logger === undefined ? {} : { logger: options.logger }),
51
+ }, undefined);
52
+ }
53
+ /**
54
+ * Builds a kernel whose config is composed lazily on the first `boot()`.
55
+ *
56
+ * The host supplies the config path explicitly; the kernel never chooses or
57
+ * discovers a config. Deferring module imports until boot keeps module
58
+ * instances in the ESM cache instead of loading a second copy through
59
+ * `require`.
60
+ */
61
+ export function createDeferredKernel(configPath, options) {
62
+ return assembleKernel(configPath, options, undefined).kernel;
63
+ }
64
+ /**
65
+ * Boots a kernel, leaving out loaded participants that cannot start.
66
+ *
67
+ * A loaded participant is any config entry not declared official. One that
68
+ * fails to load, to be admitted, or to start is left out and the boot is tried
69
+ * again without it, so a bad loaded participant never stops the kernel. A
70
+ * failure in a hardcore or composed participant still refuses the boot.
71
+ *
72
+ * A failure while composing names its loaded participants itself. A failure
73
+ * while booting is traced to the participant it names, or to the service that
74
+ * threw it. When it cannot be traced to a loaded participant, every loaded
75
+ * participant is left out once and the boot is tried again; if that fails
76
+ * too, the failure was in the build and is thrown.
77
+ *
78
+ * @param baseline - The booted config this one replaces, for a reload.
79
+ * @param beforeFirstBoot - Runs once, after the new composition is checked and
80
+ * before anything boots: a reload stops the running kernel here.
81
+ * @param wrap - Turns a failure after `beforeFirstBoot` into the error thrown.
82
+ */
83
+ async function startTolerant(configPath, options, bootOptions, baseline, beforeFirstBoot, wrap) {
84
+ const left = new Map();
85
+ let stopped = false;
86
+ let sweptAll = false;
87
+ for (;;) {
88
+ const attempt = assembleKernel(configPath, options, baseline, new Set(left.keys()));
89
+ let phase = 'compose';
90
+ try {
91
+ await attempt.validate(bootOptions);
92
+ if (!stopped) {
93
+ stopped = true;
94
+ try {
95
+ await beforeFirstBoot?.();
96
+ }
97
+ catch (error) {
98
+ attempt.abandon();
99
+ throw error;
100
+ }
101
+ }
102
+ phase = 'boot';
103
+ await attempt.kernel.boot(bootOptions);
104
+ }
105
+ catch (error) {
106
+ const fresh = blamedLoaded(attempt, error, phase, left, sweptAll);
107
+ if (fresh === undefined) {
108
+ throw stopped && wrap !== undefined ? wrap(error) : error;
109
+ }
110
+ sweptAll ||= fresh.swept;
111
+ for (const entry of fresh.entries) {
112
+ left.set(entry.path, entry);
113
+ }
114
+ continue;
115
+ }
116
+ attempt.setAbandoned([...left.values()]);
117
+ reportAbandoned(bootOptions.logger ?? options.logger ?? DEFAULT_KERNEL_LOGGER, left);
118
+ return attempt.kernel;
119
+ }
120
+ }
121
+ /** The loaded participants to leave out after a failed attempt, or `undefined` when the failure is not theirs. */
122
+ function blamedLoaded(attempt, error, phase, left, sweptAll) {
123
+ if (error instanceof LoadedParticipantFailure) {
124
+ const entries = error.participants.filter((entry) => !left.has(entry.path));
125
+ return entries.length === 0 ? undefined : { entries, swept: false };
126
+ }
127
+ if (phase === 'compose') {
128
+ return undefined;
129
+ }
130
+ const token = culpritOf(error);
131
+ const path = token === undefined ? undefined : attempt.loadedPathOf(token);
132
+ if (path !== undefined && !left.has(path)) {
133
+ return { entries: [abandonment(path, error, token)], swept: false };
134
+ }
135
+ if (sweptAll) {
136
+ return undefined;
137
+ }
138
+ const remaining = attempt.config().services.filter((entry) => entry.official !== true && !left.has(entry.path));
139
+ if (remaining.length === 0) {
140
+ return undefined;
141
+ }
142
+ const why = error instanceof Error ? error.message : String(error);
143
+ return {
144
+ swept: true,
145
+ entries: remaining.map((entry) => ({
146
+ path: entry.path,
147
+ reason: `the kernel could not start with the loaded participants and the cause could not be traced to one of them (${why})`,
148
+ })),
149
+ };
150
+ }
151
+ function reportAbandoned(logger, left) {
152
+ if (left.size === 0) {
153
+ return;
154
+ }
155
+ const lines = [...left.values()].map((entry) => `${entry.path}: ${entry.reason}`);
156
+ logger.warn(`Left out ${String(left.size)} loaded participant(s); the kernel started without them:\n${lines.join('\n')}`, {
157
+ abandoned: [...left.values()],
158
+ });
159
+ }
160
+ /**
161
+ * Builds a kernel and the handles a reload needs.
162
+ *
163
+ * @param baseline - The booted config this one replaces, when it is a reload's
164
+ * successor: its read supersedes the recorded config digest, and its frozen
165
+ * part must match the baseline.
166
+ */
167
+ function assembleKernel(configPath, options, baseline, skip = new Set()) {
168
+ let lastBootOptions = {};
169
+ let abandonedList = [];
170
+ const loadedTokens = new Map();
171
+ let loadedServices = [];
172
+ let serviceContext;
173
+ let hardcoreBootEntries = [];
174
+ let hardcorePackageHashes = new Map();
175
+ let composedConfig = { services: [] };
176
+ let activeServiceOwner = 'brud.kernel.composition';
177
+ const contextContract = new ContextContract();
178
+ function declareContextFields(scopeOrDeclaration, fields) {
179
+ contextContract.declare(activeServiceOwner, scopeOrDeclaration, fields);
180
+ }
181
+ const kernel = new BrudKernel({
182
+ contextContract,
183
+ hardcoreTokens: HARDCORE_SERVICES.map((service) => service.token),
184
+ bootHardcore: (instances, authority) => {
185
+ const identities = invokeHardcoreBootHooks(HARDCORE_SERVICES, instances, hardcorePackageHashes, hardcoreBootEntries, composedConfig, authority);
186
+ // Each participant's caller is assigned here, by the kernel: its issued
187
+ // identity, its official status from the identity-to-official mapping,
188
+ // and the capabilities its manifest requests.
189
+ return hardcoreBootEntries.map((entry) => {
190
+ const caller = Object.freeze({
191
+ callerClass: 'participant',
192
+ identity: identities.get(entry.token) ?? null,
193
+ official: entry.official,
194
+ capabilities: createCapabilitySet(entry.manifest.capabilities),
195
+ ...(entry.parentIdentity === undefined
196
+ ? {}
197
+ : { parentIdentity: entry.parentIdentity }),
198
+ });
199
+ return { tokenId: entry.token, caller };
200
+ });
201
+ },
202
+ bootPinner: async (instances) => {
203
+ const context = serviceContext;
204
+ if (context === undefined) {
205
+ return;
206
+ }
207
+ for (const loaded of loadedServices) {
208
+ const pin = pinBootPoliciesHook(loaded.module);
209
+ if (pin !== undefined) {
210
+ activeServiceOwner = `${String(loaded.index)}:${loaded.entry.path}`;
211
+ await pin(context, instances);
212
+ }
213
+ }
214
+ for (const loaded of loadedServices) {
215
+ const registrant = registerBootRegistrantsHook(loaded.module);
216
+ if (registrant !== undefined) {
217
+ activeServiceOwner = `${String(loaded.index)}:${loaded.entry.path}`;
218
+ registrant(context, instances);
219
+ }
220
+ }
221
+ },
222
+ });
223
+ let composition;
224
+ let protectedThisKernel = false;
225
+ const compose = (bootOptions) => {
226
+ composition ??= (async () => {
227
+ const raw = await readConfig(configPath);
228
+ const config = parseBrudConfig(raw, configPath);
229
+ // With a build seal, the official participants must be exactly those the
230
+ // builder sealed. One that declares itself official without being sealed
231
+ // is not part of the build, so it is left out and named.
232
+ const sealCheck = options.seal === undefined ? undefined : checkSeal(options.seal, config, configPath);
233
+ if (baseline !== undefined) {
234
+ refuseFrozenChange(baseline, config, configPath, sealCheck?.sealed);
235
+ acceptConfigChange(configPath);
236
+ }
237
+ const unsealed = sealCheck?.unsealed ?? new Set();
238
+ const newlyUnsealed = [...unsealed].filter((path) => !skip.has(path));
239
+ if (newlyUnsealed.length > 0) {
240
+ throw new LoadedParticipantFailure(newlyUnsealed.map((path) => ({
241
+ path,
242
+ code: 'PARTICIPANT_NOT_SEALED',
243
+ reason: 'it declares itself official, but the build did not seal it; only a rebuild can make a participant official',
244
+ })));
245
+ }
246
+ recordConfigRead(configPath, raw);
247
+ protectConfigFile(configPath);
248
+ protectedThisKernel = true;
249
+ composedConfig = config;
250
+ const services = await loadServiceModules(config.services.filter((entry) => !(skip.has(entry.path) && (entry.official !== true || unsealed.has(entry.path)))), configPath, raw);
251
+ const contextOptions = {
252
+ ...(options.options ?? {}),
253
+ ...(bootOptions.options ?? {}),
254
+ };
255
+ const contextLogger = bootOptions.logger ?? options.logger;
256
+ const context = {
257
+ options: contextOptions,
258
+ ...(contextLogger === undefined ? {} : { logger: contextLogger }),
259
+ shared: {},
260
+ declareContextFields,
261
+ getContextSchema: () => contextContract.schema(),
262
+ };
263
+ loadedServices = services;
264
+ serviceContext = context;
265
+ const owned = [];
266
+ const failedLoaded = [];
267
+ for (const loaded of services) {
268
+ activeServiceOwner = `${String(loaded.index)}:${loaded.entry.path}`;
269
+ try {
270
+ const own = [];
271
+ for (const descriptor of await descriptorsFromModule(loaded.module, loaded.entry, loaded.index, context, configPath, raw)) {
272
+ own.push({
273
+ ownerId: activeServiceOwner,
274
+ service: {
275
+ descriptor,
276
+ path: loaded.entry.path,
277
+ ...(loaded.entry.official === undefined ? {} : { official: loaded.entry.official }),
278
+ resolvedPath: loaded.resolvedId,
279
+ // The manifest is admitted from declared data only; the
280
+ // participant's factory is not invoked.
281
+ manifest: admitParticipantManifest(descriptor.token.id, descriptor.manifest),
282
+ },
283
+ });
284
+ }
285
+ owned.push(...own);
286
+ }
287
+ catch (error) {
288
+ if (loaded.entry.official === true) {
289
+ throw error;
290
+ }
291
+ failedLoaded.push(abandonment(loaded.entry.path, error));
292
+ }
293
+ }
294
+ if (failedLoaded.length > 0) {
295
+ throw new LoadedParticipantFailure(failedLoaded);
296
+ }
297
+ // A loaded participant that lacks a required boot option is left out. If
298
+ // any hardcore or composed participant lacks one, the boot is refused as
299
+ // before, naming every missing field.
300
+ contextContract.assertNamespaced(contextOptions);
301
+ const missing = contextContract.missingRequiredByOwner(contextOptions);
302
+ const pathOf = (ownerId) => ownerId.slice(ownerId.indexOf(':') + 1);
303
+ const loadedPaths = new Set(owned.filter((entry) => entry.service.official !== true).map((entry) => entry.service.path));
304
+ if (missing.size > 0 && [...missing.keys()].every((ownerId) => loadedPaths.has(pathOf(ownerId)))) {
305
+ throw new LoadedParticipantFailure([...missing].map(([ownerId, fields]) => ({
306
+ path: pathOf(ownerId),
307
+ code: 'CONTEXT_FIELD_MISSING',
308
+ reason: `required boot option(s) not supplied: ${fields.join(', ')}`,
309
+ })));
310
+ }
311
+ const composed = refuseMissingContext(owned, contextContract, contextOptions);
312
+ for (const entry of owned) {
313
+ if (entry.service.official !== true) {
314
+ loadedTokens.set(entry.service.descriptor.token.id, entry.service.path);
315
+ }
316
+ }
317
+ // The hardcore gate runs after descriptors exist and before any service
318
+ // is registered or initialized. A failure here never reaches the
319
+ // service initialization phase.
320
+ const packageHashes = verifyHardcoreServices(HARDCORE_SERVICES, composed, configPath);
321
+ hardcorePackageHashes = packageHashes;
322
+ hardcoreBootEntries = buildHardcoreBootEntries(composed, packageHashes, HARDCORE_SERVICES);
323
+ for (const service of composed) {
324
+ kernel.register(service.descriptor);
325
+ }
326
+ })();
327
+ return composition;
328
+ };
329
+ const boot = kernel.boot.bind(kernel);
330
+ kernel.boot = async (bootOptions) => {
331
+ lastBootOptions = bootOptions;
332
+ try {
333
+ await compose(bootOptions);
334
+ // Store the bag the composition built: the host's options. Service
335
+ // modules publish no objects into it; a service-to-service handoff goes
336
+ // through an exposed API.
337
+ const bootBag = serviceContext?.options ?? {
338
+ ...(options.options ?? {}),
339
+ ...(bootOptions.options ?? {}),
340
+ };
341
+ await boot({
342
+ options: bootBag,
343
+ logger: bootOptions.logger ?? options.logger ?? DEFAULT_KERNEL_LOGGER,
344
+ });
345
+ // The config document is reread after boot. Refuse to hand back a kernel
346
+ // if it changed underneath us.
347
+ await verifyConfigIntegrity(configPath);
348
+ }
349
+ catch (error) {
350
+ if (kernel.lifecycleState === 'RUNNING') {
351
+ await kernel.shutdown().catch(() => undefined);
352
+ }
353
+ if (protectedThisKernel) {
354
+ protectedThisKernel = false;
355
+ releaseConfigProtection(configPath);
356
+ }
357
+ throw error;
358
+ }
359
+ };
360
+ const shutdown = kernel.shutdown.bind(kernel);
361
+ kernel.shutdown = async () => {
362
+ await shutdown();
363
+ if (protectedThisKernel) {
364
+ protectedThisKernel = false;
365
+ releaseConfigProtection(configPath);
366
+ }
367
+ };
368
+ const abandon = () => {
369
+ if (protectedThisKernel) {
370
+ protectedThisKernel = false;
371
+ releaseConfigProtection(configPath);
372
+ }
373
+ };
374
+ const validate = async (bootOptions) => {
375
+ try {
376
+ await compose(bootOptions);
377
+ }
378
+ catch (error) {
379
+ abandon();
380
+ throw error;
381
+ }
382
+ };
383
+ kernel.reload = (reloadOptions = {}) => {
384
+ if (kernel.lifecycleState !== 'RUNNING') {
385
+ return Promise.reject(new LifecycleStateError('reload', kernel.lifecycleState, 'RUNNING'));
386
+ }
387
+ const target = reloadOptions.configPath ?? configPath;
388
+ // The new composition is read, checked against the frozen part and
389
+ // composed while this kernel still runs; a refusal changes nothing. Only
390
+ // then is this kernel stopped and the new one booted.
391
+ return startTolerant(target, options, lastBootOptions, composedConfig, () => kernel.shutdown(), (error) => new KernelReloadError(target, error));
392
+ };
393
+ Object.defineProperty(kernel, 'abandoned', { get: () => abandonedList, enumerable: true });
394
+ return {
395
+ kernel,
396
+ validate,
397
+ abandon,
398
+ config: () => composedConfig,
399
+ loadedPathOf: (token) => loadedTokens.get(token),
400
+ setAbandoned: (list) => {
401
+ abandonedList = list;
402
+ },
403
+ };
404
+ }
405
+ /**
406
+ * Refuses the boot when any required context field is missing.
407
+ *
408
+ * The rule is the same for every participant, official or not, hardcore or
409
+ * not, depended on or not: a participant that declared a field as required
410
+ * cannot run without it, and leaving it out would give a composition whose
411
+ * exposures disappear without a reason. The error names every missing field,
412
+ * the declaring owner, the participants it covers and the module path, so one
413
+ * failed boot tells the host everything it must supply.
414
+ *
415
+ * @returns The composed descriptors, unchanged.
416
+ */
417
+ function refuseMissingContext(owned, contextContract, options) {
418
+ // A value in the wrong shape or under a flat alias is reported as that, before
419
+ // the field it was meant for is reported as missing.
420
+ contextContract.assertNamespaced(options);
421
+ const missing = contextContract.missingRequiredByOwner(options);
422
+ if (missing.size > 0) {
423
+ const scopeOf = new Map(contextContract.schema().fields.map((field) => [field.name, field.service]));
424
+ const parts = [...missing].map(([ownerId, fields]) => {
425
+ const services = owned.filter((entry) => entry.ownerId === ownerId);
426
+ const participants = services.map((entry) => entry.service.descriptor.token.id);
427
+ const path = services[0]?.service.path;
428
+ return `${fields.join(', ')} (scope "${scopeOf.get(fields[0] ?? '') ?? ownerId}"${participants.length === 0 ? '' : `, participant ${participants.join(', ')}`}${path === undefined ? '' : `, module ${path}`})`;
429
+ });
430
+ const first = [...missing][0];
431
+ throw new ContextContractError(`Boot refused: required context field(s) missing: ${parts.join('; ')}. Supply them in the boot options.`, { field: first[1][0], service: first[0], actualType: 'missing' });
432
+ }
433
+ return owned.map((entry) => entry.service);
434
+ }
435
+ function descriptorsFromModule(moduleValue, entry, index, context, configPath, raw) {
436
+ return descriptorsFromModuleAsync(moduleValue, entry, index, context, configPath, raw);
437
+ }
438
+ async function descriptorsFromModuleAsync(moduleValue, entry, index, context, configPath, raw) {
439
+ if (!isRecord(moduleValue) || typeof moduleValue.createService !== 'function') {
440
+ throw new BrudConfigError('MODULE_CONTRACT', `Service module "${entry.path}" (services[${String(index)}]) must export createService(context)`, configPath, lineOf(raw, entry.path));
441
+ }
442
+ const createService = moduleValue.createService;
443
+ const declared = await createService(context);
444
+ const candidates = Array.isArray(declared) ? declared : [declared];
445
+ if (candidates.length === 0) {
446
+ throw new BrudConfigError('MODULE_CONTRACT', `Service module "${entry.path}" (services[${String(index)}]) exposed no service descriptor`, configPath, lineOf(raw, entry.path));
447
+ }
448
+ for (const candidate of candidates) {
449
+ if (!isServiceDescriptor(candidate)) {
450
+ throw new BrudConfigError('MODULE_CONTRACT', `Service module "${entry.path}" (services[${String(index)}]) did not return a service descriptor`, configPath, lineOf(raw, entry.path));
451
+ }
452
+ }
453
+ return candidates;
454
+ }
455
+ async function readConfig(configPath) {
456
+ try {
457
+ return await readFile(configPath, 'utf8');
458
+ }
459
+ catch (error) {
460
+ throw new BrudConfigError('CONFIG_READ', `Cannot read config: ${error instanceof Error ? error.message : String(error)}`, configPath);
461
+ }
462
+ }
463
+ const isParticipantPackage = (id) => id.endsWith('.json');
464
+ /** Reads the optional `native` entry of a participant package declared official. */
465
+ function packageRequirementsOf(manifestPath, declaredPath, configPath, label, line) {
466
+ try {
467
+ return readPackageRequirements(manifestPath);
468
+ }
469
+ catch (error) {
470
+ const reason = error instanceof PackageRequirementsError ? error.message : String(error);
471
+ throw new BrudConfigError('MODULE_RESOLVE', `Cannot read participant package "${declaredPath}" (${label}): ${reason}`, configPath, line);
472
+ }
473
+ }
474
+ function nativeEntryOf(manifestPath, configPath, label, line) {
475
+ let pkg;
476
+ try {
477
+ pkg = JSON.parse(readFileSync(manifestPath, 'utf8'));
478
+ }
479
+ catch (error) {
480
+ throw new BrudConfigError('MODULE_RESOLVE', `Cannot read participant package "${manifestPath}" (${label}): ${error instanceof Error ? error.message : String(error)}`, configPath, line);
481
+ }
482
+ const native = pkg?.native;
483
+ if (native === undefined) {
484
+ return undefined;
485
+ }
486
+ const resolvedNative = resolvePath(dirname(manifestPath), String(native));
487
+ const inside = relativePath(dirname(manifestPath), resolvedNative);
488
+ if (typeof native !== 'string' || inside.startsWith('..') || isAbsolute(inside)) {
489
+ throw new BrudConfigError('MODULE_RESOLVE', `Participant package "${manifestPath}" (${label}): native must be a path inside the package`, configPath, line);
490
+ }
491
+ return resolvedNative;
492
+ }
493
+ /**
494
+ * Loads every composition entry, enforcing the tier rule (W-01): an entry
495
+ * declared `official: true` runs as Node; every other entry must be a
496
+ * participant package, loaded by the package loader a hardcore provides, so
497
+ * none of its author code runs as Node. A non-official native module is
498
+ * refused at boot.
499
+ */
500
+ async function loadServiceModules(entries, configPath, raw) {
501
+ const unresolvable = [];
502
+ const resolved = entries.flatMap((entry, index) => {
503
+ try {
504
+ return [{
505
+ index,
506
+ entry,
507
+ resolvedId: resolveModuleId(entry.path, configPath),
508
+ label: `services[${String(index)}]`,
509
+ line: lineOf(raw, entry.path),
510
+ }];
511
+ }
512
+ catch (error) {
513
+ // A loaded participant whose path does not resolve is left out; the same
514
+ // failure in a hardcore or composed entry refuses the boot.
515
+ if (entry.official === true) {
516
+ throw error;
517
+ }
518
+ unresolvable.push(abandonment(entry.path, error));
519
+ return [];
520
+ }
521
+ });
522
+ const official = new Map();
523
+ await Promise.all(resolved.map(async (item) => {
524
+ if (item.entry.official === true && !isParticipantPackage(item.resolvedId)) {
525
+ official.set(item.index, await importModule(item.resolvedId, configPath, item.entry.path, item.label, item.line));
526
+ }
527
+ }));
528
+ const loaders = [...official.values()].flatMap((module) => {
529
+ const loader = module?.loadParticipantPackage;
530
+ return typeof loader === 'function' ? [loader] : [];
531
+ });
532
+ const outcomes = await Promise.allSettled(resolved.map(async (item) => {
533
+ const { index, entry, resolvedId, label, line } = item;
534
+ if (official.has(index)) {
535
+ return { index, entry, resolvedId, module: official.get(index) };
536
+ }
537
+ if (!isParticipantPackage(resolvedId)) {
538
+ throw new BrudConfigError('PARTICIPANT_TIER', `"${entry.path}" (${label}) is not declared official, so it cannot run as native code (W-01): ship it as a participant package (brud.participant.json) or declare it "official": true`, configPath, line);
539
+ }
540
+ const requirements = packageRequirementsOf(resolvedId, entry.path, configPath, label, line);
541
+ if (requirements.official && entry.official !== true) {
542
+ const needs = requirements.powers.length === 0 ? '' : ` It uses: ${requirements.powers.join(', ')}.`;
543
+ throw new BrudConfigError('PARTICIPANT_REQUIRES_OFFICIAL', `"${entry.path}" (${label}) requires the composition to declare it "official": true, because it cannot run caged.${needs} Declare it official to run it as trusted native code, or remove the entry`, configPath, line);
544
+ }
545
+ if (entry.official === true) {
546
+ const native = nativeEntryOf(resolvedId, configPath, label, line);
547
+ if (native !== undefined) {
548
+ return { index, entry, resolvedId, module: await importModule(native, configPath, entry.path, label, line) };
549
+ }
550
+ }
551
+ const loader = loaders.length === 1 ? loaders[0] : undefined;
552
+ if (loader === undefined) {
553
+ throw new BrudConfigError('PARTICIPANT_TIER', `"${entry.path}" (${label}) is a participant package, but the composition provides ${loaders.length === 0 ? 'no' : 'more than one'} participant package loader`, configPath, line);
554
+ }
555
+ try {
556
+ return { index, entry, resolvedId, module: await loader(resolvedId) };
557
+ }
558
+ catch (error) {
559
+ throw new BrudConfigError('MODULE_RESOLVE', `Cannot load participant package "${entry.path}" (${label}): ${error instanceof Error ? error.message : String(error)}`, configPath, line);
560
+ }
561
+ }));
562
+ const loaded = [];
563
+ const left = [...unresolvable];
564
+ for (const [position, outcome] of outcomes.entries()) {
565
+ if (outcome.status === 'fulfilled') {
566
+ loaded.push(outcome.value);
567
+ continue;
568
+ }
569
+ const entry = resolved[position].entry;
570
+ if (entry.official === true) {
571
+ throw outcome.reason;
572
+ }
573
+ left.push(abandonment(entry.path, outcome.reason));
574
+ }
575
+ if (left.length > 0) {
576
+ throw new LoadedParticipantFailure(left);
577
+ }
578
+ return loaded;
579
+ }
580
+ async function importModule(id, configPath, declaredPath, label, line) {
581
+ try {
582
+ return await import(id.startsWith('file:') || isAbsolute(id) ? pathToFileURL(id).href : id);
583
+ }
584
+ catch (error) {
585
+ throw new BrudConfigError('MODULE_RESOLVE', `Cannot resolve module "${declaredPath}" (${label}): ${error instanceof Error ? error.message : String(error)}`, configPath, line);
586
+ }
587
+ }
588
+ export function resolveModuleId(declaredPath, configPath) {
589
+ if (declaredPath.startsWith('kernel:')) {
590
+ return resolveExisting(fileURLToPath(new URL(declaredPath.slice('kernel:'.length), KERNEL_PACKAGE_ROOT)));
591
+ }
592
+ if (declaredPath.startsWith('file:')) {
593
+ return resolveExisting(fileURLToPath(declaredPath));
594
+ }
595
+ if (isAbsolute(declaredPath)) {
596
+ return resolveExisting(declaredPath);
597
+ }
598
+ if (declaredPath.startsWith('./') || declaredPath.startsWith('../')) {
599
+ return resolveExisting(resolvePath(dirname(configPath), declaredPath));
600
+ }
601
+ return declaredPath;
602
+ }
603
+ function resolveExisting(candidate) {
604
+ if (existsSync(candidate)) {
605
+ return candidate;
606
+ }
607
+ if (candidate.endsWith('.js')) {
608
+ const source = `${candidate.slice(0, -3)}.ts`;
609
+ if (existsSync(source)) {
610
+ return source;
611
+ }
612
+ }
613
+ if (!candidate.endsWith('.js') && !candidate.endsWith('.ts')) {
614
+ for (const suffix of ['.js', '.ts', '/index.js', '/index.ts']) {
615
+ const next = `${candidate}${suffix}`;
616
+ if (existsSync(next)) {
617
+ return next;
618
+ }
619
+ }
620
+ }
621
+ return candidate;
622
+ }
623
+ function isServiceDescriptor(value) {
624
+ if (!isRecord(value) || !isRecord(value.token)) {
625
+ return false;
626
+ }
627
+ return typeof value.token.id === 'string'
628
+ && typeof value.factory === 'function'
629
+ && Array.isArray(value.dependencies);
630
+ }
631
+ function isRecord(value) {
632
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
633
+ }