@devilsdev/rag-pipeline-utils 2.3.1 → 2.4.1

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 (160) hide show
  1. package/README.md +94 -480
  2. package/contracts/loader-contract.json +11 -6
  3. package/contracts/reranker-contract.json +18 -26
  4. package/dist/index.cjs +21190 -47
  5. package/dist/index.d.ts +298 -68
  6. package/dist/index.mjs +9 -76
  7. package/package.json +37 -11
  8. package/src/agentic/agentic-pipeline.js +235 -0
  9. package/src/agentic/iterative-retriever.js +213 -0
  10. package/src/agentic/query-planner.js +208 -0
  11. package/src/agentic/self-critique.js +102 -0
  12. package/src/ai/adaptive-retrieval.js +0 -3
  13. package/src/ai/federated-learning.js +0 -3
  14. package/src/ai/federation.js +1 -6
  15. package/src/ai/index.js +9 -20
  16. package/src/ai/model-training.js +0 -3
  17. package/src/ai/multimodal-processing.js +0 -3
  18. package/src/ai/multimodal.js +1 -6
  19. package/src/ai/orchestrator.js +1 -6
  20. package/src/ai/retrieval-engine.js +1 -6
  21. package/src/chunking/chunking-engine.js +142 -0
  22. package/src/chunking/strategies/fixed-size.js +54 -0
  23. package/src/chunking/strategies/recursive.js +127 -0
  24. package/src/chunking/strategies/semantic.js +128 -0
  25. package/src/chunking/strategies/sentence.js +32 -0
  26. package/src/chunking/strategies/structure-aware.js +138 -0
  27. package/src/citation/citation-tracker.js +161 -0
  28. package/src/citation/hallucination-detector.js +74 -0
  29. package/src/citation/source-mapper.js +95 -0
  30. package/src/cli/commands/ai-ml/adaptive-commands.js +178 -0
  31. package/src/cli/commands/ai-ml/federated-commands.js +207 -0
  32. package/src/cli/commands/ai-ml/index.js +17 -0
  33. package/src/cli/commands/ai-ml/multimodal-commands.js +187 -0
  34. package/src/cli/commands/ai-ml/shared.js +51 -0
  35. package/src/cli/commands/ai-ml/training-commands.js +228 -0
  36. package/src/cli/commands/ai-ml.js +176 -757
  37. package/src/cli/commands/plugin-hub/certification-commands.js +221 -0
  38. package/src/cli/commands/plugin-hub/event-handlers.js +64 -0
  39. package/src/cli/commands/plugin-hub/hub-commands.js +290 -0
  40. package/src/cli/commands/plugin-hub/review-commands.js +78 -0
  41. package/src/cli/commands/plugin-hub.js +106 -782
  42. package/src/cli/diagnostics/config-checker.js +81 -0
  43. package/src/cli/diagnostics/dependency-checker.js +69 -0
  44. package/src/cli/diagnostics/environment-checker.js +45 -0
  45. package/src/cli/diagnostics/performance-checker.js +51 -0
  46. package/src/cli/diagnostics/plugin-checker.js +106 -0
  47. package/src/cli/diagnostics/security-checker.js +61 -0
  48. package/src/cli/doctor-command.js +70 -369
  49. package/src/cli/enhanced-cli-commands.js +162 -706
  50. package/src/cli/handlers/config-handler.js +126 -0
  51. package/src/cli/handlers/diagnostics-handler.js +113 -0
  52. package/src/cli/handlers/ingest-handler.js +42 -0
  53. package/src/cli/handlers/init-handler.js +51 -0
  54. package/src/cli/handlers/query-handler.js +45 -0
  55. package/src/cli/handlers/run-handler.js +181 -0
  56. package/src/cli/interactive-wizard.js +99 -723
  57. package/src/cli/shared/cli-utils.js +89 -0
  58. package/src/cli/wizard/configuration.js +148 -0
  59. package/src/cli/wizard/observability.js +79 -0
  60. package/src/cli/wizard/performance.js +76 -0
  61. package/src/cli/wizard/plugin-selection.js +297 -0
  62. package/src/cli/wizard/preview-save.js +172 -0
  63. package/src/cli/wizard/project-setup.js +66 -0
  64. package/src/config/memory-optimization.js +3 -3
  65. package/src/connectors/anthropic-connector.js +179 -0
  66. package/src/connectors/base-connector.js +94 -0
  67. package/src/connectors/cohere-connector.js +143 -0
  68. package/src/connectors/local-embedder.js +171 -0
  69. package/src/connectors/memory-retriever.js +150 -0
  70. package/src/connectors/ollama-connector.js +205 -0
  71. package/src/connectors/openai-connector.js +173 -0
  72. package/src/core/create-pipeline.js +21 -1
  73. package/src/core/observability/tracing.js +2 -1
  74. package/src/core/pipeline-factory.js +0 -1
  75. package/src/core/plugin-registry.js +14 -14
  76. package/src/cost/cost-calculator.js +146 -0
  77. package/src/cost/cost-tracker.js +260 -0
  78. package/src/cost/token-budget.js +245 -0
  79. package/src/dag/core/execution-scheduler.js +2 -1
  80. package/src/dag/core/topology-validation.js +0 -3
  81. package/src/dag/dag-engine.js +3 -5
  82. package/src/dag/dag-node.js +0 -1
  83. package/src/dag/enhanced-dag-engine.js +171 -99
  84. package/src/dashboard/dashboard-generator.js +642 -0
  85. package/src/dashboard/metrics-aggregator.js +409 -0
  86. package/src/debug/execution-tracer.js +210 -0
  87. package/src/debug/trace-inspector.js +281 -0
  88. package/src/dev/dev-server.js +5 -5
  89. package/src/dev/hot-reload.js +3 -2
  90. package/src/dx/integration-templates.js +0 -3
  91. package/src/ecosystem/plugin-analytics-dashboard.js +2 -2
  92. package/src/ecosystem/plugin-hub.js +2 -2
  93. package/src/enterprise/audit-logging.js +2 -2
  94. package/src/enterprise/sso-integration.js +52 -32
  95. package/src/evaluate/context-metrics.js +127 -0
  96. package/src/evaluate/evaluator.js +4 -2
  97. package/src/evaluate/faithfulness.js +117 -0
  98. package/src/evaluate/groundedness.js +60 -0
  99. package/src/evaluate/pipeline-evaluator.js +156 -0
  100. package/src/evaluate/relevance.js +129 -0
  101. package/src/evaluate/scoring.js +27 -0
  102. package/src/graph/entity-extractor.js +183 -0
  103. package/src/graph/graph-index.js +113 -0
  104. package/src/graph/graph-retriever.js +244 -0
  105. package/src/graph/knowledge-graph.js +256 -0
  106. package/src/guardrails/guardrails-pipeline.js +136 -0
  107. package/src/guardrails/post-generation-guard.js +170 -0
  108. package/src/guardrails/pre-retrieval-guard.js +161 -0
  109. package/src/guardrails/retrieval-guard.js +126 -0
  110. package/src/index.js +255 -9
  111. package/src/loader/html-loader.js +4 -15
  112. package/src/loader/markdown-loader.js +4 -15
  113. package/src/mcp/mcp-server.js +199 -0
  114. package/src/mcp/mcp-tool-builder.js +121 -0
  115. package/src/observability/audit-logger.js +0 -2
  116. package/src/observability/event-logger.js +2 -1
  117. package/src/observability/security-monitor.js +0 -2
  118. package/src/observability/telemetry.js +0 -2
  119. package/src/reranker/cascade-reranker.js +79 -0
  120. package/src/reranker/embedding-reranker.js +124 -0
  121. package/src/reranker/llm-reranker.js +6 -3
  122. package/src/reranker/scoring-reranker.js +123 -0
  123. package/src/retrieval/bm25-search.js +157 -0
  124. package/src/retrieval/hybrid-retriever.js +111 -0
  125. package/src/retrieval/rank-fusion.js +62 -0
  126. package/src/security/jwt-config.js +4 -3
  127. package/src/security/jwt-validator.js +2 -1
  128. package/src/security/plugin-sandbox.js +0 -3
  129. package/src/security/plugin-signature-verifier.js +4 -6
  130. package/src/security/validator.js +0 -2
  131. package/src/streaming/embedding-stream.js +197 -0
  132. package/src/streaming/sse-adapter.js +168 -0
  133. package/src/streaming/stream-router.js +210 -0
  134. package/src/streaming/streaming-embedder.js +231 -0
  135. package/src/streaming/websocket-adapter.js +171 -0
  136. package/src/templates/scaffold.js +147 -0
  137. package/src/templates/template-registry.js +272 -0
  138. package/src/utils/contract-validator.js +2 -1
  139. package/src/utils/input-sanitizer.js +80 -99
  140. package/src/utils/performance-monitor.js +0 -3
  141. package/src/utils/plugin-scaffolder.js +9 -16
  142. package/src/utils/rate-limiter.js +0 -1
  143. package/src/utils/retry-policy.js +0 -3
  144. package/src/utils/safe-expression-evaluator.js +0 -3
  145. package/src/utils/secure-logger-config.js +2 -4
  146. package/src/utils/secure-logging.js +0 -3
  147. package/src/utils/structured-logger.js +0 -3
  148. package/src/ai/index-fixed.js +0 -509
  149. package/src/ai/module-template.js +0 -37
  150. package/src/ci/workflow-analyzer.js +0 -71
  151. package/src/cli/plugin-marketplace-commands.js +0 -869
  152. package/src/dev/README.md +0 -126
  153. package/src/dev/examples/hot-reload-usage.js +0 -355
  154. package/src/mocks/openai-embedder.js +0 -119
  155. package/src/mocks/openai-llm.js +0 -77
  156. package/src/mocks/pdf-loader.js +0 -21
  157. package/src/mocks/pinecone-retriever.js +0 -106
  158. package/src/scripts/script-utilities.js +0 -36
  159. package/src/utils/ci/diagnostic-reporter.js +0 -57
  160. package/src/utils/examples/error-formatter-usage.js +0 -351
