@originals/sdk 1.8.1 → 1.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/dist/utils/hash.js +1 -0
  2. package/package.json +6 -5
  3. package/src/adapters/FeeOracleMock.ts +9 -0
  4. package/src/adapters/index.ts +5 -0
  5. package/src/adapters/providers/OrdHttpProvider.ts +126 -0
  6. package/src/adapters/providers/OrdMockProvider.ts +101 -0
  7. package/src/adapters/types.ts +66 -0
  8. package/src/bitcoin/BitcoinManager.ts +329 -0
  9. package/src/bitcoin/BroadcastClient.ts +54 -0
  10. package/src/bitcoin/OrdinalsClient.ts +120 -0
  11. package/src/bitcoin/PSBTBuilder.ts +106 -0
  12. package/src/bitcoin/fee-calculation.ts +38 -0
  13. package/src/bitcoin/providers/OrdNodeProvider.ts +92 -0
  14. package/src/bitcoin/providers/OrdinalsProvider.ts +56 -0
  15. package/src/bitcoin/providers/types.ts +59 -0
  16. package/src/bitcoin/transactions/commit.ts +465 -0
  17. package/src/bitcoin/transactions/index.ts +13 -0
  18. package/src/bitcoin/transfer.ts +43 -0
  19. package/src/bitcoin/utxo-selection.ts +322 -0
  20. package/src/bitcoin/utxo.ts +113 -0
  21. package/src/cel/ExternalReferenceManager.ts +87 -0
  22. package/src/cel/OriginalsCel.ts +460 -0
  23. package/src/cel/algorithms/createEventLog.ts +68 -0
  24. package/src/cel/algorithms/deactivateEventLog.ts +109 -0
  25. package/src/cel/algorithms/index.ts +11 -0
  26. package/src/cel/algorithms/updateEventLog.ts +99 -0
  27. package/src/cel/algorithms/verifyEventLog.ts +306 -0
  28. package/src/cel/algorithms/witnessEvent.ts +87 -0
  29. package/src/cel/cli/create.ts +330 -0
  30. package/src/cel/cli/index.ts +383 -0
  31. package/src/cel/cli/inspect.ts +549 -0
  32. package/src/cel/cli/migrate.ts +473 -0
  33. package/src/cel/cli/verify.ts +249 -0
  34. package/src/cel/hash.ts +71 -0
  35. package/src/cel/index.ts +16 -0
  36. package/src/cel/layers/BtcoCelManager.ts +408 -0
  37. package/src/cel/layers/PeerCelManager.ts +371 -0
  38. package/src/cel/layers/WebVHCelManager.ts +361 -0
  39. package/src/cel/layers/index.ts +27 -0
  40. package/src/cel/serialization/cbor.ts +189 -0
  41. package/src/cel/serialization/index.ts +10 -0
  42. package/src/cel/serialization/json.ts +209 -0
  43. package/src/cel/types.ts +160 -0
  44. package/src/cel/witnesses/BitcoinWitness.ts +184 -0
  45. package/src/cel/witnesses/HttpWitness.ts +241 -0
  46. package/src/cel/witnesses/WitnessService.ts +51 -0
  47. package/src/cel/witnesses/index.ts +11 -0
  48. package/src/contexts/credentials-v1.json +237 -0
  49. package/src/contexts/credentials-v2-examples.json +5 -0
  50. package/src/contexts/credentials-v2.json +340 -0
  51. package/src/contexts/credentials.json +237 -0
  52. package/src/contexts/data-integrity-v2.json +81 -0
  53. package/src/contexts/dids.json +58 -0
  54. package/src/contexts/ed255192020.json +93 -0
  55. package/src/contexts/ordinals-plus.json +23 -0
  56. package/src/contexts/originals.json +22 -0
  57. package/src/core/OriginalsSDK.ts +420 -0
  58. package/src/crypto/Multikey.ts +194 -0
  59. package/src/crypto/Signer.ts +262 -0
  60. package/src/crypto/noble-init.ts +138 -0
  61. package/src/did/BtcoDidResolver.ts +231 -0
  62. package/src/did/DIDManager.ts +705 -0
  63. package/src/did/Ed25519Verifier.ts +68 -0
  64. package/src/did/KeyManager.ts +239 -0
  65. package/src/did/WebVHManager.ts +499 -0
  66. package/src/did/createBtcoDidDocument.ts +60 -0
  67. package/src/did/providers/OrdinalsClientProviderAdapter.ts +68 -0
  68. package/src/events/EventEmitter.ts +222 -0
  69. package/src/events/index.ts +19 -0
  70. package/src/events/types.ts +331 -0
  71. package/src/examples/basic-usage.ts +78 -0
  72. package/src/examples/create-module-original.ts +435 -0
  73. package/src/examples/full-lifecycle-flow.ts +514 -0
  74. package/src/examples/run.ts +60 -0
  75. package/src/index.ts +204 -0
  76. package/src/kinds/KindRegistry.ts +320 -0
  77. package/src/kinds/index.ts +74 -0
  78. package/src/kinds/types.ts +470 -0
  79. package/src/kinds/validators/AgentValidator.ts +257 -0
  80. package/src/kinds/validators/AppValidator.ts +211 -0
  81. package/src/kinds/validators/DatasetValidator.ts +242 -0
  82. package/src/kinds/validators/DocumentValidator.ts +311 -0
  83. package/src/kinds/validators/MediaValidator.ts +269 -0
  84. package/src/kinds/validators/ModuleValidator.ts +225 -0
  85. package/src/kinds/validators/base.ts +276 -0
  86. package/src/kinds/validators/index.ts +12 -0
  87. package/src/lifecycle/BatchOperations.ts +381 -0
  88. package/src/lifecycle/LifecycleManager.ts +2156 -0
  89. package/src/lifecycle/OriginalsAsset.ts +524 -0
  90. package/src/lifecycle/ProvenanceQuery.ts +280 -0
  91. package/src/lifecycle/ResourceVersioning.ts +163 -0
  92. package/src/migration/MigrationManager.ts +587 -0
  93. package/src/migration/audit/AuditLogger.ts +176 -0
  94. package/src/migration/checkpoint/CheckpointManager.ts +112 -0
  95. package/src/migration/checkpoint/CheckpointStorage.ts +101 -0
  96. package/src/migration/index.ts +33 -0
  97. package/src/migration/operations/BaseMigration.ts +126 -0
  98. package/src/migration/operations/PeerToBtcoMigration.ts +105 -0
  99. package/src/migration/operations/PeerToWebvhMigration.ts +62 -0
  100. package/src/migration/operations/WebvhToBtcoMigration.ts +105 -0
  101. package/src/migration/rollback/RollbackManager.ts +170 -0
  102. package/src/migration/state/StateMachine.ts +92 -0
  103. package/src/migration/state/StateTracker.ts +156 -0
  104. package/src/migration/types.ts +356 -0
  105. package/src/migration/validation/BitcoinValidator.ts +107 -0
  106. package/src/migration/validation/CredentialValidator.ts +62 -0
  107. package/src/migration/validation/DIDCompatibilityValidator.ts +151 -0
  108. package/src/migration/validation/LifecycleValidator.ts +64 -0
  109. package/src/migration/validation/StorageValidator.ts +79 -0
  110. package/src/migration/validation/ValidationPipeline.ts +213 -0
  111. package/src/resources/ResourceManager.ts +655 -0
  112. package/src/resources/index.ts +21 -0
  113. package/src/resources/types.ts +202 -0
  114. package/src/storage/LocalStorageAdapter.ts +64 -0
  115. package/src/storage/MemoryStorageAdapter.ts +29 -0
  116. package/src/storage/StorageAdapter.ts +25 -0
  117. package/src/storage/index.ts +3 -0
  118. package/src/types/bitcoin.ts +98 -0
  119. package/src/types/common.ts +92 -0
  120. package/src/types/credentials.ts +89 -0
  121. package/src/types/did.ts +31 -0
  122. package/src/types/external-shims.d.ts +53 -0
  123. package/src/types/index.ts +7 -0
  124. package/src/types/network.ts +178 -0
  125. package/src/utils/EventLogger.ts +298 -0
  126. package/src/utils/Logger.ts +324 -0
  127. package/src/utils/MetricsCollector.ts +358 -0
  128. package/src/utils/bitcoin-address.ts +132 -0
  129. package/src/utils/cbor.ts +31 -0
  130. package/src/utils/encoding.ts +135 -0
  131. package/src/utils/hash.ts +12 -0
  132. package/src/utils/retry.ts +46 -0
  133. package/src/utils/satoshi-validation.ts +196 -0
  134. package/src/utils/serialization.ts +102 -0
  135. package/src/utils/telemetry.ts +44 -0
  136. package/src/utils/validation.ts +123 -0
  137. package/src/vc/CredentialManager.ts +955 -0
  138. package/src/vc/Issuer.ts +105 -0
  139. package/src/vc/Verifier.ts +54 -0
  140. package/src/vc/cryptosuites/bbs.ts +253 -0
  141. package/src/vc/cryptosuites/bbsSimple.ts +21 -0
  142. package/src/vc/cryptosuites/eddsa.ts +99 -0
  143. package/src/vc/documentLoader.ts +81 -0
  144. package/src/vc/proofs/data-integrity.ts +33 -0
  145. package/src/vc/utils/jsonld.ts +18 -0
