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,273 +0,0 @@
1
- /**
2
- * SchemaLoader — primary entry point for the schema system.
3
- *
4
- * Uses TypeBox for schema representation. Since TypeBox schemas ARE JSON Schema,
5
- * the conversion layer is minimal.
6
- */
7
-
8
- import { readFileSync, existsSync } from 'node:fs';
9
- import { resolve, join } from 'node:path';
10
- import { Type, type TSchema } from '@sinclair/typebox';
11
- import yaml from 'js-yaml';
12
- import type { Config } from '../config.js';
13
- import { SchemaNotFoundError, SchemaParseError } from '../errors.js';
14
- import { RefResolver } from './ref-resolver.js';
15
- import type { ResolvedSchema, SchemaDefinition } from './types.js';
16
- import { SchemaStrategy } from './types.js';
17
-
18
- export class SchemaLoader {
19
- private _config: Config;
20
- private _schemasDir: string;
21
- private _resolver: RefResolver;
22
- private _schemaCache: Map<string, SchemaDefinition> = new Map();
23
- private _modelCache: Map<string, [ResolvedSchema, ResolvedSchema]> = new Map();
24
-
25
- constructor(config: Config, schemasDir?: string | null) {
26
- this._config = config;
27
- if (schemasDir != null) {
28
- this._schemasDir = resolve(schemasDir);
29
- } else {
30
- this._schemasDir = resolve(config.get('schema.root', './schemas') as string);
31
- }
32
- const maxDepth = (config.get('schema.max_ref_depth', 32) as number);
33
- this._resolver = new RefResolver(this._schemasDir, maxDepth);
34
- }
35
-
36
- load(moduleId: string): SchemaDefinition {
37
- const cached = this._schemaCache.get(moduleId);
38
- if (cached) return cached;
39
-
40
- const filePath = join(this._schemasDir, moduleId.replace(/\./g, '/') + '.schema.yaml');
41
- if (!existsSync(filePath)) {
42
- throw new SchemaNotFoundError(moduleId);
43
- }
44
-
45
- let data: unknown;
46
- try {
47
- data = yaml.load(readFileSync(filePath, 'utf-8'));
48
- } catch (e) {
49
- throw new SchemaParseError(`Invalid YAML in schema for '${moduleId}': ${e}`);
50
- }
51
-
52
- if (data === null || data === undefined || typeof data !== 'object' || Array.isArray(data)) {
53
- throw new SchemaParseError(`Schema file for '${moduleId}' is empty or not a mapping`);
54
- }
55
-
56
- const dataObj = data as Record<string, unknown>;
57
- for (const fieldName of ['input_schema', 'output_schema', 'description']) {
58
- if (!(fieldName in dataObj)) {
59
- throw new SchemaParseError(`Missing required field: ${fieldName} in schema for '${moduleId}'`);
60
- }
61
- }
62
-
63
- const definitions: Record<string, unknown> = {
64
- ...((dataObj['definitions'] as Record<string, unknown>) ?? {}),
65
- ...((dataObj['$defs'] as Record<string, unknown>) ?? {}),
66
- };
67
-
68
- const sd: SchemaDefinition = {
69
- moduleId: (dataObj['module_id'] as string) ?? moduleId,
70
- description: dataObj['description'] as string,
71
- inputSchema: dataObj['input_schema'] as Record<string, unknown>,
72
- outputSchema: dataObj['output_schema'] as Record<string, unknown>,
73
- errorSchema: (dataObj['error_schema'] as Record<string, unknown>) ?? null,
74
- definitions,
75
- version: (dataObj['version'] as string) ?? '1.0.0',
76
- documentation: (dataObj['documentation'] as string) ?? null,
77
- schemaUrl: (dataObj['$schema'] as string) ?? null,
78
- };
79
-
80
- this._schemaCache.set(moduleId, sd);
81
- return sd;
82
- }
83
-
84
- resolve(schemaDef: SchemaDefinition): [ResolvedSchema, ResolvedSchema] {
85
- const resolvedInput = this._resolver.resolve(schemaDef.inputSchema);
86
- const resolvedOutput = this._resolver.resolve(schemaDef.outputSchema);
87
-
88
- const inputSchema = jsonSchemaToTypeBox(resolvedInput);
89
- const outputSchema = jsonSchemaToTypeBox(resolvedOutput);
90
-
91
- const inputRs: ResolvedSchema = {
92
- jsonSchema: resolvedInput,
93
- schema: inputSchema,
94
- moduleId: schemaDef.moduleId,
95
- direction: 'input',
96
- };
97
- const outputRs: ResolvedSchema = {
98
- jsonSchema: resolvedOutput,
99
- schema: outputSchema,
100
- moduleId: schemaDef.moduleId,
101
- direction: 'output',
102
- };
103
- return [inputRs, outputRs];
104
- }
105
-
106
- getSchema(
107
- moduleId: string,
108
- nativeInputSchema?: TSchema | null,
109
- nativeOutputSchema?: TSchema | null,
110
- ): [ResolvedSchema, ResolvedSchema] {
111
- const cached = this._modelCache.get(moduleId);
112
- if (cached) return cached;
113
-
114
- const strategyMap: Record<string, SchemaStrategy> = {
115
- yaml_first: SchemaStrategy.YamlFirst,
116
- native_first: SchemaStrategy.NativeFirst,
117
- yaml_only: SchemaStrategy.YamlOnly,
118
- };
119
- const rawStrategy = this._config.get('schema.strategy', 'yaml_first') as string;
120
- const strategy = strategyMap[rawStrategy] ?? SchemaStrategy.YamlFirst;
121
-
122
- let result: [ResolvedSchema, ResolvedSchema] | null = null;
123
-
124
- if (strategy === SchemaStrategy.YamlFirst) {
125
- try {
126
- result = this._loadAndResolve(moduleId);
127
- } catch (e) {
128
- if (e instanceof SchemaNotFoundError && nativeInputSchema && nativeOutputSchema) {
129
- result = this._wrapNative(moduleId, nativeInputSchema, nativeOutputSchema);
130
- } else {
131
- throw e;
132
- }
133
- }
134
- } else if (strategy === SchemaStrategy.NativeFirst) {
135
- if (nativeInputSchema && nativeOutputSchema) {
136
- result = this._wrapNative(moduleId, nativeInputSchema, nativeOutputSchema);
137
- } else {
138
- result = this._loadAndResolve(moduleId);
139
- }
140
- } else if (strategy === SchemaStrategy.YamlOnly) {
141
- result = this._loadAndResolve(moduleId);
142
- }
143
-
144
- if (result === null) {
145
- throw new SchemaNotFoundError(moduleId);
146
- }
147
-
148
- this._modelCache.set(moduleId, result);
149
- return result;
150
- }
151
-
152
- private _loadAndResolve(moduleId: string): [ResolvedSchema, ResolvedSchema] {
153
- const cached = this._modelCache.get(moduleId);
154
- if (cached) return cached;
155
- const sd = this.load(moduleId);
156
- const result = this.resolve(sd);
157
- this._modelCache.set(moduleId, result);
158
- return result;
159
- }
160
-
161
- private _wrapNative(
162
- moduleId: string,
163
- inputSchema: TSchema,
164
- outputSchema: TSchema,
165
- ): [ResolvedSchema, ResolvedSchema] {
166
- const inputRs: ResolvedSchema = {
167
- jsonSchema: inputSchema as unknown as Record<string, unknown>,
168
- schema: inputSchema,
169
- moduleId,
170
- direction: 'input',
171
- };
172
- const outputRs: ResolvedSchema = {
173
- jsonSchema: outputSchema as unknown as Record<string, unknown>,
174
- schema: outputSchema,
175
- moduleId,
176
- direction: 'output',
177
- };
178
- return [inputRs, outputRs];
179
- }
180
-
181
- clearCache(): void {
182
- this._schemaCache.clear();
183
- this._modelCache.clear();
184
- this._resolver.clearCache();
185
- }
186
- }
187
-
188
- /**
189
- * Convert a JSON Schema dict to a TypeBox TSchema.
190
- * Since TypeBox schemas ARE JSON Schema, this wraps the raw object
191
- * so it can be used with Value.Check/Value.Decode.
192
- */
193
- export function jsonSchemaToTypeBox(schema: Record<string, unknown>): TSchema {
194
- const schemaType = schema['type'] as string | undefined;
195
-
196
- let result: TSchema;
197
- if (schemaType === 'object') result = convertObjectSchema(schema);
198
- else if (schemaType === 'array') result = convertArraySchema(schema);
199
- else if (schemaType === 'string') result = convertStringSchema(schema);
200
- else if (schemaType === 'integer') result = convertNumericSchema(schema, Type.Integer);
201
- else if (schemaType === 'number') result = convertNumericSchema(schema, Type.Number);
202
- else if (schemaType === 'boolean') result = Type.Boolean();
203
- else if (schemaType === 'null') result = Type.Null();
204
- else result = convertCombinatorSchema(schema);
205
-
206
- // Preserve JSON Schema metadata
207
- if (typeof schema['description'] === 'string') result['description'] = schema['description'];
208
- if (typeof schema['title'] === 'string') result['title'] = schema['title'];
209
-
210
- return result;
211
- }
212
-
213
- function convertObjectSchema(schema: Record<string, unknown>): TSchema {
214
- const properties = schema['properties'] as Record<string, Record<string, unknown>> | undefined;
215
- const required = new Set((schema['required'] as string[]) ?? []);
216
-
217
- if (properties) {
218
- const typeboxProps: Record<string, TSchema> = {};
219
- for (const [name, propSchema] of Object.entries(properties)) {
220
- const propType = jsonSchemaToTypeBox(propSchema);
221
- typeboxProps[name] = required.has(name) ? propType : Type.Optional(propType);
222
- }
223
- return Type.Object(typeboxProps);
224
- }
225
- return Type.Record(Type.String(), Type.Unknown());
226
- }
227
-
228
- function convertArraySchema(schema: Record<string, unknown>): TSchema {
229
- const items = schema['items'] as Record<string, unknown> | undefined;
230
- return items ? Type.Array(jsonSchemaToTypeBox(items)) : Type.Array(Type.Unknown());
231
- }
232
-
233
- function convertStringSchema(schema: Record<string, unknown>): TSchema {
234
- const opts: Record<string, unknown> = {};
235
- for (const key of ['minLength', 'maxLength', 'pattern', 'format']) {
236
- if (key in schema) opts[key] = schema[key];
237
- }
238
- return Type.String(opts);
239
- }
240
-
241
- function convertNumericSchema(
242
- schema: Record<string, unknown>,
243
- factory: (opts?: Record<string, unknown>) => TSchema,
244
- ): TSchema {
245
- const opts: Record<string, unknown> = {};
246
- for (const key of ['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf']) {
247
- if (key in schema) opts[key] = schema[key];
248
- }
249
- return factory(opts);
250
- }
251
-
252
- function convertCombinatorSchema(schema: Record<string, unknown>): TSchema {
253
- if ('enum' in schema) {
254
- const values = schema['enum'] as unknown[];
255
- return Type.Union(values.map((v) =>
256
- v === null ? Type.Null() : Type.Literal(v as string | number | boolean),
257
- ));
258
- }
259
- if ('const' in schema) {
260
- const value = schema['const'];
261
- return value === null ? Type.Null() : Type.Literal(value as string | number | boolean);
262
- }
263
- if ('oneOf' in schema) {
264
- return Type.Union((schema['oneOf'] as Record<string, unknown>[]).map(jsonSchemaToTypeBox));
265
- }
266
- if ('anyOf' in schema) {
267
- return Type.Union((schema['anyOf'] as Record<string, unknown>[]).map(jsonSchemaToTypeBox));
268
- }
269
- if ('allOf' in schema) {
270
- return Type.Intersect((schema['allOf'] as Record<string, unknown>[]).map(jsonSchemaToTypeBox));
271
- }
272
- return Type.Unknown();
273
- }
@@ -1,244 +0,0 @@
1
- /**
2
- * $ref resolution for JSON Schema documents following Algorithm A05.
3
- */
4
-
5
- import { readFileSync, existsSync } from 'node:fs';
6
- import { resolve, dirname, join } from 'node:path';
7
- import yaml from 'js-yaml';
8
- import { SchemaCircularRefError, SchemaNotFoundError, SchemaParseError } from '../errors.js';
9
- import { deepCopy } from '../utils/index.js';
10
-
11
- const INLINE_SENTINEL = '__inline__';
12
-
13
- export class RefResolver {
14
- private _schemasDir: string;
15
- private _maxDepth: number;
16
- private _fileCache: Map<string, Record<string, unknown>> = new Map();
17
-
18
- constructor(schemasDir: string, maxDepth: number = 32) {
19
- this._schemasDir = resolve(schemasDir);
20
- this._maxDepth = maxDepth;
21
- }
22
-
23
- resolve(schema: Record<string, unknown>, currentFile?: string | null): Record<string, unknown> {
24
- const result = deepCopy(schema);
25
- this._fileCache.set(INLINE_SENTINEL, result);
26
- try {
27
- this._resolveNode(result, currentFile ?? null, new Set(), 0);
28
- } finally {
29
- this._fileCache.delete(INLINE_SENTINEL);
30
- }
31
- return result;
32
- }
33
-
34
- resolveRef(
35
- refString: string,
36
- currentFile: string | null,
37
- visitedRefs?: Set<string>,
38
- depth: number = 0,
39
- siblingKeys?: Record<string, unknown> | null,
40
- ): unknown {
41
- const visited = visitedRefs ?? new Set<string>();
42
-
43
- if (visited.has(refString)) {
44
- throw new SchemaCircularRefError(refString);
45
- }
46
-
47
- if (depth >= this._maxDepth) {
48
- throw new SchemaCircularRefError(
49
- `Maximum reference depth ${this._maxDepth} exceeded resolving: ${refString}`,
50
- );
51
- }
52
-
53
- visited.add(refString);
54
-
55
- const [filePath, jsonPointer] = this._parseRef(refString, currentFile);
56
- const document = this._loadFile(filePath);
57
- const target = this._resolveJsonPointer(document, jsonPointer, refString);
58
-
59
- let result: unknown = deepCopy(target);
60
-
61
- if (siblingKeys && typeof result === 'object' && result !== null && !Array.isArray(result)) {
62
- Object.assign(result as Record<string, unknown>, siblingKeys);
63
- }
64
-
65
- const effectiveFile = filePath === INLINE_SENTINEL ? currentFile : filePath;
66
-
67
- if (typeof result === 'object' && result !== null && !Array.isArray(result)) {
68
- const resultObj = result as Record<string, unknown>;
69
- if ('$ref' in resultObj) {
70
- const nestedRef = resultObj['$ref'] as string;
71
- delete resultObj['$ref'];
72
- const nestedSiblings = Object.keys(resultObj).length > 0 ? { ...resultObj } : null;
73
- result = this.resolveRef(nestedRef, effectiveFile, visited, depth + 1, nestedSiblings);
74
- }
75
- }
76
-
77
- this._resolveNode(result, effectiveFile, visited, depth + 1);
78
- return result;
79
- }
80
-
81
- private _resolveNode(
82
- node: unknown,
83
- currentFile: string | null,
84
- visitedRefs: Set<string>,
85
- depth: number,
86
- ): unknown {
87
- if (typeof node === 'object' && node !== null && !Array.isArray(node)) {
88
- const nodeObj = node as Record<string, unknown>;
89
- if ('$ref' in nodeObj) {
90
- const refString = nodeObj['$ref'] as string;
91
- const siblingKeys: Record<string, unknown> = {};
92
- for (const [k, v] of Object.entries(nodeObj)) {
93
- if (k !== '$ref') siblingKeys[k] = v;
94
- }
95
- const resolved = this.resolveRef(
96
- refString,
97
- currentFile,
98
- new Set(visitedRefs),
99
- depth,
100
- Object.keys(siblingKeys).length > 0 ? siblingKeys : null,
101
- );
102
- // Clear and replace
103
- for (const key of Object.keys(nodeObj)) delete nodeObj[key];
104
- if (typeof resolved === 'object' && resolved !== null && !Array.isArray(resolved)) {
105
- Object.assign(nodeObj, resolved as Record<string, unknown>);
106
- } else {
107
- return resolved;
108
- }
109
- } else {
110
- for (const key of Object.keys(nodeObj)) {
111
- const result = this._resolveNode(nodeObj[key], currentFile, visitedRefs, depth);
112
- if (result !== nodeObj[key]) {
113
- nodeObj[key] = result;
114
- }
115
- }
116
- }
117
- } else if (Array.isArray(node)) {
118
- for (let i = 0; i < node.length; i++) {
119
- const result = this._resolveNode(node[i], currentFile, visitedRefs, depth);
120
- if (result !== node[i]) {
121
- node[i] = result;
122
- }
123
- }
124
- }
125
- return node;
126
- }
127
-
128
- private _parseRef(refString: string, currentFile: string | null): [string, string] {
129
- if (refString.startsWith('#')) {
130
- const pointer = refString.slice(1);
131
- if (currentFile) return [currentFile, pointer];
132
- return [INLINE_SENTINEL, pointer];
133
- }
134
-
135
- if (refString.startsWith('apcore://')) {
136
- return this._convertCanonicalToPath(refString);
137
- }
138
-
139
- if (refString.includes('#')) {
140
- const [filePart, pointer] = refString.split('#', 2);
141
- const base = currentFile ? dirname(currentFile) : this._schemasDir;
142
- const resolvedPath = resolve(base, filePart);
143
- this._assertWithinSchemasDir(resolvedPath, refString);
144
- return [resolvedPath, pointer];
145
- }
146
-
147
- const base = currentFile ? dirname(currentFile) : this._schemasDir;
148
- const resolvedPath = resolve(base, refString);
149
- this._assertWithinSchemasDir(resolvedPath, refString);
150
- return [resolvedPath, ''];
151
- }
152
-
153
- private _assertWithinSchemasDir(resolvedPath: string, refString: string): void {
154
- if (!resolvedPath.startsWith(this._schemasDir + '/') && resolvedPath !== this._schemasDir) {
155
- throw new SchemaNotFoundError(
156
- `Reference '${refString}' resolves outside schemas directory`,
157
- );
158
- }
159
- }
160
-
161
- private _convertCanonicalToPath(uri: string): [string, string] {
162
- const remainder = uri.slice('apcore://'.length);
163
- const parts = remainder.split('/');
164
- const canonicalId = parts[0];
165
- const pointerParts = parts.slice(1);
166
-
167
- const fileRel = canonicalId.replace(/\./g, '/') + '.schema.yaml';
168
- const filePath = resolve(this._schemasDir, fileRel);
169
-
170
- const pointer = pointerParts.length > 0 ? '/' + pointerParts.join('/') : '';
171
- return [filePath, pointer];
172
- }
173
-
174
- private _resolveJsonPointer(document: unknown, pointer: string, refString: string): unknown {
175
- if (!pointer) return document;
176
-
177
- let segments = pointer.split('/');
178
- if (segments.length > 0 && segments[0] === '') {
179
- segments = segments.slice(1);
180
- }
181
-
182
- let current = document;
183
- for (const rawSegment of segments) {
184
- const segment = rawSegment.replace(/~1/g, '/').replace(/~0/g, '~');
185
- if (typeof current === 'object' && current !== null && !Array.isArray(current)) {
186
- const obj = current as Record<string, unknown>;
187
- if (segment in obj) {
188
- current = obj[segment];
189
- } else {
190
- throw new SchemaNotFoundError(`${refString} (segment '${segment}' not found)`);
191
- }
192
- } else {
193
- throw new SchemaNotFoundError(`${refString} (segment '${segment}' not found)`);
194
- }
195
- }
196
- return current;
197
- }
198
-
199
- private _loadFile(filePath: string): Record<string, unknown> {
200
- if (filePath === INLINE_SENTINEL) {
201
- return this._fileCache.get(INLINE_SENTINEL) ?? {};
202
- }
203
-
204
- const resolved = resolve(filePath);
205
- const cached = this._fileCache.get(resolved);
206
- if (cached !== undefined) return cached;
207
-
208
- if (!existsSync(resolved)) {
209
- throw new SchemaNotFoundError(resolved);
210
- }
211
-
212
- const content = readFileSync(resolved, 'utf-8');
213
- if (!content.trim()) {
214
- this._fileCache.set(resolved, {});
215
- return {};
216
- }
217
-
218
- let parsed: unknown;
219
- try {
220
- parsed = yaml.load(content);
221
- } catch (e) {
222
- throw new SchemaParseError(`Invalid YAML in ${resolved}: ${e}`);
223
- }
224
-
225
- if (parsed === null || parsed === undefined) {
226
- this._fileCache.set(resolved, {});
227
- return {};
228
- }
229
-
230
- if (typeof parsed !== 'object' || Array.isArray(parsed)) {
231
- throw new SchemaParseError(
232
- `Schema file ${resolved} must be a YAML mapping, got ${typeof parsed}`,
233
- );
234
- }
235
-
236
- const result = parsed as Record<string, unknown>;
237
- this._fileCache.set(resolved, result);
238
- return result;
239
- }
240
-
241
- clearCache(): void {
242
- this._fileCache.clear();
243
- }
244
- }
@@ -1,136 +0,0 @@
1
- /**
2
- * Strict mode conversion for JSON Schemas (Algorithm A23).
3
- */
4
-
5
- import { deepCopy } from '../utils/index.js';
6
-
7
- export function toStrictSchema(schema: Record<string, unknown>): Record<string, unknown> {
8
- const result = deepCopy(schema);
9
- stripExtensions(result);
10
- convertToStrict(result);
11
- return result;
12
- }
13
-
14
- export function applyLlmDescriptions(node: unknown): void {
15
- if (typeof node !== 'object' || node === null || Array.isArray(node)) return;
16
-
17
- const obj = node as Record<string, unknown>;
18
- if ('x-llm-description' in obj) {
19
- obj['description'] = obj['x-llm-description'];
20
- }
21
-
22
- if ('properties' in obj && typeof obj['properties'] === 'object' && obj['properties'] !== null) {
23
- for (const prop of Object.values(obj['properties'] as Record<string, unknown>)) {
24
- applyLlmDescriptions(prop);
25
- }
26
- }
27
- if ('items' in obj && typeof obj['items'] === 'object') {
28
- applyLlmDescriptions(obj['items']);
29
- }
30
- for (const keyword of ['oneOf', 'anyOf', 'allOf']) {
31
- if (keyword in obj && Array.isArray(obj[keyword])) {
32
- for (const sub of obj[keyword] as unknown[]) {
33
- applyLlmDescriptions(sub);
34
- }
35
- }
36
- }
37
- for (const defsKey of ['definitions', '$defs']) {
38
- if (defsKey in obj && typeof obj[defsKey] === 'object' && obj[defsKey] !== null) {
39
- for (const defn of Object.values(obj[defsKey] as Record<string, unknown>)) {
40
- applyLlmDescriptions(defn);
41
- }
42
- }
43
- }
44
- }
45
-
46
- export function stripExtensions(node: unknown): void {
47
- if (typeof node !== 'object' || node === null || Array.isArray(node)) return;
48
-
49
- const obj = node as Record<string, unknown>;
50
- const keysToRemove = Object.keys(obj).filter(
51
- (k) => (typeof k === 'string' && k.startsWith('x-')) || k === 'default',
52
- );
53
- for (const k of keysToRemove) {
54
- delete obj[k];
55
- }
56
-
57
- for (const value of Object.values(obj)) {
58
- if (typeof value === 'object' && value !== null) {
59
- if (Array.isArray(value)) {
60
- for (const item of value) {
61
- if (typeof item === 'object' && item !== null) {
62
- stripExtensions(item);
63
- }
64
- }
65
- } else {
66
- stripExtensions(value);
67
- }
68
- }
69
- }
70
- }
71
-
72
- function convertToStrict(node: unknown): void {
73
- if (typeof node !== 'object' || node === null || Array.isArray(node)) return;
74
-
75
- const obj = node as Record<string, unknown>;
76
-
77
- if (obj['type'] === 'object' && 'properties' in obj) {
78
- obj['additionalProperties'] = false;
79
- const existingRequired = new Set(
80
- Array.isArray(obj['required']) ? (obj['required'] as string[]) : [],
81
- );
82
- const properties = obj['properties'] as Record<string, unknown>;
83
- const allNames = Object.keys(properties);
84
- const optionalNames = allNames.filter((n) => !existingRequired.has(n));
85
-
86
- for (const name of optionalNames) {
87
- const prop = properties[name] as Record<string, unknown>;
88
- if ('type' in prop) {
89
- if (typeof prop['type'] === 'string') {
90
- prop['type'] = [prop['type'], 'null'];
91
- } else if (Array.isArray(prop['type'])) {
92
- if (!(prop['type'] as string[]).includes('null')) {
93
- (prop['type'] as string[]).push('null');
94
- }
95
- }
96
- } else if ('oneOf' in prop && Array.isArray(prop['oneOf'])) {
97
- const variants = prop['oneOf'] as Record<string, unknown>[];
98
- if (!variants.some((v) => v['type'] === 'null')) {
99
- variants.push({ type: 'null' });
100
- }
101
- } else if ('anyOf' in prop && Array.isArray(prop['anyOf'])) {
102
- const variants = prop['anyOf'] as Record<string, unknown>[];
103
- if (!variants.some((v) => v['type'] === 'null')) {
104
- variants.push({ type: 'null' });
105
- }
106
- } else {
107
- properties[name] = { oneOf: [prop, { type: 'null' }] };
108
- }
109
- }
110
-
111
- obj['required'] = [...allNames].sort();
112
- }
113
-
114
- if ('properties' in obj && typeof obj['properties'] === 'object' && obj['properties'] !== null) {
115
- for (const prop of Object.values(obj['properties'] as Record<string, unknown>)) {
116
- convertToStrict(prop);
117
- }
118
- }
119
- if ('items' in obj && typeof obj['items'] === 'object') {
120
- convertToStrict(obj['items']);
121
- }
122
- for (const keyword of ['oneOf', 'anyOf', 'allOf']) {
123
- if (keyword in obj && Array.isArray(obj[keyword])) {
124
- for (const sub of obj[keyword] as unknown[]) {
125
- convertToStrict(sub);
126
- }
127
- }
128
- }
129
- for (const defsKey of ['definitions', '$defs']) {
130
- if (defsKey in obj && typeof obj[defsKey] === 'object' && obj[defsKey] !== null) {
131
- for (const defn of Object.values(obj[defsKey] as Record<string, unknown>)) {
132
- convertToStrict(defn);
133
- }
134
- }
135
- }
136
- }