@@ -1,106 +0,0 @@
1
- /**
2
- * Version: 0.1.0
3
- * File: /src/mocks/pinecone-retriever.js
4
- * Description: Mock implementation of a Pinecone retriever
5
- * Author: Ali Kahwaji
6
- */
7
-
8
- class PineconeRetriever {
9
- constructor(options = {}) {
10
- this.options = options;
11
- this.storage = [];
12
-
13
- // Configurable batch size from environment or options
14
- this.batchSize =
15
- parseInt(process.env.RAG_RETRIEVER_BATCH_SIZE) ||
16
- options.batchSize ||
17
- 1000; // Default batch size for Pinecone
18
- }
19
-
20
- /**
21
- * Mocks vector storage with batch processing
22
- * @param {Array} vectors - Vectors to store
23
- */
24
- async store(vectors = []) {
25
- if (!Array.isArray(vectors) || vectors.length === 0) {
26
- return true;
27
- }
28
-
29
- // Process storage in batches for better memory management
30
- for (let i = 0; i < vectors.length; i += this.batchSize) {
31
- const batch = vectors.slice(i, i + this.batchSize);
32
- this.storage.push(...batch);
33
-
34
- // Optional progress callback
35
- if (this.options.onProgress) {
36
- this.options.onProgress({
37
- processed: Math.min(i + this.batchSize, vectors.length),
38
- total: vectors.length,
39
- stage: "storing",
40
- });
41
- }
42
-
43
- // Simulate network delay for large batches
44
- if (vectors.length > this.batchSize) {
45
- await new Promise((resolve) => setTimeout(resolve, 20));
46
- }
47
- }
48
-
49
- return true;
50
- }
51
-
52
- /**
53
- * Returns mock retrieved documents with batch processing for large result sets
54
- * @param {Array} queryVector - Query vector
55
- * @param {number} k - Number of results to return
56
- * @returns {Promise<Array<{ id: string, text: string, metadata: object }>>}
57
- */
58
- async retrieve(queryVector = [], k = 5) {
59
- const mockResults = [
60
- { id: "a", text: "Chunk about pine trees", metadata: {} },
61
- { id: "b", text: "Chunk about vectors", metadata: {} },
62
- { id: "c", text: "Chunk about databases", metadata: {} },
63
- { id: "d", text: "Chunk about machine learning", metadata: {} },
64
- { id: "e", text: "Chunk about embeddings", metadata: {} },
65
- ];
66
-
67
- // Extend mock results for large k values
68
- const results = [];
69
- for (let i = 0; i < k; i++) {
70
- const baseResult = mockResults[i % mockResults.length];
71
- results.push({
72
- ...baseResult,
73
- id: `${baseResult.id}_${Math.floor(i / mockResults.length)}`,
74
- text: `${baseResult.text} (result ${i + 1})`,
75
- });
76
- }
77
-
78
- // For large result sets, process in batches
79
- if (k > this.batchSize) {
80
- const batchedResults = [];
81
- for (let i = 0; i < results.length; i += this.batchSize) {
82
- const batch = results.slice(i, i + this.batchSize);
83
- batchedResults.push(...batch);
84
-
85
- // Optional progress callback
86
- if (this.options.onProgress) {
87
- this.options.onProgress({
88
- processed: Math.min(i + this.batchSize, results.length),
89
- total: results.length,
90
- stage: "retrieving",
91
- });
92
- }
93
-
94
- // Simulate network delay for large retrievals
95
- await new Promise((resolve) => setTimeout(resolve, 10));
96
- }
97
- return batchedResults;
98
- }
99
-
100
- return results;
101
- }
102
- }
103
-
104
- // Default export
105
-
106
- module.exports = PineconeRetriever;
@@ -1,36 +0,0 @@
1
- // src/scripts/script-utilities.js
2
-
3
- // default sleeper uses real timers (prod) - unref'd to not block process exit
4
- const sleep = (ms) =>
5
- new Promise((resolve) => {
6
- const t = setTimeout(resolve, ms);
7
- // critical: don't keep the process alive just because of a timer
8
- if (typeof t.unref === "function") t.unref();
9
- });
10
-
11
- async function retry(fn, opts = {}) {
12
- const {
13
- retries = 3,
14
- baseDelay = 100,
15
- factor = 2,
16
- onDelay = () => {},
17
- sleeper = sleep, // <-- inject for tests
18
- } = opts;
19
-
20
- let lastErr;
21
- for (let attempt = 0; attempt <= retries; attempt++) {
22
- try {
23
- // pass attempt if useful for logging/logic
24
- return await fn(attempt);
25
- } catch (err) {
26
- lastErr = err;
27
- if (attempt === retries) break;
28
- const delay = baseDelay * Math.pow(factor, attempt);
29
- onDelay(delay, attempt);
30
- await sleeper(delay); // <-- no-op in tests
31
- }
32
- }
33
- throw lastErr;
34
- }
35
-
36
- module.exports = { retry, sleep };
@@ -1,57 +0,0 @@
1
- /**
2
- * Version: 1.0.0
3
- * Description: Enhanced CI diagnostics for plugin mock verification
4
- * Author: Ali Kahwaji
5
- */
6
-
7
- const path = require('path');
8
- // eslint-disable-line global-require
9
- const chalk = require('chalk');
10
- // eslint-disable-line global-require
11
-
12
- /**
13
- * Pretty prints CI validation errors and guidance
14
- * @param {Array<{ file: string, missing: string[] }>} failures
15
- */
16
- function reportPluginValidationFailures(failures) {
17
- if (!failures.length) return;
18
-
19
- console.log(`\n${chalk.redBright.bold('❌ Plugin Mock Validation Failed')}`);
20
- // eslint-disable-line no-console
21
-
22
- failures.forEach(({ file, missing }) => {
23
- const fileName = path.basename(file);
24
- console.log(
25
- // eslint-disable-line no-console
26
- `${chalk.red(` ✖ ${fileName}`)} ${chalk.gray(`missing: ${missing.join(', ')}`)}`,
27
- );
28
-
29
- // Add method-level fix hints
30
- missing.forEach((method) => {
31
- const pluginType = fileName.split('.')[0].split('-')[1] || 'unknown';
32
- console.error(
33
- ` → Fix: implement method ${chalk.cyan(`${method}()`)} for plugin _type ${chalk.yellow(pluginType)}`,
34
- );
35
- // eslint-disable-line no-console
36
- });
37
- });
38
-
39
- console.log(`\n${chalk.yellowBright('Recommended Fixes:')}`);
40
- // eslint-disable-line no-console
41
- console.log(
42
- ' • Implement all required methods defined in /src/core/plugin-contracts.js',
43
- );
44
- // eslint-disable-line no-console
45
- console.log(` • Re-run: ${chalk.cyan('npm run ci')} to confirm validation`);
46
- // eslint-disable-line no-console
47
- console.log(
48
- ` • Optionally use: ${chalk.cyan('scripts/repair-fixtures.js')} to auto-repair mocks\n`,
49
- );
50
- // eslint-disable-line no-console
51
- }
52
-
53
- // Default export
54
-
55
- module.exports = {
56
- reportPluginValidationFailures,
57
- };
@@ -1,351 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * Error Formatter Usage Examples
5
- *
6
- * Demonstrates how to use the enhanced error formatter
7
- * throughout the codebase
8
- */
9
-
10
- const {
11
- createError,
12
- wrapError,
13
- formatErrorMessage,
14
- logError,
15
- ERROR_CODES,
16
- } = require('../error-formatter');
17
-
18
- // ============================================================================
19
- // Example 1: Basic Error Creation
20
- // ============================================================================
21
-
22
- function basicErrorExample() {
23
- console.log('\n=== Example 1: Basic Error Creation ===\n');
24
-
25
- try {
26
- throw createError(ERROR_CODES.CONFIG_NOT_FOUND, {
27
- path: '.ragrc.json',
28
- });
29
- } catch (error) {
30
- console.log(formatErrorMessage(error));
31
- }
32
- }
33
-
34
- // ============================================================================
35
- // Example 2: Error with Rich Context
36
- // ============================================================================
37
-
38
- function richContextExample() {
39
- console.log('\n=== Example 2: Error with Rich Context ===\n');
40
-
41
- try {
42
- const input = { invalid: 'data' };
43
-
44
- throw createError(ERROR_CODES.PLUGIN_EXECUTION_FAILED, {
45
- plugin: 'embedder-openai',
46
- reason: 'Invalid API key',
47
- input: JSON.stringify(input),
48
- details: 'Check your OPENAI_API_KEY environment variable',
49
- });
50
- } catch (error) {
51
- console.log(
52
- formatErrorMessage(error, {
53
- includeContext: true,
54
- includeSuggestions: true,
55
- includeDocumentation: true,
56
- }),
57
- );
58
- }
59
- }
60
-
61
- // ============================================================================
62
- // Example 3: Wrapping Existing Errors
63
- // ============================================================================
64
-
65
- function wrapErrorExample() {
66
- console.log('\n=== Example 3: Wrapping Existing Errors ===\n');
67
-
68
- try {
69
- try {
70
- // Simulate file read error
71
- throw new Error('ENOENT: no such file or directory');
72
- } catch (originalError) {
73
- throw wrapError(originalError, ERROR_CODES.FS_FILE_NOT_FOUND, {
74
- path: '/path/to/config.json',
75
- });
76
- }
77
- } catch (error) {
78
- console.log(
79
- formatErrorMessage(error, {
80
- includeStack: false,
81
- }),
82
- );
83
- }
84
- }
85
-
86
- // ============================================================================
87
- // Example 4: Configuration Errors
88
- // ============================================================================
89
-
90
- function configErrorExample() {
91
- console.log('\n=== Example 4: Configuration Errors ===\n');
92
-
93
- try {
94
- throw createError(ERROR_CODES.CONFIG_INVALID_TYPE, {
95
- field: 'pipeline.stages',
96
- expected: 'array',
97
- actual: 'string',
98
- currentValue: '"fetch,process,store"',
99
- });
100
- } catch (error) {
101
- console.log(formatErrorMessage(error));
102
- }
103
- }
104
-
105
- // ============================================================================
106
- // Example 5: Plugin Contract Violation
107
- // ============================================================================
108
-
109
- function pluginContractExample() {
110
- console.log('\n=== Example 5: Plugin Contract Violation ===\n');
111
-
112
- try {
113
- throw createError(ERROR_CODES.PLUGIN_CONTRACT_VIOLATION, {
114
- plugin: 'my-custom-plugin',
115
- violation: 'Missing execute() method',
116
- missingMethod: 'execute',
117
- expectedType: 'function',
118
- });
119
- } catch (error) {
120
- console.log(formatErrorMessage(error));
121
- }
122
- }
123
-
124
- // ============================================================================
125
- // Example 6: Pipeline Execution Error
126
- // ============================================================================
127
-
128
- function pipelineErrorExample() {
129
- console.log('\n=== Example 6: Pipeline Execution Error ===\n');
130
-
131
- try {
132
- throw createError(ERROR_CODES.PIPELINE_STAGE_FAILED, {
133
- stage: 'embedding',
134
- reason: 'API rate limit exceeded',
135
- input: JSON.stringify({ text: 'Sample text...' }).slice(0, 50),
136
- });
137
- } catch (error) {
138
- // Log with appropriate severity
139
- logError(error);
140
- }
141
- }
142
-
143
- // ============================================================================
144
- // Example 7: Validation Error with Multiple Issues
145
- // ============================================================================
146
-
147
- function validationErrorExample() {
148
- console.log('\n=== Example 7: Validation Error ===\n');
149
-
150
- try {
151
- const errors = [
152
- { field: 'metadata.name', message: 'Required field missing' },
153
- { field: 'pipeline.stages', message: 'Must be an array' },
154
- ];
155
-
156
- throw createError(ERROR_CODES.VALIDATION_FAILED, {
157
- reason: 'Configuration validation failed',
158
- errors: JSON.stringify(errors, null, 2),
159
- });
160
- } catch (error) {
161
- console.log(
162
- formatErrorMessage(error, {
163
- includeContext: true,
164
- }),
165
- );
166
- }
167
- }
168
-
169
- // ============================================================================
170
- // Example 8: Hot Reload Error
171
- // ============================================================================
172
-
173
- function hotReloadErrorExample() {
174
- console.log('\n=== Example 8: Hot Reload Error ===\n');
175
-
176
- try {
177
- throw createError(ERROR_CODES.HOT_RELOAD_FAILED, {
178
- path: './src/plugins/my-plugin.js',
179
- reason: 'SyntaxError: Unexpected token',
180
- watchPaths: './src/plugins, ./src/mocks',
181
- });
182
- } catch (error) {
183
- console.log(formatErrorMessage(error));
184
- }
185
- }
186
-
187
- // ============================================================================
188
- // Example 9: DAG Cycle Detection
189
- // ============================================================================
190
-
191
- function dagCycleExample() {
192
- console.log('\n=== Example 9: DAG Cycle Detection ===\n');
193
-
194
- try {
195
- throw createError(ERROR_CODES.DAG_CYCLE_DETECTED, {
196
- cycle: 'A -> B -> C -> A',
197
- });
198
- } catch (error) {
199
- console.log(formatErrorMessage(error));
200
- }
201
- }
202
-
203
- // ============================================================================
204
- // Example 10: Authentication Error
205
- // ============================================================================
206
-
207
- function authErrorExample() {
208
- console.log('\n=== Example 10: Authentication Error ===\n');
209
-
210
- try {
211
- throw createError(ERROR_CODES.AUTH_TOKEN_EXPIRED, {
212
- expiredAt: new Date(Date.now() - 3600000).toISOString(),
213
- });
214
- } catch (error) {
215
- console.log(formatErrorMessage(error));
216
- }
217
- }
218
-
219
- // ============================================================================
220
- // Example 11: Custom Error Handling in Try-Catch
221
- // ============================================================================
222
-
223
- async function asyncErrorHandlingExample() {
224
- console.log('\n=== Example 11: Async Error Handling ===\n');
225
-
226
- async function loadPlugin(name) {
227
- // Simulate plugin loading
228
- throw new Error(`Cannot find module '${name}'`);
229
- }
230
-
231
- try {
232
- await loadPlugin('@rag-pipeline/embedder-openai');
233
- } catch (error) {
234
- const enhanced = wrapError(error, ERROR_CODES.PLUGIN_LOAD_FAILED, {
235
- plugin: '@rag-pipeline/embedder-openai',
236
- path: './node_modules/@rag-pipeline/embedder-openai',
237
- reason: error.message,
238
- });
239
-
240
- console.log(formatErrorMessage(enhanced));
241
- }
242
- }
243
-
244
- // ============================================================================
245
- // Example 12: Error Serialization for Logging
246
- // ============================================================================
247
-
248
- function serializationExample() {
249
- console.log('\n=== Example 12: Error Serialization ===\n');
250
-
251
- try {
252
- throw createError(ERROR_CODES.PLUGIN_NOT_FOUND, {
253
- plugin: 'my-plugin',
254
- path: './plugins/my-plugin.js',
255
- });
256
- } catch (error) {
257
- // Serialize for logging to external service
258
- const serialized = error.toJSON();
259
- console.log(JSON.stringify(serialized, null, 2));
260
- }
261
- }
262
-
263
- // ============================================================================
264
- // Example 13: Custom Error Formatting
265
- // ============================================================================
266
-
267
- function customFormattingExample() {
268
- console.log('\n=== Example 13: Custom Formatting ===\n');
269
-
270
- try {
271
- throw createError(ERROR_CODES.CONFIG_VALIDATION_FAILED, {
272
- reason: 'Invalid schema',
273
- requiredFields: 'metadata.name, pipeline.stages',
274
- });
275
- } catch (error) {
276
- // Minimal format for CI logs
277
- console.log('CI Format:');
278
- console.log(
279
- formatErrorMessage(error, {
280
- includeCode: true,
281
- includeSuggestions: false,
282
- includeDocumentation: false,
283
- includeStack: false,
284
- }),
285
- );
286
-
287
- console.log('\n---\n');
288
-
289
- // Detailed format for debugging
290
- console.log('Debug Format:');
291
- console.log(
292
- formatErrorMessage(error, {
293
- includeCode: true,
294
- includeSuggestions: true,
295
- includeDocumentation: true,
296
- includeContext: true,
297
- includeStack: true,
298
- }),
299
- );
300
- }
301
- }
302
-
303
- // ============================================================================
304
- // Run Examples
305
- // ============================================================================
306
-
307
- async function runAllExamples() {
308
- console.log('='.repeat(70));
309
- console.log('Error Formatter Usage Examples');
310
- console.log('='.repeat(70));
311
-
312
- basicErrorExample();
313
- richContextExample();
314
- wrapErrorExample();
315
- configErrorExample();
316
- pluginContractExample();
317
- pipelineErrorExample();
318
- validationErrorExample();
319
- hotReloadErrorExample();
320
- dagCycleExample();
321
- authErrorExample();
322
- await asyncErrorHandlingExample();
323
- serializationExample();
324
- customFormattingExample();
325
-
326
- console.log('\n' + '='.repeat(70));
327
- console.log('Examples Complete');
328
- console.log('='.repeat(70) + '\n');
329
- }
330
-
331
- // Run if executed directly
332
- if (require.main === module) {
333
- runAllExamples().catch(console.error);
334
- }
335
-
336
- module.exports = {
337
- basicErrorExample,
338
- richContextExample,
339
- wrapErrorExample,
340
- configErrorExample,
341
- pluginContractExample,
342
- pipelineErrorExample,
343
- validationErrorExample,
344
- hotReloadErrorExample,
345
- dagCycleExample,
346
- authErrorExample,
347
- asyncErrorHandlingExample,
348
- serializationExample,
349
- customFormattingExample,
350
- runAllExamples,
351
- };