apcore-js 0.5.0 → 0.7.0

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 (319) hide show
  1. package/README.md +1 -1
  2. package/dist/acl.d.ts +27 -0
  3. package/dist/acl.d.ts.map +1 -0
  4. package/dist/acl.js +175 -0
  5. package/dist/acl.js.map +1 -0
  6. package/dist/approval.d.ts +85 -0
  7. package/dist/approval.d.ts.map +1 -0
  8. package/dist/approval.js +73 -0
  9. package/dist/approval.js.map +1 -0
  10. package/dist/async-task.d.ts +90 -0
  11. package/dist/async-task.d.ts.map +1 -0
  12. package/dist/async-task.js +215 -0
  13. package/dist/async-task.js.map +1 -0
  14. package/dist/bindings.d.ts +12 -0
  15. package/dist/bindings.d.ts.map +1 -0
  16. package/dist/bindings.js +185 -0
  17. package/dist/bindings.js.map +1 -0
  18. package/dist/cancel.d.ts +14 -0
  19. package/dist/cancel.d.ts.map +1 -0
  20. package/dist/cancel.js +27 -0
  21. package/dist/cancel.js.map +1 -0
  22. package/dist/config.d.ts +9 -0
  23. package/dist/config.d.ts.map +1 -0
  24. package/dist/config.js +23 -0
  25. package/dist/config.js.map +1 -0
  26. package/dist/context.d.ts +50 -0
  27. package/dist/context.d.ts.map +1 -0
  28. package/dist/context.js +87 -0
  29. package/dist/context.js.map +1 -0
  30. package/dist/decorator.d.ts +57 -0
  31. package/dist/decorator.d.ts.map +1 -0
  32. package/dist/decorator.js +74 -0
  33. package/dist/decorator.js.map +1 -0
  34. package/dist/errors.d.ts +204 -0
  35. package/dist/errors.d.ts.map +1 -0
  36. package/dist/errors.js +364 -0
  37. package/dist/errors.js.map +1 -0
  38. package/dist/executor.d.ts +82 -0
  39. package/dist/executor.d.ts.map +1 -0
  40. package/dist/executor.js +489 -0
  41. package/dist/executor.js.map +1 -0
  42. package/dist/extensions.d.ts +58 -0
  43. package/dist/extensions.d.ts.map +1 -0
  44. package/dist/extensions.js +239 -0
  45. package/dist/extensions.js.map +1 -0
  46. package/{src/index.ts → dist/index.d.ts} +6 -63
  47. package/dist/index.d.ts.map +1 -0
  48. package/dist/index.js +45 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/middleware/adapters.d.ts +18 -0
  51. package/dist/middleware/adapters.d.ts.map +1 -0
  52. package/dist/middleware/adapters.js +25 -0
  53. package/dist/middleware/adapters.js.map +1 -0
  54. package/dist/middleware/base.d.ts +10 -0
  55. package/dist/middleware/base.d.ts.map +1 -0
  56. package/dist/middleware/base.js +15 -0
  57. package/dist/middleware/base.js.map +1 -0
  58. package/{src/middleware/index.ts → dist/middleware/index.d.ts} +1 -0
  59. package/dist/middleware/index.d.ts.map +1 -0
  60. package/dist/middleware/index.js +5 -0
  61. package/dist/middleware/index.js.map +1 -0
  62. package/dist/middleware/logging.d.ts +25 -0
  63. package/dist/middleware/logging.d.ts.map +1 -0
  64. package/dist/middleware/logging.js +64 -0
  65. package/dist/middleware/logging.js.map +1 -0
  66. package/dist/middleware/manager.d.ts +21 -0
  67. package/dist/middleware/manager.d.ts.map +1 -0
  68. package/dist/middleware/manager.js +77 -0
  69. package/dist/middleware/manager.js.map +1 -0
  70. package/dist/module.d.ts +31 -0
  71. package/dist/module.d.ts.map +1 -0
  72. package/dist/module.js +12 -0
  73. package/dist/module.js.map +1 -0
  74. package/dist/observability/context-logger.d.ts +54 -0
  75. package/dist/observability/context-logger.d.ts.map +1 -0
  76. package/dist/observability/context-logger.js +151 -0
  77. package/dist/observability/context-logger.js.map +1 -0
  78. package/{src/observability/index.ts → dist/observability/index.d.ts} +1 -0
  79. package/dist/observability/index.d.ts.map +1 -0
  80. package/dist/observability/index.js +4 -0
  81. package/dist/observability/index.js.map +1 -0
  82. package/dist/observability/metrics.d.ts +30 -0
  83. package/dist/observability/metrics.d.ts.map +1 -0
  84. package/dist/observability/metrics.js +177 -0
  85. package/dist/observability/metrics.js.map +1 -0
  86. package/dist/observability/tracing.d.ts +62 -0
  87. package/dist/observability/tracing.d.ts.map +1 -0
  88. package/dist/observability/tracing.js +184 -0
  89. package/dist/observability/tracing.js.map +1 -0
  90. package/dist/registry/dependencies.d.ts +6 -0
  91. package/dist/registry/dependencies.d.ts.map +1 -0
  92. package/dist/registry/dependencies.js +83 -0
  93. package/dist/registry/dependencies.js.map +1 -0
  94. package/dist/registry/entry-point.d.ts +6 -0
  95. package/dist/registry/entry-point.d.ts.map +1 -0
  96. package/dist/registry/entry-point.js +55 -0
  97. package/dist/registry/entry-point.js.map +1 -0
  98. package/{src/registry/index.ts → dist/registry/index.d.ts} +1 -0
  99. package/dist/registry/index.d.ts.map +1 -0
  100. package/dist/registry/index.js +8 -0
  101. package/dist/registry/index.js.map +1 -0
  102. package/dist/registry/metadata.d.ts +9 -0
  103. package/dist/registry/metadata.d.ts.map +1 -0
  104. package/dist/registry/metadata.js +105 -0
  105. package/dist/registry/metadata.js.map +1 -0
  106. package/dist/registry/registry.d.ts +102 -0
  107. package/dist/registry/registry.d.ts.map +1 -0
  108. package/dist/registry/registry.js +534 -0
  109. package/dist/registry/registry.js.map +1 -0
  110. package/dist/registry/scanner.d.ts +7 -0
  111. package/dist/registry/scanner.d.ts.map +1 -0
  112. package/dist/registry/scanner.js +164 -0
  113. package/dist/registry/scanner.js.map +1 -0
  114. package/dist/registry/schema-export.d.ts +9 -0
  115. package/dist/registry/schema-export.d.ts.map +1 -0
  116. package/dist/registry/schema-export.js +132 -0
  117. package/dist/registry/schema-export.js.map +1 -0
  118. package/dist/registry/types.d.ts +29 -0
  119. package/dist/registry/types.d.ts.map +1 -0
  120. package/dist/registry/types.js +5 -0
  121. package/dist/registry/types.js.map +1 -0
  122. package/dist/registry/validation.d.ts +9 -0
  123. package/dist/registry/validation.d.ts.map +1 -0
  124. package/dist/registry/validation.js +33 -0
  125. package/dist/registry/validation.js.map +1 -0
  126. package/dist/schema/annotations.d.ts +8 -0
  127. package/dist/schema/annotations.d.ts.map +1 -0
  128. package/dist/schema/annotations.js +52 -0
  129. package/dist/schema/annotations.js.map +1 -0
  130. package/dist/schema/exporter.d.ts +13 -0
  131. package/dist/schema/exporter.d.ts.map +1 -0
  132. package/dist/schema/exporter.js +71 -0
  133. package/dist/schema/exporter.js.map +1 -0
  134. package/dist/schema/index.d.ts +9 -0
  135. package/dist/schema/index.d.ts.map +1 -0
  136. package/{src/schema/index.ts → dist/schema/index.js} +1 -7
  137. package/dist/schema/index.js.map +1 -0
  138. package/dist/schema/loader.d.ts +30 -0
  139. package/dist/schema/loader.d.ts.map +1 -0
  140. package/dist/schema/loader.js +260 -0
  141. package/dist/schema/loader.js.map +1 -0
  142. package/dist/schema/ref-resolver.d.ts +19 -0
  143. package/dist/schema/ref-resolver.d.ts.map +1 -0
  144. package/dist/schema/ref-resolver.js +212 -0
  145. package/dist/schema/ref-resolver.js.map +1 -0
  146. package/dist/schema/strict.d.ts +7 -0
  147. package/dist/schema/strict.d.ts.map +1 -0
  148. package/dist/schema/strict.js +127 -0
  149. package/dist/schema/strict.js.map +1 -0
  150. package/dist/schema/types.d.ts +53 -0
  151. package/dist/schema/types.d.ts.map +1 -0
  152. package/dist/schema/types.js +31 -0
  153. package/dist/schema/types.js.map +1 -0
  154. package/dist/schema/validator.d.ts +16 -0
  155. package/dist/schema/validator.d.ts.map +1 -0
  156. package/dist/schema/validator.js +71 -0
  157. package/dist/schema/validator.js.map +1 -0
  158. package/dist/trace-context.d.ts +35 -0
  159. package/dist/trace-context.d.ts.map +1 -0
  160. package/dist/trace-context.js +86 -0
  161. package/dist/trace-context.js.map +1 -0
  162. package/dist/utils/index.d.ts +11 -0
  163. package/dist/utils/index.d.ts.map +1 -0
  164. package/dist/utils/index.js +32 -0
  165. package/dist/utils/index.js.map +1 -0
  166. package/dist/utils/pattern.d.ts +5 -0
  167. package/dist/utils/pattern.d.ts.map +1 -0
  168. package/dist/utils/pattern.js +31 -0
  169. package/dist/utils/pattern.js.map +1 -0
  170. package/package.json +24 -3
  171. package/.claude/settings.local.json +0 -12
  172. package/.github/workflows/ci.yml +0 -39
  173. package/.gitmessage +0 -60
  174. package/.pre-commit-config.yaml +0 -28
  175. package/CHANGELOG.md +0 -214
  176. package/CLAUDE.md +0 -68
  177. package/apcore-logo.svg +0 -79
  178. package/planning/acl-system/overview.md +0 -54
  179. package/planning/acl-system/plan.md +0 -92
  180. package/planning/acl-system/state.json +0 -76
  181. package/planning/acl-system/tasks/acl-core.md +0 -226
  182. package/planning/acl-system/tasks/acl-rule.md +0 -92
  183. package/planning/acl-system/tasks/conditional-rules.md +0 -259
  184. package/planning/acl-system/tasks/pattern-matching.md +0 -152
  185. package/planning/acl-system/tasks/yaml-loading.md +0 -271
  186. package/planning/core-executor/overview.md +0 -53
  187. package/planning/core-executor/plan.md +0 -88
  188. package/planning/core-executor/state.json +0 -76
  189. package/planning/core-executor/tasks/async-support.md +0 -106
  190. package/planning/core-executor/tasks/execution-pipeline.md +0 -113
  191. package/planning/core-executor/tasks/redaction.md +0 -85
  192. package/planning/core-executor/tasks/safety-checks.md +0 -65
  193. package/planning/core-executor/tasks/setup.md +0 -75
  194. package/planning/decorator-bindings/overview.md +0 -62
  195. package/planning/decorator-bindings/plan.md +0 -104
  196. package/planning/decorator-bindings/state.json +0 -87
  197. package/planning/decorator-bindings/tasks/binding-directory.md +0 -79
  198. package/planning/decorator-bindings/tasks/binding-loader.md +0 -148
  199. package/planning/decorator-bindings/tasks/explicit-schemas.md +0 -85
  200. package/planning/decorator-bindings/tasks/function-module.md +0 -127
  201. package/planning/decorator-bindings/tasks/module-factory.md +0 -89
  202. package/planning/decorator-bindings/tasks/schema-modes.md +0 -142
  203. package/planning/middleware-system/overview.md +0 -48
  204. package/planning/middleware-system/plan.md +0 -102
  205. package/planning/middleware-system/state.json +0 -65
  206. package/planning/middleware-system/tasks/adapters.md +0 -170
  207. package/planning/middleware-system/tasks/base.md +0 -115
  208. package/planning/middleware-system/tasks/logging-middleware.md +0 -304
  209. package/planning/middleware-system/tasks/manager.md +0 -313
  210. package/planning/observability/overview.md +0 -53
  211. package/planning/observability/plan.md +0 -119
  212. package/planning/observability/state.json +0 -98
  213. package/planning/observability/tasks/context-logger.md +0 -201
  214. package/planning/observability/tasks/exporters.md +0 -121
  215. package/planning/observability/tasks/metrics-collector.md +0 -162
  216. package/planning/observability/tasks/metrics-middleware.md +0 -141
  217. package/planning/observability/tasks/obs-logging-middleware.md +0 -179
  218. package/planning/observability/tasks/span-model.md +0 -120
  219. package/planning/observability/tasks/tracing-middleware.md +0 -179
  220. package/planning/overview.md +0 -81
  221. package/planning/registry-system/overview.md +0 -57
  222. package/planning/registry-system/plan.md +0 -114
  223. package/planning/registry-system/state.json +0 -109
  224. package/planning/registry-system/tasks/dependencies.md +0 -157
  225. package/planning/registry-system/tasks/entry-point.md +0 -148
  226. package/planning/registry-system/tasks/metadata.md +0 -198
  227. package/planning/registry-system/tasks/registry-core.md +0 -323
  228. package/planning/registry-system/tasks/scanner.md +0 -172
  229. package/planning/registry-system/tasks/schema-export.md +0 -261
  230. package/planning/registry-system/tasks/types.md +0 -124
  231. package/planning/registry-system/tasks/validation.md +0 -177
  232. package/planning/schema-system/overview.md +0 -56
  233. package/planning/schema-system/plan.md +0 -121
  234. package/planning/schema-system/state.json +0 -98
  235. package/planning/schema-system/tasks/exporter.md +0 -153
  236. package/planning/schema-system/tasks/loader.md +0 -106
  237. package/planning/schema-system/tasks/ref-resolver.md +0 -133
  238. package/planning/schema-system/tasks/strict-mode.md +0 -140
  239. package/planning/schema-system/tasks/typebox-generation.md +0 -133
  240. package/planning/schema-system/tasks/types-and-annotations.md +0 -160
  241. package/planning/schema-system/tasks/validator.md +0 -149
  242. package/src/acl.ts +0 -200
  243. package/src/async-task.ts +0 -267
  244. package/src/bindings.ts +0 -207
  245. package/src/cancel.ts +0 -32
  246. package/src/config.ts +0 -24
  247. package/src/context.ts +0 -160
  248. package/src/decorator.ts +0 -110
  249. package/src/errors.ts +0 -429
  250. package/src/executor.ts +0 -493
  251. package/src/extensions.ts +0 -265
  252. package/src/middleware/adapters.ts +0 -54
  253. package/src/middleware/base.ts +0 -33
  254. package/src/middleware/logging.ts +0 -103
  255. package/src/middleware/manager.ts +0 -105
  256. package/src/module.ts +0 -43
  257. package/src/observability/context-logger.ts +0 -203
  258. package/src/observability/metrics.ts +0 -214
  259. package/src/observability/tracing.ts +0 -252
  260. package/src/registry/dependencies.ts +0 -99
  261. package/src/registry/entry-point.ts +0 -64
  262. package/src/registry/metadata.ts +0 -111
  263. package/src/registry/registry.ts +0 -580
  264. package/src/registry/scanner.ts +0 -168
  265. package/src/registry/schema-export.ts +0 -181
  266. package/src/registry/types.ts +0 -32
  267. package/src/registry/validation.ts +0 -38
  268. package/src/schema/annotations.ts +0 -68
  269. package/src/schema/exporter.ts +0 -90
  270. package/src/schema/loader.ts +0 -273
  271. package/src/schema/ref-resolver.ts +0 -244
  272. package/src/schema/strict.ts +0 -136
  273. package/src/schema/types.ts +0 -73
  274. package/src/schema/validator.ts +0 -82
  275. package/src/trace-context.ts +0 -102
  276. package/src/utils/index.ts +0 -5
  277. package/src/utils/pattern.ts +0 -30
  278. package/tests/async-task.test.ts +0 -335
  279. package/tests/helpers.ts +0 -30
  280. package/tests/integration/test-acl-safety.test.ts +0 -269
  281. package/tests/integration/test-binding-executor.test.ts +0 -194
  282. package/tests/integration/test-e2e-flow.test.ts +0 -117
  283. package/tests/integration/test-error-propagation.test.ts +0 -259
  284. package/tests/integration/test-middleware-chain.test.ts +0 -120
  285. package/tests/integration/test-observability-integration.test.ts +0 -438
  286. package/tests/observability/test-context-logger.test.ts +0 -123
  287. package/tests/observability/test-metrics.test.ts +0 -186
  288. package/tests/observability/test-tracing.test.ts +0 -303
  289. package/tests/registry/test-dependencies.test.ts +0 -70
  290. package/tests/registry/test-entry-point.test.ts +0 -133
  291. package/tests/registry/test-metadata.test.ts +0 -265
  292. package/tests/registry/test-registry.test.ts +0 -1397
  293. package/tests/registry/test-scanner.test.ts +0 -257
  294. package/tests/registry/test-schema-export.test.ts +0 -355
  295. package/tests/registry/test-validation.test.ts +0 -75
  296. package/tests/schema/test-annotations.test.ts +0 -137
  297. package/tests/schema/test-exporter.test.ts +0 -172
  298. package/tests/schema/test-loader.test.ts +0 -461
  299. package/tests/schema/test-ref-resolver.test.ts +0 -530
  300. package/tests/schema/test-strict.test.ts +0 -348
  301. package/tests/schema/test-validator.test.ts +0 -64
  302. package/tests/test-acl.test.ts +0 -423
  303. package/tests/test-bindings.test.ts +0 -227
  304. package/tests/test-cancel.test.ts +0 -71
  305. package/tests/test-config.test.ts +0 -76
  306. package/tests/test-context.test.ts +0 -266
  307. package/tests/test-decorator.test.ts +0 -173
  308. package/tests/test-errors.test.ts +0 -647
  309. package/tests/test-executor-stream.test.ts +0 -208
  310. package/tests/test-executor.test.ts +0 -252
  311. package/tests/test-extensions.test.ts +0 -310
  312. package/tests/test-logging-middleware.test.ts +0 -150
  313. package/tests/test-middleware-manager.test.ts +0 -185
  314. package/tests/test-middleware.test.ts +0 -86
  315. package/tests/test-trace-context.test.ts +0 -251
  316. package/tests/utils/test-pattern.test.ts +0 -109
  317. package/tsconfig.build.json +0 -8
  318. package/tsconfig.json +0 -20
  319. package/vitest.config.ts +0 -18