@@ -0,0 +1,324 @@
1
+ /**
2
+ * Enhanced Logger for Originals SDK
3
+ *
4
+ * Features:
5
+ * - Multiple log levels (debug, info, warn, error)
6
+ * - Child loggers with hierarchical context
7
+ * - Performance timing with startTimer
8
+ * - Multiple output destinations
9
+ * - Data sanitization for sensitive information
10
+ * - Async-safe operations
11
+ */
12
+
13
+ import type { OriginalsConfig } from '../types';
14
+
15
+ /**
16
+ * Log level type
17
+ */
18
+ export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
19
+
20
+ /**
21
+ * Structured log entry
22
+ */
23
+ export interface LogEntry {
24
+ timestamp: string;
25
+ level: LogLevel;
26
+ context: string;
27
+ message: string;
28
+ data?: unknown;
29
+ duration?: number; // For performance tracking
30
+ traceId?: string; // For request correlation
31
+ }
32
+
33
+ /**
34
+ * Log output interface for custom outputs
35
+ */
36
+ export interface LogOutput {
37
+ write(entry: LogEntry): void | Promise<void>;
38
+ }
39
+
40
+ /**
41
+ * Console log output implementation
42
+ */
43
+ export class ConsoleLogOutput implements LogOutput {
44
+ write(entry: LogEntry): void {
45
+ const timestamp = entry.timestamp;
46
+ const level = entry.level.toUpperCase().padEnd(5);
47
+ const context = entry.context;
48
+ const message = entry.message;
49
+ const durationStr = entry.duration !== undefined ? ` (${entry.duration.toFixed(2)}ms)` : '';
50
+ const dataStr = entry.data ? ` ${JSON.stringify(entry.data)}` : '';
51
+
52
+ const logMessage = `[${timestamp}] ${level} [${context}] ${message}${durationStr}${dataStr}`;
53
+
54
+ switch (entry.level) {
55
+ case 'debug':
56
+ console.debug(logMessage);
57
+ break;
58
+ case 'info':
59
+ console.info(logMessage);
60
+ break;
61
+ case 'warn':
62
+ console.warn(logMessage);
63
+ break;
64
+ case 'error':
65
+ console.error(logMessage);
66
+ break;
67
+ }
68
+ }
69
+ }
70
+
71
+ /**
72
+ * File log output implementation (async)
73
+ */
74
+ export class FileLogOutput implements LogOutput {
75
+ private buffer: string[] = [];
76
+ private flushTimeout: ReturnType<typeof setTimeout> | null = null;
77
+ private readonly flushInterval = 1000; // Flush every 1 second
78
+
79
+ constructor(private filePath: string) {}
80
+
81
+ write(entry: LogEntry): void {
82
+ // Format as JSON line
83
+ const line = JSON.stringify(entry) + '\n';
84
+ this.buffer.push(line);
85
+
86
+ // Schedule flush
87
+ if (!this.flushTimeout) {
88
+ this.flushTimeout = setTimeout(() => {
89
+ void this.flush();
90
+ }, this.flushInterval);
91
+ }
92
+ }
93
+
94
+ private async flush(): Promise<void> {
95
+ if (this.buffer.length === 0) {
96
+ return;
97
+ }
98
+
99
+ const lines = this.buffer.join('');
100
+ this.buffer = [];
101
+ this.flushTimeout = null;
102
+
103
+ try {
104
+ // Use Bun's file API for efficient file writing
105
+ const file = Bun.file(this.filePath);
106
+ const exists = await file.exists();
107
+
108
+ if (exists) {
109
+ // Append to existing file
110
+ const content = await file.text();
111
+ await Bun.write(this.filePath, content + lines);
112
+ } else {
113
+ // Create new file
114
+ await Bun.write(this.filePath, lines);
115
+ }
116
+ } catch (err) {
117
+ // Fallback to console on file write error
118
+ console.error('Failed to write log file:', err);
119
+ }
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Main Logger class
125
+ */
126
+ export class Logger {
127
+ private outputs: LogOutput[] = [];
128
+ private minLevel: LogLevel;
129
+ private includeTimestamps: boolean;
130
+ private includeContext: boolean;
131
+ private sanitizeLogs: boolean;
132
+
133
+ // Log level priorities
134
+ private static readonly LEVEL_PRIORITY: Record<LogLevel, number> = {
135
+ debug: 0,
136
+ info: 1,
137
+ warn: 2,
138
+ error: 3
139
+ };
140
+
141
+ constructor(
142
+ private context: string,
143
+ config: OriginalsConfig
144
+ ) {
145
+ this.minLevel = config.logging?.level || 'info';
146
+ this.includeTimestamps = config.logging?.includeTimestamps !== false;
147
+ this.includeContext = config.logging?.includeContext !== false;
148
+ this.sanitizeLogs = config.logging?.sanitizeLogs !== false;
149
+
150
+ // Set up default outputs
151
+ if (config.logging?.outputs && config.logging.outputs.length > 0) {
152
+ this.outputs = [...config.logging.outputs];
153
+ } else {
154
+ // Default to console output
155
+ this.outputs = [new ConsoleLogOutput()];
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Log a debug message
161
+ */
162
+ debug(message: string, data?: unknown): void {
163
+ this.log('debug', message, data);
164
+ }
165
+
166
+ /**
167
+ * Log an info message
168
+ */
169
+ info(message: string, data?: unknown): void {
170
+ this.log('info', message, data);
171
+ }
172
+
173
+ /**
174
+ * Log a warning message
175
+ */
176
+ warn(message: string, data?: unknown): void {
177
+ this.log('warn', message, data);
178
+ }
179
+
180
+ /**
181
+ * Log an error message
182
+ */
183
+ error(message: string, error?: Error, data?: unknown): void {
184
+ const errorData: unknown = error ? {
185
+ ...(data && typeof data === 'object' ? data : {}),
186
+ error: {
187
+ name: error.name,
188
+ message: error.message,
189
+ stack: error.stack
190
+ }
191
+ } : data;
192
+
193
+ this.log('error', message, errorData);
194
+ }
195
+
196
+ /**
197
+ * Start a timer for performance tracking
198
+ * Returns a function that stops the timer and logs the duration
199
+ */
200
+ startTimer(operation: string): () => void {
201
+ const startTime = performance.now();
202
+
203
+ return () => {
204
+ const duration = performance.now() - startTime;
205
+ this.log('debug', `${operation} completed`, undefined, duration);
206
+ };
207
+ }
208
+
209
+ /**
210
+ * Create a child logger with nested context
211
+ */
212
+ child(childContext: string): Logger {
213
+ const newLogger = Object.create(Logger.prototype) as Logger;
214
+ newLogger.context = `${this.context}:${childContext}`;
215
+ newLogger.outputs = this.outputs;
216
+ newLogger.minLevel = this.minLevel;
217
+ newLogger.includeTimestamps = this.includeTimestamps;
218
+ newLogger.includeContext = this.includeContext;
219
+ newLogger.sanitizeLogs = this.sanitizeLogs;
220
+ return newLogger;
221
+ }
222
+
223
+ /**
224
+ * Set a single output (replaces existing outputs)
225
+ */
226
+ setOutput(output: LogOutput): void {
227
+ this.outputs = [output];
228
+ }
229
+
230
+ /**
231
+ * Add an output to the existing outputs
232
+ */
233
+ addOutput(output: LogOutput): void {
234
+ this.outputs.push(output);
235
+ }
236
+
237
+ /**
238
+ * Internal log method
239
+ */
240
+ private log(level: LogLevel, message: string, data?: unknown, duration?: number): void {
241
+ // Check if we should log this level
242
+ if (Logger.LEVEL_PRIORITY[level] < Logger.LEVEL_PRIORITY[this.minLevel]) {
243
+ return;
244
+ }
245
+
246
+ // Sanitize data if needed
247
+ const sanitizedData = this.sanitizeLogs ? this.sanitize(data) : data;
248
+
249
+ // Create log entry
250
+ const entry: LogEntry = {
251
+ timestamp: this.includeTimestamps ? new Date().toISOString() : '',
252
+ level,
253
+ context: this.includeContext ? this.context : '',
254
+ message,
255
+ data: sanitizedData,
256
+ duration
257
+ };
258
+
259
+ // Write to all outputs (fire and forget for async outputs)
260
+ for (const output of this.outputs) {
261
+ try {
262
+ const result = output.write(entry);
263
+ // If result is a promise, don't await it (non-blocking)
264
+ if (result instanceof Promise) {
265
+ result.catch(err => {
266
+ // Silently fail for async outputs to avoid blocking
267
+ if (typeof console !== 'undefined' && console.error) {
268
+ console.error('Log output error:', err);
269
+ }
270
+ });
271
+ }
272
+ } catch (err) {
273
+ // Continue even if one output fails
274
+ if (typeof console !== 'undefined' && console.error) {
275
+ console.error('Log output error:', err);
276
+ }
277
+ }
278
+ }
279
+ }
280
+
281
+ /**
282
+ * Sanitize sensitive data from logs
283
+ */
284
+ private sanitize(data: unknown): unknown {
285
+ if (!data) {
286
+ return data;
287
+ }
288
+
289
+ // Handle arrays
290
+ if (Array.isArray(data)) {
291
+ return data.map(item => this.sanitize(item));
292
+ }
293
+
294
+ // Handle objects
295
+ if (typeof data === 'object') {
296
+ const sanitized: Record<string, unknown> = {};
297
+
298
+ for (const [key, value] of Object.entries(data)) {
299
+ const lowerKey = key.toLowerCase();
300
+
301
+ // Sanitize sensitive keys
302
+ if (
303
+ lowerKey.includes('private') ||
304
+ lowerKey.includes('key') ||
305
+ lowerKey.includes('secret') ||
306
+ lowerKey.includes('password') ||
307
+ lowerKey.includes('token') ||
308
+ lowerKey.includes('credential')
309
+ ) {
310
+ sanitized[key] = '[REDACTED]';
311
+ } else {
312
+ // Recursively sanitize nested objects
313
+ sanitized[key] = this.sanitize(value);
314
+ }
315
+ }
316
+
317
+ return sanitized;
318
+ }
319
+
320
+ // Return primitive values as-is
321
+ return data;
322
+ }
323
+ }
324
+
@@ -0,0 +1,358 @@
1
+ /**
2
+ * Metrics Collector for Originals SDK
3
+ *
4
+ * Features:
5
+ * - Track operation counts and performance
6
+ * - Asset lifecycle metrics (created, migrated, transferred)
7
+ * - Error tracking by error code
8
+ * - Cache statistics (optional)
9
+ * - Export in JSON and Prometheus formats
10
+ * - Memory-efficient storage
11
+ */
12
+
13
+ import type { LayerType } from '../types';
14
+
15
+ /**
16
+ * Operation-specific metrics
17
+ */
18
+ export interface OperationMetrics {
19
+ count: number;
20
+ totalTime: number;
21
+ avgTime: number;
22
+ minTime: number;
23
+ maxTime: number;
24
+ errorCount: number;
25
+ }
26
+
27
+ /**
28
+ * Complete metrics snapshot
29
+ */
30
+ export interface Metrics {
31
+ // Asset operations
32
+ assetsCreated: number;
33
+ assetsMigrated: Record<string, number>; // by layer transition (e.g., "peer→webvh": 5)
34
+ assetsTransferred: number;
35
+
36
+ // Operation performance
37
+ operationTimes: Record<string, OperationMetrics>;
38
+
39
+ // Error tracking
40
+ errors: Record<string, number>; // by error code
41
+
42
+ // Cache statistics (if caching is implemented)
43
+ cacheStats?: {
44
+ hits: number;
45
+ misses: number;
46
+ hitRate: number;
47
+ };
48
+
49
+ // System metrics
50
+ startTime: string;
51
+ uptime: number; // milliseconds
52
+ }
53
+
54
+ /**
55
+ * MetricsCollector class
56
+ */
57
+ export class MetricsCollector {
58
+ private assetsCreatedCount = 0;
59
+ private assetsMigratedMap: Map<string, number> = new Map();
60
+ private assetsTransferredCount = 0;
61
+
62
+ private operationMetrics: Map<string, {
63
+ count: number;
64
+ totalTime: number;
65
+ minTime: number;
66
+ maxTime: number;
67
+ errorCount: number;
68
+ }> = new Map();
69
+
70
+ private errorCounts: Map<string, number> = new Map();
71
+
72
+ private cacheHits = 0;
73
+ private cacheMisses = 0;
74
+
75
+ private readonly startTime: string;
76
+
77
+ constructor() {
78
+ this.startTime = new Date().toISOString();
79
+ }
80
+
81
+ /**
82
+ * Record an operation with timing and success status
83
+ */
84
+ recordOperation(operation: string, duration: number, success: boolean): void {
85
+ if (!this.operationMetrics.has(operation)) {
86
+ this.operationMetrics.set(operation, {
87
+ count: 0,
88
+ totalTime: 0,
89
+ minTime: Infinity,
90
+ maxTime: -Infinity,
91
+ errorCount: 0
92
+ });
93
+ }
94
+
95
+ const metrics = this.operationMetrics.get(operation)!;
96
+ metrics.count++;
97
+ metrics.totalTime += duration;
98
+ metrics.minTime = Math.min(metrics.minTime, duration);
99
+ metrics.maxTime = Math.max(metrics.maxTime, duration);
100
+
101
+ if (!success) {
102
+ metrics.errorCount++;
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Start tracking an operation, returns completion function
108
+ */
109
+ startOperation(operation: string): () => void {
110
+ const startTime = performance.now();
111
+
112
+ return (success: boolean = true) => {
113
+ const duration = performance.now() - startTime;
114
+ this.recordOperation(operation, duration, success);
115
+ };
116
+ }
117
+
118
+ /**
119
+ * Record an asset creation
120
+ */
121
+ recordAssetCreated(): void {
122
+ this.assetsCreatedCount++;
123
+ }
124
+
125
+ /**
126
+ * Record an asset migration between layers
127
+ */
128
+ recordMigration(from: LayerType, to: LayerType): void {
129
+ // Create transition key
130
+ const fromShort = from.split(':')[1]; // "peer", "webvh", "btco"
131
+ const toShort = to.split(':')[1];
132
+ const transitionKey = `${fromShort}→${toShort}`;
133
+
134
+ const current = this.assetsMigratedMap.get(transitionKey) || 0;
135
+ this.assetsMigratedMap.set(transitionKey, current + 1);
136
+ }
137
+
138
+ /**
139
+ * Record an asset transfer
140
+ */
141
+ recordTransfer(): void {
142
+ this.assetsTransferredCount++;
143
+ }
144
+
145
+ /**
146
+ * Record an error by error code
147
+ */
148
+ recordError(code: string, operation?: string): void {
149
+ // Track error by code
150
+ const current = this.errorCounts.get(code) || 0;
151
+ this.errorCounts.set(code, current + 1);
152
+
153
+ // If operation is provided, increment its error count
154
+ if (operation && this.operationMetrics.has(operation)) {
155
+ this.operationMetrics.get(operation)!.errorCount++;
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Record a cache hit
161
+ */
162
+ recordCacheHit(): void {
163
+ this.cacheHits++;
164
+ }
165
+
166
+ /**
167
+ * Record a cache miss
168
+ */
169
+ recordCacheMiss(): void {
170
+ this.cacheMisses++;
171
+ }
172
+
173
+ /**
174
+ * Get a snapshot of all metrics
175
+ */
176
+ getMetrics(): Metrics {
177
+ const operationTimes: Record<string, OperationMetrics> = {};
178
+
179
+ for (const [operation, metrics] of this.operationMetrics.entries()) {
180
+ operationTimes[operation] = {
181
+ count: metrics.count,
182
+ totalTime: metrics.totalTime,
183
+ avgTime: metrics.count > 0 ? metrics.totalTime / metrics.count : 0,
184
+ minTime: metrics.minTime === Infinity ? 0 : metrics.minTime,
185
+ maxTime: metrics.maxTime === -Infinity ? 0 : metrics.maxTime,
186
+ errorCount: metrics.errorCount
187
+ };
188
+ }
189
+
190
+ const assetsMigrated: Record<string, number> = {};
191
+ for (const [key, count] of this.assetsMigratedMap.entries()) {
192
+ assetsMigrated[key] = count;
193
+ }
194
+
195
+ const errors: Record<string, number> = {};
196
+ for (const [code, count] of this.errorCounts.entries()) {
197
+ errors[code] = count;
198
+ }
199
+
200
+ const totalCacheRequests = this.cacheHits + this.cacheMisses;
201
+ const cacheStats = totalCacheRequests > 0 ? {
202
+ hits: this.cacheHits,
203
+ misses: this.cacheMisses,
204
+ hitRate: this.cacheHits / totalCacheRequests
205
+ } : undefined;
206
+
207
+ return {
208
+ assetsCreated: this.assetsCreatedCount,
209
+ assetsMigrated,
210
+ assetsTransferred: this.assetsTransferredCount,
211
+ operationTimes,
212
+ errors,
213
+ cacheStats,
214
+ startTime: this.startTime,
215
+ uptime: Date.now() - new Date(this.startTime).getTime()
216
+ };
217
+ }
218
+
219
+ /**
220
+ * Get metrics for a specific operation
221
+ */
222
+ getOperationMetrics(operation: string): OperationMetrics | null {
223
+ const metrics = this.operationMetrics.get(operation);
224
+
225
+ if (!metrics) {
226
+ return null;
227
+ }
228
+
229
+ return {
230
+ count: metrics.count,
231
+ totalTime: metrics.totalTime,
232
+ avgTime: metrics.count > 0 ? metrics.totalTime / metrics.count : 0,
233
+ minTime: metrics.minTime === Infinity ? 0 : metrics.minTime,
234
+ maxTime: metrics.maxTime === -Infinity ? 0 : metrics.maxTime,
235
+ errorCount: metrics.errorCount
236
+ };
237
+ }
238
+
239
+ /**
240
+ * Reset all metrics
241
+ */
242
+ reset(): void {
243
+ this.assetsCreatedCount = 0;
244
+ this.assetsMigratedMap.clear();
245
+ this.assetsTransferredCount = 0;
246
+ this.operationMetrics.clear();
247
+ this.errorCounts.clear();
248
+ this.cacheHits = 0;
249
+ this.cacheMisses = 0;
250
+ }
251
+
252
+ /**
253
+ * Export metrics in the specified format
254
+ */
255
+ export(format: 'json' | 'prometheus'): string {
256
+ if (format === 'json') {
257
+ return this.exportJSON();
258
+ } else if (format === 'prometheus') {
259
+ return this.exportPrometheus();
260
+ }
261
+
262
+ throw new Error(`Unsupported export format: ${String(format)}`);
263
+ }
264
+
265
+ /**
266
+ * Export metrics as JSON
267
+ */
268
+ private exportJSON(): string {
269
+ return JSON.stringify(this.getMetrics(), null, 2);
270
+ }
271
+
272
+ /**
273
+ * Export metrics in Prometheus format
274
+ */
275
+ private exportPrometheus(): string {
276
+ const lines: string[] = [];
277
+ const metrics = this.getMetrics();
278
+
279
+ // Asset metrics
280
+ lines.push('# HELP originals_assets_created_total Total number of assets created');
281
+ lines.push('# TYPE originals_assets_created_total counter');
282
+ lines.push(`originals_assets_created_total ${metrics.assetsCreated}`);
283
+ lines.push('');
284
+
285
+ lines.push('# HELP originals_assets_transferred_total Total number of assets transferred');
286
+ lines.push('# TYPE originals_assets_transferred_total counter');
287
+ lines.push(`originals_assets_transferred_total ${metrics.assetsTransferred}`);
288
+ lines.push('');
289
+
290
+ // Migration metrics
291
+ lines.push('# HELP originals_assets_migrated_total Total number of assets migrated by layer transition');
292
+ lines.push('# TYPE originals_assets_migrated_total counter');
293
+ for (const [transition, count] of Object.entries(metrics.assetsMigrated)) {
294
+ const [from, to] = transition.split('→');
295
+ lines.push(`originals_assets_migrated_total{from="${from}",to="${to}"} ${count}`);
296
+ }
297
+ lines.push('');
298
+
299
+ // Operation metrics
300
+ for (const [operation, opMetrics] of Object.entries(metrics.operationTimes)) {
301
+ const safeOpName = operation.replace(/[^a-zA-Z0-9_]/g, '_');
302
+
303
+ lines.push(`# HELP originals_operation_${safeOpName}_total Total number of ${operation} operations`);
304
+ lines.push(`# TYPE originals_operation_${safeOpName}_total counter`);
305
+ lines.push(`originals_operation_${safeOpName}_total ${opMetrics.count}`);
306
+ lines.push('');
307
+
308
+ lines.push(`# HELP originals_operation_${safeOpName}_duration_milliseconds Duration of ${operation} operations`);
309
+ lines.push(`# TYPE originals_operation_${safeOpName}_duration_milliseconds summary`);
310
+ lines.push(`originals_operation_${safeOpName}_duration_milliseconds{quantile="0.0"} ${opMetrics.minTime}`);
311
+ lines.push(`originals_operation_${safeOpName}_duration_milliseconds{quantile="0.5"} ${opMetrics.avgTime}`);
312
+ lines.push(`originals_operation_${safeOpName}_duration_milliseconds{quantile="1.0"} ${opMetrics.maxTime}`);
313
+ lines.push(`originals_operation_${safeOpName}_duration_milliseconds_sum ${opMetrics.totalTime}`);
314
+ lines.push(`originals_operation_${safeOpName}_duration_milliseconds_count ${opMetrics.count}`);
315
+ lines.push('');
316
+
317
+ lines.push(`# HELP originals_operation_${safeOpName}_errors_total Total number of errors in ${operation} operations`);
318
+ lines.push(`# TYPE originals_operation_${safeOpName}_errors_total counter`);
319
+ lines.push(`originals_operation_${safeOpName}_errors_total ${opMetrics.errorCount}`);
320
+ lines.push('');
321
+ }
322
+
323
+ // Error metrics
324
+ lines.push('# HELP originals_errors_total Total number of errors by code');
325
+ lines.push('# TYPE originals_errors_total counter');
326
+ for (const [code, count] of Object.entries(metrics.errors)) {
327
+ lines.push(`originals_errors_total{code="${code}"} ${count}`);
328
+ }
329
+ lines.push('');
330
+
331
+ // Cache metrics
332
+ if (metrics.cacheStats) {
333
+ lines.push('# HELP originals_cache_hits_total Total number of cache hits');
334
+ lines.push('# TYPE originals_cache_hits_total counter');
335
+ lines.push(`originals_cache_hits_total ${metrics.cacheStats.hits}`);
336
+ lines.push('');
337
+
338
+ lines.push('# HELP originals_cache_misses_total Total number of cache misses');
339
+ lines.push('# TYPE originals_cache_misses_total counter');
340
+ lines.push(`originals_cache_misses_total ${metrics.cacheStats.misses}`);
341
+ lines.push('');
342
+
343
+ lines.push('# HELP originals_cache_hit_rate Cache hit rate');
344
+ lines.push('# TYPE originals_cache_hit_rate gauge');
345
+ lines.push(`originals_cache_hit_rate ${metrics.cacheStats.hitRate}`);
346
+ lines.push('');
347
+ }
348
+
349
+ // System metrics
350
+ lines.push('# HELP originals_uptime_milliseconds SDK uptime in milliseconds');
351
+ lines.push('# TYPE originals_uptime_milliseconds gauge');
352
+ lines.push(`originals_uptime_milliseconds ${metrics.uptime}`);
353
+ lines.push('');
354
+
355
+ return lines.join('\n');
356
+ }
357
+ }
358
+