@@ -1,580 +0,0 @@
1
- /**
2
- * Central module registry for discovering, registering, and querying modules.
3
- */
4
-
5
- import { watch as fsWatch, accessSync } from 'node:fs';
6
- import { resolve, join, basename, extname } from 'node:path';
7
- import type { Config } from '../config.js';
8
- import { InvalidInputError, ModuleNotFoundError } from '../errors.js';
9
- import type { ModuleAnnotations, ModuleExample } from '../module.js';
10
- import { resolveDependencies } from './dependencies.js';
11
- import { resolveEntryPoint } from './entry-point.js';
12
- import { loadIdMap, loadMetadata, mergeModuleMetadata, parseDependencies } from './metadata.js';
13
- import { scanExtensions, scanMultiRoot } from './scanner.js';
14
- import type { DependencyInfo, ModuleDescriptor } from './types.js';
15
- import { validateModule } from './validation.js';
16
-
17
- /**
18
- * Standard registry event names.
19
- */
20
- export const REGISTRY_EVENTS = Object.freeze({
21
- REGISTER: "register",
22
- UNREGISTER: "unregister",
23
- } as const);
24
-
25
- /**
26
- * Valid module ID pattern. Only lowercase letters, digits, underscores, and dots.
27
- * Hyphens are prohibited to ensure bijective MCP/OpenAI tool name normalization.
28
- */
29
- export const MODULE_ID_PATTERN = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/;
30
-
31
- /**
32
- * Maximum allowed length for a module ID.
33
- */
34
- export const MAX_MODULE_ID_LENGTH = 128;
35
-
36
- /**
37
- * Reserved words that cannot appear as any segment of a module ID.
38
- */
39
- export const RESERVED_WORDS = new Set(['system', 'internal', 'core', 'apcore', 'plugin', 'schema', 'acl']);
40
-
41
- /**
42
- * Interface for custom module discovery.
43
- */
44
- export interface Discoverer {
45
- discover(roots: string[]): Array<{ moduleId: string; module: unknown }> | Promise<Array<{ moduleId: string; module: unknown }>>;
46
- }
47
-
48
- /**
49
- * Interface for custom module validation.
50
- */
51
- export interface ModuleValidator {
52
- validate(module: unknown): string[] | Promise<string[]>;
53
- }
54
-
55
- type EventCallback = (moduleId: string, module: unknown) => void;
56
-
57
- export class Registry {
58
- private _extensionRoots: Array<Record<string, unknown>>;
59
- private _modules: Map<string, unknown> = new Map();
60
- private _moduleMeta: Map<string, Record<string, unknown>> = new Map();
61
- private _callbacks: Map<string, EventCallback[]> = new Map([
62
- [REGISTRY_EVENTS.REGISTER, []],
63
- [REGISTRY_EVENTS.UNREGISTER, []],
64
- ]);
65
- private _idMap: Record<string, Record<string, unknown>> = {};
66
- private _schemaCache: Map<string, Record<string, unknown>> = new Map();
67
- private _config: Config | null;
68
- private _watchers?: Array<{ close(): void }>;
69
- private _debounceTimers?: Map<string, number>;
70
- private _customDiscoverer: Discoverer | null = null;
71
- private _customValidator: ModuleValidator | null = null;
72
-
73
- constructor(options?: {
74
- config?: Config | null;
75
- extensionsDir?: string | null;
76
- extensionsDirs?: Array<string | Record<string, unknown>> | null;
77
- idMapPath?: string | null;
78
- }) {
79
- const config = options?.config ?? null;
80
- const extensionsDir = options?.extensionsDir ?? null;
81
- const extensionsDirs = options?.extensionsDirs ?? null;
82
- const idMapPath = options?.idMapPath ?? null;
83
-
84
- if (extensionsDir !== null && extensionsDirs !== null) {
85
- throw new InvalidInputError('Cannot specify both extensionsDir and extensionsDirs');
86
- }
87
-
88
- if (extensionsDir !== null) {
89
- this._extensionRoots = [{ root: extensionsDir }];
90
- } else if (extensionsDirs !== null) {
91
- this._extensionRoots = extensionsDirs.map((item) =>
92
- typeof item === 'string' ? { root: item } : item,
93
- );
94
- } else if (config !== null) {
95
- const extRoot = config.get('extensions.root') as string | undefined;
96
- this._extensionRoots = [{ root: extRoot ?? './extensions' }];
97
- } else {
98
- this._extensionRoots = [{ root: './extensions' }];
99
- }
100
-
101
- this._config = config;
102
-
103
- if (idMapPath !== null) {
104
- this._idMap = loadIdMap(idMapPath);
105
- }
106
- }
107
-
108
- setDiscoverer(discoverer: Discoverer): void {
109
- this._customDiscoverer = discoverer;
110
- }
111
-
112
- setValidator(validator: ModuleValidator): void {
113
- this._customValidator = validator;
114
- }
115
-
116
- async discover(): Promise<number> {
117
- if (this._customDiscoverer !== null) {
118
- return this._discoverCustom();
119
- }
120
- return this._discoverDefault();
121
- }
122
-
123
- private async _discoverCustom(): Promise<number> {
124
- const rootPaths = this._extensionRoots.map((r) => r['root'] as string);
125
- const customModules = await this._customDiscoverer!.discover(rootPaths);
126
-
127
- let count = 0;
128
- for (const entry of customModules) {
129
- const { moduleId, module: mod } = entry;
130
-
131
- // Apply custom validator if set
132
- if (this._customValidator !== null) {
133
- const errors = await this._customValidator.validate(mod);
134
- if (errors.length > 0) {
135
- console.warn(
136
- `[apcore:registry] Custom validator rejected module '${moduleId}': ${errors.join('; ')}`,
137
- );
138
- continue;
139
- }
140
- }
141
-
142
- try {
143
- this.register(moduleId, mod);
144
- count++;
145
- } catch (e) {
146
- console.warn(`[apcore:registry] Failed to register custom-discovered module '${moduleId}':`, e);
147
- }
148
- }
149
-
150
- return count;
151
- }
152
-
153
- private async _discoverDefault(): Promise<number> {
154
- const discovered = this._scanRoots();
155
- this._applyIdMapOverrides(discovered);
156
-
157
- const rawMetadata = this._loadAllMetadata(discovered);
158
- const resolvedModules = await this._resolveAllEntryPoints(discovered, rawMetadata);
159
- const validModules = await this._validateAll(resolvedModules);
160
- const loadOrder = this._resolveLoadOrder(validModules, rawMetadata);
161
-
162
- return this._registerInOrder(loadOrder, validModules, rawMetadata);
163
- }
164
-
165
- private _scanRoots(): import('./types.js').DiscoveredModule[] {
166
- let maxDepth = 8;
167
- let followSymlinks = false;
168
- if (this._config !== null) {
169
- maxDepth = (this._config.get('extensions.max_depth', 8) as number);
170
- followSymlinks = (this._config.get('extensions.follow_symlinks', false) as boolean);
171
- }
172
-
173
- const hasNamespace = this._extensionRoots.some((r) => 'namespace' in r);
174
- if (this._extensionRoots.length > 1 || hasNamespace) {
175
- return scanMultiRoot(this._extensionRoots, maxDepth, followSymlinks);
176
- }
177
- return scanExtensions(this._extensionRoots[0]['root'] as string, maxDepth, followSymlinks);
178
- }
179
-
180
- private _applyIdMapOverrides(discovered: import('./types.js').DiscoveredModule[]): void {
181
- if (Object.keys(this._idMap).length === 0) return;
182
-
183
- const resolvedRoots = this._extensionRoots.map((r) => resolve(r['root'] as string));
184
- for (const dm of discovered) {
185
- for (const root of resolvedRoots) {
186
- try {
187
- const relPath = dm.filePath.startsWith(root)
188
- ? dm.filePath.slice(root.length + 1)
189
- : null;
190
- if (relPath && relPath in this._idMap) {
191
- dm.canonicalId = this._idMap[relPath]['id'] as string;
192
- break;
193
- }
194
- } catch (e) {
195
- console.warn(`[apcore:registry] Failed to apply ID map for ${dm.canonicalId}:`, e);
196
- continue;
197
- }
198
- }
199
- }
200
- }
201
-
202
- private _loadAllMetadata(
203
- discovered: import('./types.js').DiscoveredModule[],
204
- ): Map<string, Record<string, unknown>> {
205
- const rawMetadata = new Map<string, Record<string, unknown>>();
206
- for (const dm of discovered) {
207
- rawMetadata.set(dm.canonicalId, dm.metaPath ? loadMetadata(dm.metaPath) : {});
208
- }
209
- return rawMetadata;
210
- }
211
-
212
- private async _resolveAllEntryPoints(
213
- discovered: import('./types.js').DiscoveredModule[],
214
- rawMetadata: Map<string, Record<string, unknown>>,
215
- ): Promise<Map<string, unknown>> {
216
- const resolvedModules = new Map<string, unknown>();
217
- for (const dm of discovered) {
218
- const meta = rawMetadata.get(dm.canonicalId) ?? {};
219
- try {
220
- const mod = await resolveEntryPoint(dm.filePath, meta);
221
- resolvedModules.set(dm.canonicalId, mod);
222
- } catch (e) {
223
- console.warn(`[apcore:registry] Failed to resolve entry point for ${dm.canonicalId}:`, e);
224
- }
225
- }
226
- return resolvedModules;
227
- }
228
-
229
- private async _validateAll(resolvedModules: Map<string, unknown>): Promise<Map<string, unknown>> {
230
- const validModules = new Map<string, unknown>();
231
- for (const [modId, mod] of resolvedModules) {
232
- if (this._customValidator !== null) {
233
- const errors = await this._customValidator.validate(mod);
234
- if (errors.length === 0) {
235
- validModules.set(modId, mod);
236
- }
237
- } else if (validateModule(mod).length === 0) {
238
- validModules.set(modId, mod);
239
- }
240
- }
241
- return validModules;
242
- }
243
-
244
- private _resolveLoadOrder(
245
- validModules: Map<string, unknown>,
246
- rawMetadata: Map<string, Record<string, unknown>>,
247
- ): string[] {
248
- const modulesWithDeps: Array<[string, DependencyInfo[]]> = [];
249
- for (const modId of validModules.keys()) {
250
- const meta = rawMetadata.get(modId) ?? {};
251
- const depsRaw = (meta['dependencies'] as Array<Record<string, unknown>>) ?? [];
252
- modulesWithDeps.push([modId, depsRaw.length > 0 ? parseDependencies(depsRaw) : []]);
253
- }
254
- const knownIds = new Set(modulesWithDeps.map(([id]) => id));
255
- return resolveDependencies(modulesWithDeps, knownIds);
256
- }
257
-
258
- private _registerInOrder(
259
- loadOrder: string[],
260
- validModules: Map<string, unknown>,
261
- rawMetadata: Map<string, Record<string, unknown>>,
262
- ): number {
263
- let count = 0;
264
- for (const modId of loadOrder) {
265
- const mod = validModules.get(modId)!;
266
- const modObj = mod as Record<string, unknown>;
267
- const mergedMeta = mergeModuleMetadata(modObj, rawMetadata.get(modId) ?? {});
268
-
269
- this._modules.set(modId, mod);
270
- this._moduleMeta.set(modId, mergedMeta);
271
-
272
- if (typeof modObj['onLoad'] === 'function') {
273
- try {
274
- (modObj['onLoad'] as () => void)();
275
- } catch (e) {
276
- console.warn(`[apcore:registry] onLoad failed for ${modId}, skipping:`, e);
277
- this._modules.delete(modId);
278
- this._moduleMeta.delete(modId);
279
- continue;
280
- }
281
- }
282
-
283
- this._triggerEvent(REGISTRY_EVENTS.REGISTER, modId, mod);
284
- count++;
285
- }
286
- return count;
287
- }
288
-
289
- register(moduleId: string, module: unknown): void {
290
- if (!moduleId || typeof moduleId !== "string") {
291
- throw new InvalidInputError("Module ID must be a non-empty string");
292
- }
293
- if (!MODULE_ID_PATTERN.test(moduleId)) {
294
- throw new InvalidInputError(
295
- `Invalid module ID: "${moduleId}". Must match pattern: ${MODULE_ID_PATTERN} (lowercase, digits, underscores, dots only; no hyphens)`,
296
- );
297
- }
298
-
299
- const parts = moduleId.split('.');
300
- for (const part of parts) {
301
- if (RESERVED_WORDS.has(part)) {
302
- throw new InvalidInputError(`Module ID contains reserved word: '${part}'`);
303
- }
304
- }
305
- if (moduleId.length > MAX_MODULE_ID_LENGTH) {
306
- throw new InvalidInputError(`Module ID exceeds maximum length of ${MAX_MODULE_ID_LENGTH}: ${moduleId.length}`);
307
- }
308
-
309
- if (this._modules.has(moduleId)) {
310
- throw new InvalidInputError(`Module already exists: ${moduleId}`);
311
- }
312
-
313
- this._modules.set(moduleId, module);
314
-
315
- // Populate metadata from the module object
316
- const modObj = module as Record<string, unknown>;
317
- this._moduleMeta.set(moduleId, mergeModuleMetadata(modObj, {}));
318
-
319
- // Call onLoad if available
320
- if (typeof modObj['onLoad'] === 'function') {
321
- try {
322
- (modObj['onLoad'] as () => void)();
323
- } catch (e) {
324
- this._modules.delete(moduleId);
325
- this._moduleMeta.delete(moduleId);
326
- throw e;
327
- }
328
- }
329
-
330
- this._triggerEvent(REGISTRY_EVENTS.REGISTER, moduleId, module);
331
- }
332
-
333
- unregister(moduleId: string): boolean {
334
- if (!this._modules.has(moduleId)) return false;
335
-
336
- const module = this._modules.get(moduleId)!;
337
- this._modules.delete(moduleId);
338
- this._moduleMeta.delete(moduleId);
339
- this._schemaCache.delete(moduleId);
340
-
341
- // Call onUnload if available
342
- const modObj = module as Record<string, unknown>;
343
- if (typeof modObj['onUnload'] === 'function') {
344
- try {
345
- (modObj['onUnload'] as () => void)();
346
- } catch (e) {
347
- console.warn(`[apcore:registry] onUnload failed for ${moduleId}:`, e);
348
- }
349
- }
350
-
351
- this._triggerEvent(REGISTRY_EVENTS.UNREGISTER, moduleId, module);
352
- return true;
353
- }
354
-
355
- get(moduleId: string): unknown | null {
356
- if (moduleId === '') {
357
- throw new ModuleNotFoundError('');
358
- }
359
- return this._modules.get(moduleId) ?? null;
360
- }
361
-
362
- has(moduleId: string): boolean {
363
- return this._modules.has(moduleId);
364
- }
365
-
366
- list(options?: { tags?: string[]; prefix?: string }): string[] {
367
- let ids = [...this._modules.keys()];
368
-
369
- if (options?.prefix != null) {
370
- ids = ids.filter((id) => id.startsWith(options.prefix!));
371
- }
372
-
373
- if (options?.tags != null) {
374
- const tagSet = new Set(options.tags);
375
- ids = ids.filter((id) => {
376
- const mod = this._modules.get(id) as Record<string, unknown>;
377
- const modTags = new Set((mod['tags'] as string[]) ?? []);
378
- const metaTags = (this._moduleMeta.get(id) ?? {})['tags'];
379
- if (Array.isArray(metaTags)) {
380
- for (const t of metaTags) modTags.add(t as string);
381
- }
382
- for (const t of tagSet) {
383
- if (!modTags.has(t)) return false;
384
- }
385
- return true;
386
- });
387
- }
388
-
389
- return ids.sort();
390
- }
391
-
392
- iter(): IterableIterator<[string, unknown]> {
393
- return this._modules.entries();
394
- }
395
-
396
- get count(): number {
397
- return this._modules.size;
398
- }
399
-
400
- get moduleIds(): string[] {
401
- return [...this._modules.keys()].sort();
402
- }
403
-
404
- getDefinition(moduleId: string): ModuleDescriptor | null {
405
- const module = this._modules.get(moduleId);
406
- if (module == null) return null;
407
- const meta = this._moduleMeta.get(moduleId) ?? {};
408
- const mod = module as Record<string, unknown>;
409
-
410
- return {
411
- moduleId,
412
- name: ((meta['name'] as string) ?? (mod['name'] as string)) ?? null,
413
- description: ((meta['description'] as string) ?? (mod['description'] as string)) ?? '',
414
- documentation: ((meta['documentation'] as string) ?? (mod['documentation'] as string)) ?? null,
415
- inputSchema: (mod['inputSchema'] as Record<string, unknown>) ?? {},
416
- outputSchema: (mod['outputSchema'] as Record<string, unknown>) ?? {},
417
- version: ((meta['version'] as string) ?? (mod['version'] as string)) ?? '1.0.0',
418
- tags: (meta['tags'] as string[]) ?? (mod['tags'] as string[]) ?? [],
419
- annotations: (mod['annotations'] as ModuleAnnotations) ?? null,
420
- examples: (mod['examples'] as ModuleExample[]) ?? [],
421
- metadata: (meta['metadata'] as Record<string, unknown>) ?? {},
422
- };
423
- }
424
-
425
- describe(moduleId: string): string {
426
- const module = this.get(moduleId);
427
- if (module === null) {
428
- throw new ModuleNotFoundError(moduleId);
429
- }
430
-
431
- // Check for custom describe method
432
- const modObj = module as Record<string, unknown>;
433
- if (typeof modObj['describe'] === 'function') {
434
- return (modObj['describe'] as () => string)();
435
- }
436
-
437
- // Auto-generate from descriptor
438
- const descriptor = this.getDefinition(moduleId);
439
- if (descriptor === null) {
440
- return `Module: ${moduleId}\n\nNo description available.`;
441
- }
442
-
443
- const lines: string[] = [`# ${descriptor.moduleId}`];
444
- if (descriptor.description) {
445
- lines.push(`\n${descriptor.description}`);
446
- }
447
- if (descriptor.tags.length > 0) {
448
- lines.push(`\n**Tags:** ${descriptor.tags.join(', ')}`);
449
- }
450
- const props = descriptor.inputSchema['properties'] as Record<string, Record<string, unknown>> | undefined;
451
- if (props && Object.keys(props).length > 0) {
452
- lines.push('\n**Parameters:**');
453
- const requiredFields = (descriptor.inputSchema['required'] as string[]) ?? [];
454
- for (const [param, schema] of Object.entries(props)) {
455
- const paramType = (schema['type'] as string) ?? 'any';
456
- const paramDesc = (schema['description'] as string) ?? '';
457
- const isRequired = requiredFields.includes(param);
458
- const reqMarker = isRequired ? ' (required)' : '';
459
- lines.push(`- \`${param}\` (${paramType})${reqMarker}: ${paramDesc}`);
460
- }
461
- }
462
- if (descriptor.documentation) {
463
- lines.push(`\n**Documentation:**\n${descriptor.documentation}`);
464
- }
465
- return lines.join('\n');
466
- }
467
-
468
- on(event: string, callback: EventCallback): void {
469
- const validEvents = Object.values(REGISTRY_EVENTS) as string[];
470
- if (!validEvents.includes(event)) {
471
- throw new InvalidInputError(
472
- `Invalid event: ${event}. Must be one of: ${validEvents.map((e) => `'${e}'`).join(', ')}`,
473
- );
474
- }
475
- this._callbacks.get(event)!.push(callback);
476
- }
477
-
478
- private _triggerEvent(event: string, moduleId: string, module: unknown): void {
479
- const callbacks = this._callbacks.get(event) ?? [];
480
- for (const cb of callbacks) {
481
- try {
482
- cb(moduleId, module);
483
- } catch (e) {
484
- console.warn(`[apcore:registry] Event callback error for '${event}' on ${moduleId}:`, e);
485
- }
486
- }
487
- }
488
-
489
- watch(): void {
490
- if (this._watchers && this._watchers.length > 0) {
491
- return; // Already watching
492
- }
493
-
494
- this._watchers = [];
495
- this._debounceTimers = new Map<string, number>();
496
-
497
- for (const root of this._extensionRoots) {
498
- const rootPath = typeof root === "string" ? root : (root as Record<string, unknown>).root as string;
499
- if (!rootPath) continue;
500
-
501
- try {
502
- const watcher = fsWatch(rootPath, { recursive: true }, (eventType: string, filename: string | null) => {
503
- if (!filename) return;
504
- if (!filename.endsWith(".ts") && !filename.endsWith(".js")) return;
505
-
506
- const fullPath = join(rootPath, filename);
507
- const now = Date.now();
508
- const last = this._debounceTimers?.get(fullPath) ?? 0;
509
- if (now - last < 300) return;
510
- this._debounceTimers?.set(fullPath, now);
511
-
512
- if (eventType === "rename") {
513
- // Could be create or delete
514
- try {
515
- accessSync(fullPath);
516
- this._handleFileChange(fullPath);
517
- } catch {
518
- this._handleFileDeletion(fullPath);
519
- }
520
- } else {
521
- this._handleFileChange(fullPath);
522
- }
523
- });
524
- this._watchers.push(watcher);
525
- } catch {
526
- // Skip directories that don't exist
527
- }
528
- }
529
- }
530
-
531
- unwatch(): void {
532
- if (this._watchers) {
533
- for (const watcher of this._watchers) {
534
- watcher.close();
535
- }
536
- this._watchers = [];
537
- }
538
- this._debounceTimers = undefined;
539
- }
540
-
541
- private _handleFileChange(filePath: string): void {
542
- const moduleId = this._pathToModuleId(filePath);
543
-
544
- if (moduleId && this.has(moduleId)) {
545
- const oldModule = this.get(moduleId) as Record<string, unknown> | null;
546
- if (oldModule && typeof oldModule.onUnload === "function") {
547
- try { oldModule.onUnload(); } catch { /* ignore */ }
548
- }
549
- this.unregister(moduleId);
550
- }
551
-
552
- // Re-import is complex in ES modules - emit event for user to handle
553
- this._triggerEvent("register", moduleId ?? basename(filePath, extname(filePath)), null);
554
- }
555
-
556
- private _handleFileDeletion(path: string): void {
557
- const moduleId = this._pathToModuleId(path);
558
- if (moduleId && this.has(moduleId)) {
559
- const module = this.get(moduleId) as Record<string, unknown> | null;
560
- if (module && typeof module.onUnload === "function") {
561
- try { module.onUnload(); } catch { /* ignore */ }
562
- }
563
- this.unregister(moduleId);
564
- }
565
- }
566
-
567
- private _pathToModuleId(filePath: string): string | null {
568
- const base = basename(filePath, extname(filePath));
569
- for (const mid of this.moduleIds) {
570
- if (mid.endsWith(base) || mid === base) {
571
- return mid;
572
- }
573
- }
574
- return null;
575
- }
576
-
577
- clearCache(): void {
578
- this._schemaCache.clear();
579
- }
580
- }