@happyvertical/smrt-core 0.36.5 → 0.36.7

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 (131) hide show
  1. package/dist/collection.d.ts +1 -1
  2. package/dist/config.d.ts +1 -1
  3. package/dist/config.d.ts.map +1 -1
  4. package/dist/config.js.map +1 -1
  5. package/dist/consumer-plugin/index.d.ts.map +1 -1
  6. package/dist/consumer-plugin/index.js +7 -3
  7. package/dist/consumer-plugin/index.js.map +1 -1
  8. package/dist/database.d.ts +3 -3
  9. package/dist/database.d.ts.map +1 -1
  10. package/dist/database.js.map +1 -1
  11. package/dist/embeddings/provider.d.ts +14 -2
  12. package/dist/embeddings/provider.d.ts.map +1 -1
  13. package/dist/embeddings/provider.js +3 -3
  14. package/dist/embeddings/provider.js.map +1 -1
  15. package/dist/embeddings/storage.js.map +1 -1
  16. package/dist/errors.d.ts +22 -22
  17. package/dist/errors.d.ts.map +1 -1
  18. package/dist/errors.js +5 -4
  19. package/dist/errors.js.map +1 -1
  20. package/dist/generators/cli.d.ts +4 -22
  21. package/dist/generators/cli.d.ts.map +1 -1
  22. package/dist/generators/cli.js +9 -5
  23. package/dist/generators/cli.js.map +1 -1
  24. package/dist/generators/mcp-runtime-template.d.ts +1 -1
  25. package/dist/generators/mcp-runtime-template.d.ts.map +1 -1
  26. package/dist/generators/mcp-runtime-template.js.map +1 -1
  27. package/dist/generators/mcp.d.ts +16 -4
  28. package/dist/generators/mcp.d.ts.map +1 -1
  29. package/dist/generators/mcp.js +25 -9
  30. package/dist/generators/mcp.js.map +1 -1
  31. package/dist/generators/rest.d.ts +6 -5
  32. package/dist/generators/rest.d.ts.map +1 -1
  33. package/dist/generators/rest.js +8 -5
  34. package/dist/generators/rest.js.map +1 -1
  35. package/dist/generators/swagger.d.ts +12 -2
  36. package/dist/generators/swagger.d.ts.map +1 -1
  37. package/dist/generators/swagger.js +6 -3
  38. package/dist/generators/swagger.js.map +1 -1
  39. package/dist/knowledge.d.ts +12 -1
  40. package/dist/knowledge.d.ts.map +1 -1
  41. package/dist/knowledge.js.map +1 -1
  42. package/dist/lazy-config.d.ts.map +1 -1
  43. package/dist/lazy-config.js.map +1 -1
  44. package/dist/manifest/generator.d.ts.map +1 -1
  45. package/dist/manifest/generator.js +14 -12
  46. package/dist/manifest/generator.js.map +1 -1
  47. package/dist/manifest/manager.d.ts +3 -3
  48. package/dist/manifest/manager.d.ts.map +1 -1
  49. package/dist/manifest/manager.js.map +1 -1
  50. package/dist/manifest/manifest-loader.d.ts +3 -2
  51. package/dist/manifest/manifest-loader.d.ts.map +1 -1
  52. package/dist/manifest/manifest-loader.js +3 -2
  53. package/dist/manifest/manifest-loader.js.map +1 -1
  54. package/dist/manifest/static-manifest.js +2 -2
  55. package/dist/manifest/static-manifest.js.map +1 -1
  56. package/dist/manifest/store.js +2 -2
  57. package/dist/manifest/test-manifest-stub.js +2 -2
  58. package/dist/manifest/test-manifest-stub.js.map +1 -1
  59. package/dist/manifest.json +2 -2
  60. package/dist/mcp-advisor/index.d.ts +1 -1
  61. package/dist/mcp-advisor/index.d.ts.map +1 -1
  62. package/dist/mcp-advisor/tools/get-object-config.d.ts.map +1 -1
  63. package/dist/mcp-advisor/types.d.ts +5 -5
  64. package/dist/mcp-advisor/types.d.ts.map +1 -1
  65. package/dist/migrations/differ.js.map +1 -1
  66. package/dist/scanner/manifest-generator.d.ts +11 -3
  67. package/dist/scanner/manifest-generator.d.ts.map +1 -1
  68. package/dist/scanner/manifest-generator.js +19 -15
  69. package/dist/scanner/manifest-generator.js.map +1 -1
  70. package/dist/scanner/types.d.ts +60 -6
  71. package/dist/scanner/types.d.ts.map +1 -1
  72. package/dist/schema/code-generator.d.ts.map +1 -1
  73. package/dist/schema/ddl/base-strategy.d.ts +2 -2
  74. package/dist/schema/ddl/base-strategy.d.ts.map +1 -1
  75. package/dist/schema/ddl/base-strategy.js.map +1 -1
  76. package/dist/schema/ddl/sqlite-strategy.d.ts +1 -1
  77. package/dist/schema/ddl/sqlite-strategy.d.ts.map +1 -1
  78. package/dist/schema/ddl/sqlite-strategy.js.map +1 -1
  79. package/dist/schema/ddl/types.d.ts +1 -1
  80. package/dist/schema/ddl/types.d.ts.map +1 -1
  81. package/dist/schema/generator.d.ts +27 -4
  82. package/dist/schema/generator.d.ts.map +1 -1
  83. package/dist/schema/generator.js +3 -2
  84. package/dist/schema/generator.js.map +1 -1
  85. package/dist/schema/override-system.d.ts +3 -3
  86. package/dist/schema/override-system.d.ts.map +1 -1
  87. package/dist/schema/schema-aggregator.d.ts.map +1 -1
  88. package/dist/schema/schema-manager.d.ts.map +1 -1
  89. package/dist/schema/schema-manager.js +12 -4
  90. package/dist/schema/schema-manager.js.map +1 -1
  91. package/dist/schema/types.d.ts +1 -1
  92. package/dist/schema/types.d.ts.map +1 -1
  93. package/dist/schema/utils.d.ts +6 -1
  94. package/dist/schema/utils.d.ts.map +1 -1
  95. package/dist/schema/utils.js +2 -1
  96. package/dist/schema/utils.js.map +1 -1
  97. package/dist/signals/sanitizer.d.ts +1 -1
  98. package/dist/signals/sanitizer.d.ts.map +1 -1
  99. package/dist/signals/sanitizer.js +12 -2
  100. package/dist/signals/sanitizer.js.map +1 -1
  101. package/dist/smrt-knowledge.json +4 -4
  102. package/dist/system/types.d.ts +2 -2
  103. package/dist/system/types.d.ts.map +1 -1
  104. package/dist/system-fields.d.ts +5 -43
  105. package/dist/system-fields.d.ts.map +1 -1
  106. package/dist/system-fields.js +2 -1
  107. package/dist/system-fields.js.map +1 -1
  108. package/dist/test-utils.d.ts +39 -13
  109. package/dist/test-utils.d.ts.map +1 -1
  110. package/dist/testing/database.d.ts.map +1 -1
  111. package/dist/testing/database.js.map +1 -1
  112. package/dist/tools/tool-executor.d.ts +19 -5
  113. package/dist/tools/tool-executor.d.ts.map +1 -1
  114. package/dist/tools/tool-executor.js +4 -2
  115. package/dist/tools/tool-executor.js.map +1 -1
  116. package/dist/tools/tool-generator.d.ts +8 -1
  117. package/dist/tools/tool-generator.d.ts.map +1 -1
  118. package/dist/tools/tool-generator.js +10 -11
  119. package/dist/tools/tool-generator.js.map +1 -1
  120. package/dist/utils/json.js.map +1 -1
  121. package/dist/utils.d.ts +16 -8
  122. package/dist/utils.d.ts.map +1 -1
  123. package/dist/utils.js.map +1 -1
  124. package/dist/vite-plugin/index.d.ts.map +1 -1
  125. package/dist/vite-plugin/index.js +9 -7
  126. package/dist/vite-plugin/index.js.map +1 -1
  127. package/dist/vite-plugin/sveltekit-generator.d.ts.map +1 -1
  128. package/dist/vite-plugin/sveltekit-generator.js +4 -3
  129. package/dist/vite-plugin/sveltekit-generator.js.map +1 -1
  130. package/dist/vite-plugin/templates/default-ui.ts +20 -6
  131. package/package.json +4 -4
package/dist/errors.d.ts CHANGED
@@ -7,9 +7,9 @@
7
7
  export declare abstract class SmrtError extends Error {
8
8
  readonly code: string;
9
9
  readonly category: 'database' | 'ai' | 'filesystem' | 'validation' | 'network' | 'configuration' | 'runtime';
10
- readonly details?: Record<string, any>;
10
+ readonly details?: Record<string, unknown>;
11
11
  readonly cause?: Error;
12
- constructor(message: string, code: string, category: SmrtError['category'], details?: Record<string, any>, cause?: Error);
12
+ constructor(message: string, code: string, category: SmrtError['category'], details?: Record<string, unknown>, cause?: Error);
13
13
  /**
14
14
  * Converts error to a serializable object for logging/debugging
15
15
  */
@@ -18,7 +18,7 @@ export declare abstract class SmrtError extends Error {
18
18
  message: string;
19
19
  code: string;
20
20
  category: "ai" | "database" | "filesystem" | "validation" | "network" | "configuration" | "runtime";
21
- details: Record<string, any> | undefined;
21
+ details: Record<string, unknown> | undefined;
22
22
  stack: string | undefined;
23
23
  cause: {
24
24
  name: string;
@@ -43,11 +43,11 @@ export declare abstract class SmrtError extends Error {
43
43
  * All errors have `category: 'database'` and codes prefixed with `DB_`.
44
44
  */
45
45
  export declare class DatabaseError extends SmrtError {
46
- constructor(message: string, code: string, details?: Record<string, any>, cause?: Error);
46
+ constructor(message: string, code: string, details?: Record<string, unknown>, cause?: Error);
47
47
  static connectionFailed(dbUrl: string, cause?: Error): DatabaseError;
48
48
  static queryFailed(query: string, cause?: Error): DatabaseError;
49
49
  static schemaError(tableName: string, operation: string, cause?: Error): DatabaseError;
50
- static constraintViolation(constraint: string, value: any, cause?: Error): DatabaseError;
50
+ static constraintViolation(constraint: string, value: unknown, cause?: Error): DatabaseError;
51
51
  static corruptedData(fieldName: string, className: string, cause?: Error): DatabaseError;
52
52
  static missingDiscriminator(className: string, rowId?: string): DatabaseError;
53
53
  static stiDiscriminatorConflict(details: {
@@ -56,7 +56,7 @@ export declare class DatabaseError extends SmrtError {
56
56
  id: string;
57
57
  slug: string;
58
58
  context: string;
59
- conflictIdentity: Record<string, any>;
59
+ conflictIdentity: Record<string, unknown>;
60
60
  legacyMetaType: string;
61
61
  qualifiedMetaType: string;
62
62
  duplicateId: string;
@@ -76,10 +76,10 @@ export declare class DatabaseError extends SmrtError {
76
76
  * AI errors are considered retryable by `ErrorUtils.isRetryable()`.
77
77
  */
78
78
  export declare class AIError extends SmrtError {
79
- constructor(message: string, code: string, details?: Record<string, any>, cause?: Error);
79
+ constructor(message: string, code: string, details?: Record<string, unknown>, cause?: Error);
80
80
  static providerError(provider: string, operation: string, cause?: Error): AIError;
81
81
  static rateLimitExceeded(provider: string, retryAfter?: number): AIError;
82
- static invalidResponse(provider: string, response: any): AIError;
82
+ static invalidResponse(provider: string, response: unknown): AIError;
83
83
  static authenticationFailed(provider: string): AIError;
84
84
  }
85
85
  /**
@@ -93,7 +93,7 @@ export declare class AIError extends SmrtError {
93
93
  * All errors have `category: 'filesystem'` and codes prefixed with `FS_`.
94
94
  */
95
95
  export declare class FilesystemError extends SmrtError {
96
- constructor(message: string, code: string, details?: Record<string, any>, cause?: Error);
96
+ constructor(message: string, code: string, details?: Record<string, unknown>, cause?: Error);
97
97
  static fileNotFound(path: string): FilesystemError;
98
98
  static permissionDenied(path: string, operation: string): FilesystemError;
99
99
  static diskSpaceExceeded(path: string, requiredBytes: number): FilesystemError;
@@ -114,10 +114,10 @@ export declare class FilesystemError extends SmrtError {
114
114
  * All errors have `category: 'validation'` and codes prefixed with `VALIDATION_`.
115
115
  */
116
116
  export declare class ValidationError extends SmrtError {
117
- constructor(message: string, code: string, details?: Record<string, any>, cause?: Error);
117
+ constructor(message: string, code: string, details?: Record<string, unknown>, cause?: Error);
118
118
  static requiredField(fieldName: string, objectType: string): ValidationError;
119
- static invalidValue(fieldName: string, value: any, expectedType: string): ValidationError;
120
- static uniqueConstraint(fieldName: string, value: any): ValidationError;
119
+ static invalidValue(fieldName: string, value: unknown, expectedType: string): ValidationError;
120
+ static uniqueConstraint(fieldName: string, value: unknown): ValidationError;
121
121
  static rangeError(fieldName: string, value: number, min?: number, max?: number): ValidationError;
122
122
  }
123
123
  /**
@@ -132,7 +132,7 @@ export declare class ValidationError extends SmrtError {
132
132
  * Network errors are considered retryable by `ErrorUtils.isRetryable()`.
133
133
  */
134
134
  export declare class NetworkError extends SmrtError {
135
- constructor(message: string, code: string, details?: Record<string, any>, cause?: Error);
135
+ constructor(message: string, code: string, details?: Record<string, unknown>, cause?: Error);
136
136
  static requestFailed(url: string, status?: number, responseBody?: string | Error): NetworkError;
137
137
  static timeout(url: string, timeoutMs: number): NetworkError;
138
138
  static serviceUnavailable(service: string, reason?: string): NetworkError;
@@ -155,9 +155,9 @@ export declare class NetworkError extends SmrtError {
155
155
  * Configuration errors are **not** retried by `ErrorUtils.withRetry()`.
156
156
  */
157
157
  export declare class ConfigurationError extends SmrtError {
158
- constructor(message: string, code: string, details?: Record<string, any>, cause?: Error);
158
+ constructor(message: string, code: string, details?: Record<string, unknown>, cause?: Error);
159
159
  static missingConfiguration(configKey: string, context?: string): ConfigurationError;
160
- static invalidConfiguration(configKey: string, value: any, expected: string): ConfigurationError;
160
+ static invalidConfiguration(configKey: string, value: unknown, expected: string): ConfigurationError;
161
161
  static initializationFailed(component: string, cause?: Error): ConfigurationError;
162
162
  static circularInheritance(className: string, inheritanceChain: string[]): ConfigurationError;
163
163
  static incompatibleStrategy(className: string, classStrategy: string, parentClass: string, parentStrategy: string): ConfigurationError;
@@ -178,9 +178,9 @@ export declare class ConfigurationError extends SmrtError {
178
178
  * All errors have `category: 'runtime'` and codes prefixed with `RUNTIME_`.
179
179
  */
180
180
  export declare class RuntimeError extends SmrtError {
181
- constructor(message: string, code: string, details?: Record<string, any>, cause?: Error);
181
+ constructor(message: string, code: string, details?: Record<string, unknown>, cause?: Error);
182
182
  static operationFailed(operation: string, context?: string, cause?: Error): RuntimeError;
183
- static invalidState(message: string, context?: Record<string, any>): RuntimeError;
183
+ static invalidState(message: string, context?: Record<string, unknown>): RuntimeError;
184
184
  static resourceExhausted(resource: string, limit: number): RuntimeError;
185
185
  }
186
186
  /**
@@ -231,7 +231,7 @@ export declare class TenantIsolationError extends SmrtError {
231
231
  constructor(message: string, details?: {
232
232
  tenantId?: string;
233
233
  attemptedTenantId?: string;
234
- [key: string]: any;
234
+ [key: string]: unknown;
235
235
  }, cause?: Error);
236
236
  /**
237
237
  * Builds a {@link TenantIsolationError} for a blocked cross-tenant
@@ -260,7 +260,7 @@ export declare class ErrorUtils {
260
260
  /**
261
261
  * Sanitizes an error for safe logging (removes sensitive information)
262
262
  */
263
- static sanitizeError(error: Error): Record<string, any>;
263
+ static sanitizeError(error: Error): Record<string, unknown>;
264
264
  }
265
265
  /**
266
266
  * Validation report that collects multiple validation errors
@@ -332,7 +332,7 @@ export declare class ValidationUtils {
332
332
  * @param options - Validation options (required, min, max, etc.)
333
333
  * @returns ValidationError if validation fails, null otherwise
334
334
  */
335
- static validateField(fieldName: string, value: any, options: {
335
+ static validateField(fieldName: string, value: unknown, options: {
336
336
  required?: boolean;
337
337
  min?: number;
338
338
  max?: number;
@@ -340,13 +340,13 @@ export declare class ValidationUtils {
340
340
  maxLength?: number;
341
341
  pattern?: string | RegExp;
342
342
  type?: string;
343
- customValidator?: (value: any) => boolean | Promise<boolean>;
343
+ customValidator?: (value: unknown) => boolean | Promise<boolean>;
344
344
  customMessage?: string;
345
345
  }, objectType?: string): Promise<ValidationError | null>;
346
346
  /**
347
347
  * Validate required field
348
348
  */
349
- static validateRequired(fieldName: string, value: any, objectType?: string): ValidationError | null;
349
+ static validateRequired(fieldName: string, value: unknown, objectType?: string): ValidationError | null;
350
350
  /**
351
351
  * Validate numeric range
352
352
  */
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAgCH,8BAAsB,SAAU,SAAQ,KAAK;IAC3C,SAAgB,IAAI,EAAE,MAAM,CAAC;IAC7B,SAAgB,QAAQ,EACpB,UAAU,GACV,IAAI,GACJ,YAAY,GACZ,YAAY,GACZ,SAAS,GACT,eAAe,GACf,SAAS,CAAC;IACd,SAAgB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC9C,SAAgB,KAAK,CAAC,EAAE,KAAK,CAAC;gBAG5B,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,SAAS,CAAC,UAAU,CAAC,EAC/B,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC7B,KAAK,CAAC,EAAE,KAAK;IAef;;OAEG;IACH,MAAM;;;;;;;;;;;;;CAiBP;AAsED;;;;;;;;;;;;;;GAcG;AACH,qBAAa,aAAc,SAAQ,SAAS;gBAExC,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC7B,KAAK,CAAC,EAAE,KAAK;IAKf,MAAM,CAAC,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,aAAa;IASpE,MAAM,CAAC,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,aAAa;IAgB/D,MAA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MAAiB,GAC5B,eAAe,GAAG,IAAI;IAOzB;;OAEG;IACH,MAAM,CAAC,aAAa,CAClB,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,MAAM,EACb,GAAG,CAAC,EAAE,MAAM,EACZ,GAAG,CAAC,EAAE,MAAM,GACX,eAAe,GAAG,IAAI;IAUzB;;OAEG;IACH,MAAM,CAAC,cAAc,CACnB,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,MAAM,EACb,SAAS,CAAC,EAAE,MAAM,EAClB,SAAS,CAAC,EAAE,MAAM,GACjB,eAAe,GAAG,IAAI;IAkBzB;;OAEG;IACH,MAAM,CAAC,eAAe,CACpB,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,MAAM,GAAG,MAAM,GACvB,eAAe,GAAG,IAAI;CAW1B"}
package/dist/errors.js CHANGED
@@ -230,7 +230,7 @@ class ValidationError extends SmrtError {
230
230
  }
231
231
  static uniqueConstraint(fieldName, value) {
232
232
  return new ValidationError(
233
- `Unique constraint violation for field '${fieldName}' with value: ${value}`,
233
+ `Unique constraint violation for field '${fieldName}' with value: ${String(value)}`,
234
234
  "VALIDATION_UNIQUE_CONSTRAINT",
235
235
  { fieldName, value }
236
236
  );
@@ -432,7 +432,8 @@ class ErrorUtils {
432
432
  sanitized.code = error.code;
433
433
  sanitized.category = error.category;
434
434
  if (error.details) {
435
- sanitized.details = { ...error.details };
435
+ const details = { ...error.details };
436
+ sanitized.details = details;
436
437
  const sensitiveFields = [
437
438
  "password",
438
439
  "token",
@@ -441,8 +442,8 @@ class ErrorUtils {
441
442
  "apiKey"
442
443
  ];
443
444
  for (const field of sensitiveFields) {
444
- if (sanitized.details[field]) {
445
- sanitized.details[field] = "[REDACTED]";
445
+ if (details[field]) {
446
+ details[field] = "[REDACTED]";
446
447
  }
447
448
  }
448
449
  }
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sources":["../src/errors.ts"],"sourcesContent":["/**\n * Comprehensive error handling system for SMRT framework\n *\n * Provides specialized error types for different failure scenarios\n * with proper error codes, messages, and debugging information.\n */\n\n/**\n * Abstract base class for all SMRT framework errors.\n *\n * Adds a structured `code` (machine-readable string constant), a `category`\n * (coarse error domain), optional structured `details`, and an optional\n * causal `Error` chain on top of the standard `Error` class.\n *\n * Never throw `SmrtError` directly — use one of the concrete subclasses\n * (`DatabaseError`, `AIError`, `ValidationError`, etc.) or their static\n * factory methods for consistent error codes and messages.\n *\n * @example\n * ```typescript\n * try {\n * await product.save();\n * } catch (err) {\n * if (err instanceof ValidationError) {\n * console.error(err.code, err.details); // 'VALIDATION_REQUIRED_FIELD', { fieldName, objectType }\n * }\n * if (err instanceof SmrtError) {\n * logger.error(ErrorUtils.sanitizeError(err));\n * }\n * }\n * ```\n */\n\nimport { createLogger } from '@happyvertical/logger';\n\nconst logger = createLogger({ level: 'info' });\n\nexport abstract class SmrtError extends Error {\n public readonly code: string;\n public readonly category:\n | 'database'\n | 'ai'\n | 'filesystem'\n | 'validation'\n | 'network'\n | 'configuration'\n | 'runtime';\n public readonly details?: Record<string, any>;\n public readonly cause?: Error;\n\n constructor(\n message: string,\n code: string,\n category: SmrtError['category'],\n details?: Record<string, any>,\n cause?: Error,\n ) {\n super(message);\n this.name = this.constructor.name;\n this.code = code;\n this.category = category;\n this.details = details;\n this.cause = cause;\n\n // Maintain proper stack trace for V8\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Converts error to a serializable object for logging/debugging\n */\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n category: this.category,\n details: this.details,\n stack: this.stack,\n cause: this.cause\n ? {\n name: this.cause.name,\n message: this.cause.message,\n stack: this.cause.stack,\n }\n : undefined,\n };\n }\n}\n\ntype ErrorLikeWithContext = Error & {\n cause?: unknown;\n context?: {\n originalError?: unknown;\n };\n};\n\nfunction collectErrorMessages(\n value: unknown,\n messages: string[],\n visited: Set<unknown>,\n depth = 0,\n): void {\n if (!value || visited.has(value) || depth > 10) {\n return;\n }\n\n visited.add(value);\n\n if (typeof value === 'string') {\n const trimmed = value.trim();\n if (trimmed) {\n messages.push(trimmed);\n }\n return;\n }\n\n if (!(value instanceof Error)) {\n return;\n }\n\n const message = value.message?.trim();\n if (message) {\n messages.push(message);\n }\n\n const errorWithContext = value as ErrorLikeWithContext;\n collectErrorMessages(\n errorWithContext.context?.originalError,\n messages,\n visited,\n depth + 1,\n );\n collectErrorMessages(errorWithContext.cause, messages, visited, depth + 1);\n}\n\nfunction getPrimaryCauseMessage(cause?: Error): {\n message?: string;\n messages?: string[];\n} {\n if (!cause) {\n return {};\n }\n\n const collected: string[] = [];\n collectErrorMessages(cause, collected, new Set<unknown>());\n\n const uniqueMessages = [...new Set(collected.filter(Boolean))];\n if (uniqueMessages.length === 0) {\n return {};\n }\n\n return {\n message: uniqueMessages[uniqueMessages.length - 1],\n messages: uniqueMessages,\n };\n}\n\n/**\n * Errors originating from database operations.\n *\n * Use the static factory methods rather than the constructor directly:\n * - `DatabaseError.connectionFailed(url, cause)` — DB connection failure\n * - `DatabaseError.queryFailed(query, cause)` — SQL execution error\n * - `DatabaseError.schemaError(table, op, cause)` — DDL/migration error\n * - `DatabaseError.constraintViolation(constraint, value, cause)` — FK/CHECK/UNIQUE\n * - `DatabaseError.corruptedData(field, class, cause)` — unparse-able column data\n * - `DatabaseError.missingDiscriminator(class, rowId)` — STI row missing `_meta_type`\n * - `DatabaseError.stiDiscriminatorConflict(...)` — legacy STI discriminator collides during qualification\n * - `DatabaseError.schemaMissing(table, class)` — table not yet migrated\n *\n * All errors have `category: 'database'` and codes prefixed with `DB_`.\n */\nexport class DatabaseError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, any>,\n cause?: Error,\n ) {\n super(message, code, 'database', details, cause);\n }\n\n static connectionFailed(dbUrl: string, cause?: Error): DatabaseError {\n return new DatabaseError(\n `Failed to connect to database: ${dbUrl}`,\n 'DB_CONNECTION_FAILED',\n { dbUrl },\n cause,\n );\n }\n\n static queryFailed(query: string, cause?: Error): DatabaseError {\n // Include the deepest actionable cause message for better debugging.\n const causeInfo = getPrimaryCauseMessage(cause);\n const causeMsg = causeInfo.message ? `\\nCause: ${causeInfo.message}` : '';\n return new DatabaseError(\n `Database query failed: ${query.substring(0, 100)}${query.length > 100 ? '...' : ''}${causeMsg}`,\n 'DB_QUERY_FAILED',\n {\n query,\n causeMessage: causeInfo.message,\n causeMessages: causeInfo.messages,\n },\n cause,\n );\n }\n\n static schemaError(\n tableName: string,\n operation: string,\n cause?: Error,\n ): DatabaseError {\n return new DatabaseError(\n `Schema operation failed for table '${tableName}': ${operation}`,\n 'DB_SCHEMA_ERROR',\n { tableName, operation },\n cause,\n );\n }\n\n static constraintViolation(\n constraint: string,\n value: any,\n cause?: Error,\n ): DatabaseError {\n return new DatabaseError(\n `Database constraint violation: ${constraint}`,\n 'DB_CONSTRAINT_VIOLATION',\n { constraint, value },\n cause,\n );\n }\n\n static corruptedData(\n fieldName: string,\n className: string,\n cause?: Error,\n ): DatabaseError {\n return new DatabaseError(\n `Corrupted data in field '${fieldName}' for ${className}. ` +\n `The data cannot be parsed or is malformed. ` +\n `This may indicate database corruption or incompatible schema changes.`,\n 'DB_CORRUPTED_DATA',\n { fieldName, className },\n cause,\n );\n }\n\n static missingDiscriminator(\n className: string,\n rowId?: string,\n ): DatabaseError {\n return new DatabaseError(\n `Missing discriminator (_meta_type) for STI class ${className}${rowId ? ` (row id: ${rowId})` : ''}. ` +\n `STI classes require a discriminator column to determine the correct subclass. ` +\n `This may indicate a schema mismatch or manual database modification.`,\n 'DB_MISSING_DISCRIMINATOR',\n { className, rowId },\n );\n }\n\n static stiDiscriminatorConflict(details: {\n className: string;\n tableName: string;\n id: string;\n slug: string;\n context: string;\n conflictIdentity: Record<string, any>;\n legacyMetaType: string;\n qualifiedMetaType: string;\n duplicateId: string;\n }): DatabaseError {\n const identityText = Object.entries(details.conflictIdentity)\n .map(([key, value]) => `${key} '${String(value)}'`)\n .join(', ');\n\n return new DatabaseError(\n `Legacy STI discriminator collision for ${details.className} (${details.tableName}). ` +\n `Row '${details.id}' would upgrade _meta_type from '${details.legacyMetaType}' to '${details.qualifiedMetaType}', ` +\n `but row '${details.duplicateId}' already uses the qualified discriminator for ${identityText || 'the same conflict identity'}. ` +\n `Merge or remove the duplicate legacy/qualified rows before saving.`,\n 'DB_STI_DISCRIMINATOR_CONFLICT',\n details,\n );\n }\n\n static schemaMissing(tableName: string, className: string): DatabaseError {\n return new DatabaseError(\n `Table '${tableName}' does not exist for class '${className}'. ` +\n `Run 'smrt db:migrate' to create database schema.`,\n 'DB_SCHEMA_MISSING',\n { tableName, className },\n );\n }\n}\n\n/**\n * Errors from AI provider integrations.\n *\n * Use the static factory methods:\n * - `AIError.providerError(provider, operation, cause)` — generic provider failure\n * - `AIError.rateLimitExceeded(provider, retryAfter)` — rate limit hit\n * - `AIError.invalidResponse(provider, response)` — unexpected response shape\n * - `AIError.authenticationFailed(provider)` — bad API key / credentials\n *\n * All errors have `category: 'ai'` and codes prefixed with `AI_`.\n * AI errors are considered retryable by `ErrorUtils.isRetryable()`.\n */\nexport class AIError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, any>,\n cause?: Error,\n ) {\n super(message, code, 'ai', details, cause);\n }\n\n static providerError(\n provider: string,\n operation: string,\n cause?: Error,\n ): AIError {\n return new AIError(\n `AI provider '${provider}' failed during ${operation}`,\n 'AI_PROVIDER_ERROR',\n { provider, operation },\n cause,\n );\n }\n\n static rateLimitExceeded(provider: string, retryAfter?: number): AIError {\n return new AIError(\n `AI provider '${provider}' rate limit exceeded`,\n 'AI_RATE_LIMIT',\n { provider, retryAfter },\n );\n }\n\n static invalidResponse(provider: string, response: any): AIError {\n return new AIError(\n `AI provider '${provider}' returned invalid response`,\n 'AI_INVALID_RESPONSE',\n { provider, response },\n );\n }\n\n static authenticationFailed(provider: string): AIError {\n return new AIError(\n `AI provider '${provider}' authentication failed`,\n 'AI_AUTH_FAILED',\n { provider },\n );\n }\n}\n\n/**\n * Errors from filesystem operations.\n *\n * Use the static factory methods:\n * - `FilesystemError.fileNotFound(path)` — file does not exist\n * - `FilesystemError.permissionDenied(path, operation)` — access denied\n * - `FilesystemError.diskSpaceExceeded(path, requiredBytes)` — insufficient space\n *\n * All errors have `category: 'filesystem'` and codes prefixed with `FS_`.\n */\nexport class FilesystemError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, any>,\n cause?: Error,\n ) {\n super(message, code, 'filesystem', details, cause);\n }\n\n static fileNotFound(path: string): FilesystemError {\n return new FilesystemError(`File not found: ${path}`, 'FS_FILE_NOT_FOUND', {\n path,\n });\n }\n\n static permissionDenied(path: string, operation: string): FilesystemError {\n return new FilesystemError(\n `Permission denied for ${operation} on: ${path}`,\n 'FS_PERMISSION_DENIED',\n { path, operation },\n );\n }\n\n static diskSpaceExceeded(\n path: string,\n requiredBytes: number,\n ): FilesystemError {\n return new FilesystemError(\n `Insufficient disk space for operation on: ${path}`,\n 'FS_DISK_SPACE_EXCEEDED',\n { path, requiredBytes },\n );\n }\n}\n\n/**\n * Input/data validation errors thrown before or during a database operation.\n *\n * `save()` throws `ValidationError` when field validation fails. The collection's\n * `convertWhereKeys()` throws it for invalid WHERE clause operators or field names.\n * `ValidationError` is **not** retried by `ErrorUtils.withRetry()`.\n *\n * Use the static factory methods:\n * - `ValidationError.requiredField(field, objectType)` — missing required field\n * - `ValidationError.invalidValue(field, value, expected)` — wrong type/format\n * - `ValidationError.uniqueConstraint(field, value)` — duplicate unique value\n * - `ValidationError.rangeError(field, value, min?, max?)` — out of allowed range\n *\n * All errors have `category: 'validation'` and codes prefixed with `VALIDATION_`.\n */\nexport class ValidationError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, any>,\n cause?: Error,\n ) {\n super(message, code, 'validation', details, cause);\n }\n\n static requiredField(fieldName: string, objectType: string): ValidationError {\n return new ValidationError(\n `Required field '${fieldName}' is missing for ${objectType}`,\n 'VALIDATION_REQUIRED_FIELD',\n { fieldName, objectType },\n );\n }\n\n static invalidValue(\n fieldName: string,\n value: any,\n expectedType: string,\n ): ValidationError {\n return new ValidationError(\n `Invalid value for field '${fieldName}': expected ${expectedType}, got ${typeof value}`,\n 'VALIDATION_INVALID_VALUE',\n { fieldName, value, expectedType },\n );\n }\n\n static uniqueConstraint(fieldName: string, value: any): ValidationError {\n return new ValidationError(\n `Unique constraint violation for field '${fieldName}' with value: ${value}`,\n 'VALIDATION_UNIQUE_CONSTRAINT',\n { fieldName, value },\n );\n }\n\n static rangeError(\n fieldName: string,\n value: number,\n min?: number,\n max?: number,\n ): ValidationError {\n const range =\n min !== undefined && max !== undefined\n ? `between ${min} and ${max}`\n : min !== undefined\n ? `>= ${min}`\n : `<= ${max}`;\n\n return new ValidationError(\n `Value for field '${fieldName}' must be ${range}, got: ${value}`,\n 'VALIDATION_RANGE_ERROR',\n { fieldName, value, min, max },\n );\n }\n}\n\n/**\n * Errors from HTTP and external network operations.\n *\n * Use the static factory methods:\n * - `NetworkError.requestFailed(url, status?, body?)` — non-2xx response or connection failure\n * - `NetworkError.timeout(url, timeoutMs)` — request exceeded timeout\n * - `NetworkError.serviceUnavailable(service, reason?)` — external service down\n *\n * All errors have `category: 'network'` and codes prefixed with `NETWORK_`.\n * Network errors are considered retryable by `ErrorUtils.isRetryable()`.\n */\nexport class NetworkError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, any>,\n cause?: Error,\n ) {\n super(message, code, 'network', details, cause);\n }\n\n static requestFailed(\n url: string,\n status?: number,\n responseBody?: string | Error,\n ): NetworkError {\n const cause = responseBody instanceof Error ? responseBody : undefined;\n const body = typeof responseBody === 'string' ? responseBody : undefined;\n return new NetworkError(\n `Network request failed: ${url}${status ? ` (Status: ${status})` : ''}${body ? ` - ${body.substring(0, 200)}` : ''}`,\n 'NETWORK_REQUEST_FAILED',\n { url, status, responseBody: body },\n cause,\n );\n }\n\n static timeout(url: string, timeoutMs: number): NetworkError {\n return new NetworkError(\n `Network request timed out after ${timeoutMs}ms: ${url}`,\n 'NETWORK_TIMEOUT',\n { url, timeoutMs },\n );\n }\n\n static serviceUnavailable(service: string, reason?: string): NetworkError {\n return new NetworkError(\n reason\n ? `External service unavailable: ${service} - ${reason}`\n : `External service unavailable: ${service}`,\n 'NETWORK_SERVICE_UNAVAILABLE',\n { service, reason },\n );\n }\n}\n\n/**\n * Errors from misconfigured or incompatible class/framework setup.\n *\n * These are typically thrown during class registration (i.e. at module load time),\n * not during normal request handling.\n *\n * Use the static factory methods:\n * - `ConfigurationError.missingConfiguration(key, context?)` — missing required config\n * - `ConfigurationError.invalidConfiguration(key, value, expected)` — wrong config type/value\n * - `ConfigurationError.initializationFailed(component, cause?)` — component failed to start\n * - `ConfigurationError.circularInheritance(class, chain)` — circular class inheritance\n * - `ConfigurationError.incompatibleStrategy(class, strategy, parent, parentStrategy)` — STI mismatch\n * - `ConfigurationError.unregisteredBaseClass(child, base)` — STI base not yet registered\n *\n * All errors have `category: 'configuration'` and codes prefixed with `CONFIG_`.\n * Configuration errors are **not** retried by `ErrorUtils.withRetry()`.\n */\nexport class ConfigurationError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, any>,\n cause?: Error,\n ) {\n super(message, code, 'configuration', details, cause);\n }\n\n static missingConfiguration(\n configKey: string,\n context?: string,\n ): ConfigurationError {\n return new ConfigurationError(\n `Missing required configuration: ${configKey}${context ? ` in ${context}` : ''}`,\n 'CONFIG_MISSING',\n { configKey, context },\n );\n }\n\n static invalidConfiguration(\n configKey: string,\n value: any,\n expected: string,\n ): ConfigurationError {\n return new ConfigurationError(\n `Invalid configuration for ${configKey}: expected ${expected}, got ${typeof value}`,\n 'CONFIG_INVALID',\n { configKey, value, expected },\n );\n }\n\n static initializationFailed(\n component: string,\n cause?: Error,\n ): ConfigurationError {\n return new ConfigurationError(\n `Failed to initialize component: ${component}`,\n 'CONFIG_INIT_FAILED',\n { component },\n cause,\n );\n }\n\n static circularInheritance(\n className: string,\n inheritanceChain: string[],\n ): ConfigurationError {\n return new ConfigurationError(\n `Circular inheritance detected for class '${className}'. ` +\n `Inheritance chain: ${inheritanceChain.join(' → ')} → ${className}. ` +\n `Classes cannot inherit from themselves directly or indirectly.`,\n 'CONFIG_CIRCULAR_INHERITANCE',\n { className, inheritanceChain },\n );\n }\n\n static incompatibleStrategy(\n className: string,\n classStrategy: string,\n parentClass: string,\n parentStrategy: string,\n ): ConfigurationError {\n return new ConfigurationError(\n `Incompatible table strategy for class '${className}' (${classStrategy}). ` +\n `Parent class '${parentClass}' uses ${parentStrategy} strategy. ` +\n `Child classes must use the same table strategy as their parent. ` +\n `Either change ${className} to use ${parentStrategy}, or remove the inheritance.`,\n 'CONFIG_INCOMPATIBLE_STRATEGY',\n { className, classStrategy, parentClass, parentStrategy },\n );\n }\n\n static unregisteredBaseClass(\n childClass: string,\n baseClass: string,\n ): ConfigurationError {\n return new ConfigurationError(\n `STI base class '${baseClass}' is not registered for child class '${childClass}'. ` +\n `When using Single Table Inheritance, the base class must be registered before any child classes. ` +\n `Ensure ${baseClass} is decorated with @smrt({ tableStrategy: 'sti' }) and imported before ${childClass}.`,\n 'CONFIG_UNREGISTERED_BASE',\n { childClass, baseClass },\n );\n }\n}\n\n/**\n * Errors representing unexpected runtime failures not covered by other categories.\n *\n * `RuntimeError` is the catch-all for internal framework errors — invalid object\n * state, exhausted resources, or failures in operations like `save()` and `loadFromId()`\n * that propagate from an unknown cause.\n *\n * Use the static factory methods:\n * - `RuntimeError.operationFailed(operation, context?, cause?)` — generic operation failure\n * - `RuntimeError.invalidState(message, context?)` — unexpected object/system state\n * - `RuntimeError.resourceExhausted(resource, limit)` — limit exceeded (e.g. connections)\n *\n * All errors have `category: 'runtime'` and codes prefixed with `RUNTIME_`.\n */\nexport class RuntimeError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, any>,\n cause?: Error,\n ) {\n super(message, code, 'runtime', details, cause);\n }\n\n static operationFailed(\n operation: string,\n context?: string,\n cause?: Error,\n ): RuntimeError {\n return new RuntimeError(\n `Operation failed: ${operation}${context ? ` in ${context}` : ''}`,\n 'RUNTIME_OPERATION_FAILED',\n { operation, context },\n cause,\n );\n }\n\n static invalidState(\n message: string,\n context?: Record<string, any>,\n ): RuntimeError {\n return new RuntimeError(message, 'RUNTIME_INVALID_STATE', context);\n }\n\n static resourceExhausted(resource: string, limit: number): RuntimeError {\n return new RuntimeError(\n `Resource exhausted: ${resource} exceeded limit of ${limit}`,\n 'RUNTIME_RESOURCE_EXHAUSTED',\n { resource, limit },\n );\n }\n}\n\n/**\n * Error thrown when a tenant isolation boundary is crossed while resolving a\n * relationship.\n *\n * Raised by {@link SmrtObject.loadRelated} / {@link SmrtObject.loadRelatedMany}\n * (and {@link SmrtObject.getRelated}, which delegates to them) when a\n * tenant-scoped object resolves a relationship to an object belonging to a\n * *different*, non-null tenant — the genuine cross-tenant data leak. The guard\n * is a no-op when either side has a `null` tenant (global / non-tenant-scoped\n * models) and when both sides share the same tenant, so it only fires on real\n * leaks. Pass `{ allowCrossTenant: true }` to the loader to deliberately opt out.\n *\n * The `code` is always `'TENANT_ISOLATION_VIOLATION'` and the category is\n * `'validation'`. It is never retried — `ErrorUtils.withRetry()` rethrows it\n * immediately and `ErrorUtils.isRetryable()` returns `false` — because a tenant\n * boundary violation is deterministic. `tenantId` is the owning object's tenant\n * and `attemptedTenantId` is the tenant of the object that was reached.\n *\n * This shares its stable `code`, `name`, `tenantId`, and `attemptedTenantId`\n * shape with the interceptor-level `TenantIsolationError` in\n * `@happyvertical/smrt-tenancy`, so cross-cutting handlers can match either via\n * `err.code === 'TENANT_ISOLATION_VIOLATION'`. They are intentionally distinct\n * classes because `@happyvertical/smrt-core` cannot depend on the tenancy\n * package (the dependency runs the other way).\n *\n * @example\n * ```typescript\n * try {\n * await order.loadRelated('customerId');\n * } catch (err) {\n * if (err instanceof TenantIsolationError) {\n * // err.tenantId — the order's tenant\n * // err.attemptedTenantId — the customer's tenant\n * }\n * }\n * ```\n *\n * @see SmrtObject.loadRelated\n * @see SmrtObject.loadRelatedMany\n */\nexport class TenantIsolationError extends SmrtError {\n /** The tenant ID of the object that owns the relationship. */\n public readonly tenantId?: string;\n /** The tenant ID of the related object that was reached (and rejected). */\n public readonly attemptedTenantId?: string;\n\n constructor(\n message: string,\n details?: {\n tenantId?: string;\n attemptedTenantId?: string;\n [key: string]: any;\n },\n cause?: Error,\n ) {\n super(message, 'TENANT_ISOLATION_VIOLATION', 'validation', details, cause);\n this.tenantId = details?.tenantId;\n this.attemptedTenantId = details?.attemptedTenantId;\n }\n\n /**\n * Builds a {@link TenantIsolationError} for a blocked cross-tenant\n * relationship resolution, with a descriptive message and structured details.\n */\n static crossTenantReference(details: {\n sourceClass: string;\n fieldName: string;\n sourceTenantId: string;\n targetClass?: string;\n targetTenantId: string;\n }): TenantIsolationError {\n const target = details.targetClass\n ? `${details.targetClass} (tenant '${details.targetTenantId}')`\n : `tenant '${details.targetTenantId}'`;\n return new TenantIsolationError(\n `Cross-tenant relationship access blocked on ${details.sourceClass}.${details.fieldName}: ` +\n `owning tenant '${details.sourceTenantId}' does not match ${target}. ` +\n `Pass { allowCrossTenant: true } to loadRelated()/loadRelatedMany()/getRelated() to override.`,\n {\n tenantId: details.sourceTenantId,\n attemptedTenantId: details.targetTenantId,\n sourceClass: details.sourceClass,\n fieldName: details.fieldName,\n targetClass: details.targetClass,\n },\n );\n }\n}\n\n/**\n * Utility functions for error handling\n */\nexport class ErrorUtils {\n /**\n * Wraps a function with error handling and automatic retry logic\n */\n static async withRetry<T>(\n operation: () => Promise<T>,\n maxRetries = 3,\n delay = 1000,\n backoffMultiplier = 2,\n ): Promise<T> {\n let lastError: Error = new Error('Operation failed without error details');\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n if (attempt === maxRetries) {\n throw lastError;\n }\n\n // Skip retry for certain error types. A tenant isolation violation is\n // deterministic — retrying re-fetches the same cross-tenant target — and\n // is a security boundary, so it must never be retried.\n if (\n error instanceof ValidationError ||\n error instanceof ConfigurationError ||\n error instanceof TenantIsolationError\n ) {\n throw error;\n }\n\n // Wait before retrying with exponential backoff\n // Wrap in try-catch to handle any potential timer errors\n try {\n await new Promise<void>((resolve) => {\n setTimeout(() => resolve(), delay * backoffMultiplier ** attempt);\n });\n } catch (timerError) {\n // Log timer error but don't fail the retry\n logger.error('Timer error during retry', { error: timerError });\n }\n }\n }\n\n throw lastError;\n }\n\n /**\n * Checks if an error is retryable\n */\n static isRetryable(error: Error): boolean {\n if (error instanceof SmrtError) {\n return error.category === 'network' || error.category === 'ai';\n }\n\n // Check for common retryable error patterns\n const retryablePatterns = [\n /ECONNRESET/,\n /ETIMEDOUT/,\n /ENOTFOUND/,\n /rate.?limit/i,\n /timeout/i,\n /503/,\n /502/,\n /500/,\n ];\n\n return retryablePatterns.some((pattern) => pattern.test(error.message));\n }\n\n /**\n * Sanitizes an error for safe logging (removes sensitive information)\n */\n static sanitizeError(error: Error): Record<string, any> {\n const sanitized: Record<string, any> = {\n name: error.name,\n message: error.message,\n stack: error.stack,\n };\n\n if (error instanceof SmrtError) {\n sanitized.code = error.code;\n sanitized.category = error.category;\n\n // Sanitize details to remove potential sensitive information\n if (error.details) {\n sanitized.details = { ...error.details };\n\n // Remove common sensitive fields\n const sensitiveFields = [\n 'password',\n 'token',\n 'key',\n 'secret',\n 'apiKey',\n ];\n for (const field of sensitiveFields) {\n if (sanitized.details[field]) {\n sanitized.details[field] = '[REDACTED]';\n }\n }\n }\n }\n\n return sanitized;\n }\n}\n\n/**\n * Validation report that collects multiple validation errors\n *\n * Useful for validating an entire object and reporting all errors\n * at once rather than stopping at the first error.\n *\n * @example\n * ```typescript\n * const report = new ValidationReport('Product');\n * report.addError(ValidationError.requiredField('name', 'Product'));\n * report.addError(ValidationError.rangeError('price', -10, 0));\n *\n * if (report.hasErrors()) {\n * console.error(report.toString());\n * // Output:\n * // Validation failed for Product with 2 errors:\n * // - name: Required field 'name' is missing for Product\n * // - price: Value -10 for field 'price' is outside allowed range [0, undefined]\n * }\n * ```\n */\nexport class ValidationReport {\n private errors: ValidationError[] = [];\n private objectType: string;\n\n constructor(objectType: string) {\n this.objectType = objectType;\n }\n\n /**\n * Add a validation error to the report\n */\n addError(error: ValidationError): void {\n this.errors.push(error);\n }\n\n /**\n * Check if there are any validation errors\n */\n hasErrors(): boolean {\n return this.errors.length > 0;\n }\n\n /**\n * Get all validation errors\n */\n getErrors(): ValidationError[] {\n return [...this.errors];\n }\n\n /**\n * Get the number of validation errors\n */\n getErrorCount(): number {\n return this.errors.length;\n }\n\n /**\n * Convert to a human-readable string\n */\n toString(): string {\n if (this.errors.length === 0) {\n return `Validation passed for ${this.objectType}`;\n }\n\n const errorList = this.errors\n .map((err, idx) => ` ${idx + 1}. ${err.message}`)\n .join('\\n');\n\n return `Validation failed for ${this.objectType} with ${this.errors.length} error(s):\\n${errorList}`;\n }\n\n /**\n * Convert to JSON format\n */\n toJSON(): object {\n return {\n objectType: this.objectType,\n errorCount: this.errors.length,\n errors: this.errors.map((err) => err.toJSON()),\n };\n }\n\n /**\n * Throw the first error if there are any errors\n */\n throwIfErrors(): void {\n if (this.errors.length > 0) {\n throw this.errors[0];\n }\n }\n\n /**\n * Clear all errors\n */\n clear(): void {\n this.errors = [];\n }\n}\n\n/**\n * Validation utility functions\n */\nexport class ValidationUtils {\n /**\n * Validate a single field value\n *\n * @param fieldName - Name of the field\n * @param value - Value to validate\n * @param options - Validation options (required, min, max, etc.)\n * @returns ValidationError if validation fails, null otherwise\n */\n static async validateField(\n fieldName: string,\n value: any,\n options: {\n required?: boolean;\n min?: number;\n max?: number;\n minLength?: number;\n maxLength?: number;\n pattern?: string | RegExp;\n type?: string;\n customValidator?: (value: any) => boolean | Promise<boolean>;\n customMessage?: string;\n },\n objectType: string = 'Object',\n ): Promise<ValidationError | null> {\n // Required check\n if (\n options.required &&\n (value === null || value === undefined || value === '')\n ) {\n return ValidationError.requiredField(fieldName, objectType);\n }\n\n // Skip further validation if value is null/undefined and not required\n if (value === null || value === undefined) {\n return null;\n }\n\n // Numeric range validation\n if (typeof value === 'number') {\n if (options.min !== undefined && value < options.min) {\n return ValidationError.rangeError(\n fieldName,\n value,\n options.min,\n options.max,\n );\n }\n if (options.max !== undefined && value > options.max) {\n return ValidationError.rangeError(\n fieldName,\n value,\n options.min,\n options.max,\n );\n }\n }\n\n // String length validation\n if (typeof value === 'string') {\n if (options.minLength !== undefined && value.length < options.minLength) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string with minimum length ${options.minLength}`,\n );\n }\n if (options.maxLength !== undefined && value.length > options.maxLength) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string with maximum length ${options.maxLength}`,\n );\n }\n\n // Pattern validation\n if (options.pattern) {\n const regex =\n typeof options.pattern === 'string'\n ? new RegExp(options.pattern)\n : options.pattern;\n if (!regex.test(value)) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string matching pattern ${options.pattern}`,\n );\n }\n }\n }\n\n // Custom validator\n if (options.customValidator) {\n try {\n const isValid = await options.customValidator(value);\n if (!isValid) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n options.customMessage || 'custom validation failed',\n );\n }\n } catch (error) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `custom validation error: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n return null;\n }\n\n /**\n * Validate required field\n */\n static validateRequired(\n fieldName: string,\n value: any,\n objectType: string = 'Object',\n ): ValidationError | null {\n if (value === null || value === undefined || value === '') {\n return ValidationError.requiredField(fieldName, objectType);\n }\n return null;\n }\n\n /**\n * Validate numeric range\n */\n static validateRange(\n fieldName: string,\n value: number,\n min?: number,\n max?: number,\n ): ValidationError | null {\n if (min !== undefined && value < min) {\n return ValidationError.rangeError(fieldName, value, min, max);\n }\n if (max !== undefined && value > max) {\n return ValidationError.rangeError(fieldName, value, min, max);\n }\n return null;\n }\n\n /**\n * Validate string length\n */\n static validateLength(\n fieldName: string,\n value: string,\n minLength?: number,\n maxLength?: number,\n ): ValidationError | null {\n if (minLength !== undefined && value.length < minLength) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string with minimum length ${minLength}`,\n );\n }\n if (maxLength !== undefined && value.length > maxLength) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string with maximum length ${maxLength}`,\n );\n }\n return null;\n }\n\n /**\n * Validate string pattern\n */\n static validatePattern(\n fieldName: string,\n value: string,\n pattern: string | RegExp,\n ): ValidationError | null {\n const regex = typeof pattern === 'string' ? new RegExp(pattern) : pattern;\n if (!regex.test(value)) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string matching pattern ${pattern}`,\n );\n }\n return null;\n }\n}\n"],"names":[],"mappings":";AAmCA,MAAM,SAAS,aAAa,EAAE,OAAO,QAAQ;AAEtC,MAAe,kBAAkB,MAAM;AAAA,EAC5B;AAAA,EACA;AAAA,EAQA;AAAA,EACA;AAAA,EAEhB,YACE,SACA,MACA,UACA,SACA,OACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO,KAAK,YAAY;AAC7B,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,SAAK,UAAU;AACf,SAAK,QAAQ;AAGb,QAAI,MAAM,mBAAmB;AAC3B,YAAM,kBAAkB,MAAM,KAAK,WAAW;AAAA,IAChD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,SAAS;AACP,WAAO;AAAA,MACL,MAAM,KAAK;AAAA,MACX,SAAS,KAAK;AAAA,MACd,MAAM,KAAK;AAAA,MACX,UAAU,KAAK;AAAA,MACf,SAAS,KAAK;AAAA,MACd,OAAO,KAAK;AAAA,MACZ,OAAO,KAAK,QACR;AAAA,QACE,MAAM,KAAK,MAAM;AAAA,QACjB,SAAS,KAAK,MAAM;AAAA,QACpB,OAAO,KAAK,MAAM;AAAA,MAAA,IAEpB;AAAA,IAAA;AAAA,EAER;AACF;A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,QACA;AAAA,QACA,8BAA8B,SAAS;AAAA,MAAA;AAAA,IAE3C;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,gBACL,WACA,OACA,SACwB;AACxB,UAAM,QAAQ,OAAO,YAAY,WAAW,IAAI,OAAO,OAAO,IAAI;AAClE,QAAI,CAAC,MAAM,KAAK,KAAK,GAAG;AACtB,aAAO,gBAAgB;AAAA,QACrB;AAAA,QACA;AAAA,QACA,2BAA2B,OAAO;AAAA,MAAA;AAAA,IAEtC;AACA,WAAO;AAAA,EACT;AACF;"}
1
+ {"version":3,"file":"errors.js","sources":["../src/errors.ts"],"sourcesContent":["/**\n * Comprehensive error handling system for SMRT framework\n *\n * Provides specialized error types for different failure scenarios\n * with proper error codes, messages, and debugging information.\n */\n\n/**\n * Abstract base class for all SMRT framework errors.\n *\n * Adds a structured `code` (machine-readable string constant), a `category`\n * (coarse error domain), optional structured `details`, and an optional\n * causal `Error` chain on top of the standard `Error` class.\n *\n * Never throw `SmrtError` directly — use one of the concrete subclasses\n * (`DatabaseError`, `AIError`, `ValidationError`, etc.) or their static\n * factory methods for consistent error codes and messages.\n *\n * @example\n * ```typescript\n * try {\n * await product.save();\n * } catch (err) {\n * if (err instanceof ValidationError) {\n * console.error(err.code, err.details); // 'VALIDATION_REQUIRED_FIELD', { fieldName, objectType }\n * }\n * if (err instanceof SmrtError) {\n * logger.error(ErrorUtils.sanitizeError(err));\n * }\n * }\n * ```\n */\n\nimport { createLogger } from '@happyvertical/logger';\n\nconst logger = createLogger({ level: 'info' });\n\nexport abstract class SmrtError extends Error {\n public readonly code: string;\n public readonly category:\n | 'database'\n | 'ai'\n | 'filesystem'\n | 'validation'\n | 'network'\n | 'configuration'\n | 'runtime';\n public readonly details?: Record<string, unknown>;\n public readonly cause?: Error;\n\n constructor(\n message: string,\n code: string,\n category: SmrtError['category'],\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message);\n this.name = this.constructor.name;\n this.code = code;\n this.category = category;\n this.details = details;\n this.cause = cause;\n\n // Maintain proper stack trace for V8\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Converts error to a serializable object for logging/debugging\n */\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n category: this.category,\n details: this.details,\n stack: this.stack,\n cause: this.cause\n ? {\n name: this.cause.name,\n message: this.cause.message,\n stack: this.cause.stack,\n }\n : undefined,\n };\n }\n}\n\ntype ErrorLikeWithContext = Error & {\n cause?: unknown;\n context?: {\n originalError?: unknown;\n };\n};\n\nfunction collectErrorMessages(\n value: unknown,\n messages: string[],\n visited: Set<unknown>,\n depth = 0,\n): void {\n if (!value || visited.has(value) || depth > 10) {\n return;\n }\n\n visited.add(value);\n\n if (typeof value === 'string') {\n const trimmed = value.trim();\n if (trimmed) {\n messages.push(trimmed);\n }\n return;\n }\n\n if (!(value instanceof Error)) {\n return;\n }\n\n const message = value.message?.trim();\n if (message) {\n messages.push(message);\n }\n\n const errorWithContext = value as ErrorLikeWithContext;\n collectErrorMessages(\n errorWithContext.context?.originalError,\n messages,\n visited,\n depth + 1,\n );\n collectErrorMessages(errorWithContext.cause, messages, visited, depth + 1);\n}\n\nfunction getPrimaryCauseMessage(cause?: Error): {\n message?: string;\n messages?: string[];\n} {\n if (!cause) {\n return {};\n }\n\n const collected: string[] = [];\n collectErrorMessages(cause, collected, new Set<unknown>());\n\n const uniqueMessages = [...new Set(collected.filter(Boolean))];\n if (uniqueMessages.length === 0) {\n return {};\n }\n\n return {\n message: uniqueMessages[uniqueMessages.length - 1],\n messages: uniqueMessages,\n };\n}\n\n/**\n * Errors originating from database operations.\n *\n * Use the static factory methods rather than the constructor directly:\n * - `DatabaseError.connectionFailed(url, cause)` — DB connection failure\n * - `DatabaseError.queryFailed(query, cause)` — SQL execution error\n * - `DatabaseError.schemaError(table, op, cause)` — DDL/migration error\n * - `DatabaseError.constraintViolation(constraint, value, cause)` — FK/CHECK/UNIQUE\n * - `DatabaseError.corruptedData(field, class, cause)` — unparse-able column data\n * - `DatabaseError.missingDiscriminator(class, rowId)` — STI row missing `_meta_type`\n * - `DatabaseError.stiDiscriminatorConflict(...)` — legacy STI discriminator collides during qualification\n * - `DatabaseError.schemaMissing(table, class)` — table not yet migrated\n *\n * All errors have `category: 'database'` and codes prefixed with `DB_`.\n */\nexport class DatabaseError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'database', details, cause);\n }\n\n static connectionFailed(dbUrl: string, cause?: Error): DatabaseError {\n return new DatabaseError(\n `Failed to connect to database: ${dbUrl}`,\n 'DB_CONNECTION_FAILED',\n { dbUrl },\n cause,\n );\n }\n\n static queryFailed(query: string, cause?: Error): DatabaseError {\n // Include the deepest actionable cause message for better debugging.\n const causeInfo = getPrimaryCauseMessage(cause);\n const causeMsg = causeInfo.message ? `\\nCause: ${causeInfo.message}` : '';\n return new DatabaseError(\n `Database query failed: ${query.substring(0, 100)}${query.length > 100 ? '...' : ''}${causeMsg}`,\n 'DB_QUERY_FAILED',\n {\n query,\n causeMessage: causeInfo.message,\n causeMessages: causeInfo.messages,\n },\n cause,\n );\n }\n\n static schemaError(\n tableName: string,\n operation: string,\n cause?: Error,\n ): DatabaseError {\n return new DatabaseError(\n `Schema operation failed for table '${tableName}': ${operation}`,\n 'DB_SCHEMA_ERROR',\n { tableName, operation },\n cause,\n );\n }\n\n static constraintViolation(\n constraint: string,\n value: unknown,\n cause?: Error,\n ): DatabaseError {\n return new DatabaseError(\n `Database constraint violation: ${constraint}`,\n 'DB_CONSTRAINT_VIOLATION',\n { constraint, value },\n cause,\n );\n }\n\n static corruptedData(\n fieldName: string,\n className: string,\n cause?: Error,\n ): DatabaseError {\n return new DatabaseError(\n `Corrupted data in field '${fieldName}' for ${className}. ` +\n `The data cannot be parsed or is malformed. ` +\n `This may indicate database corruption or incompatible schema changes.`,\n 'DB_CORRUPTED_DATA',\n { fieldName, className },\n cause,\n );\n }\n\n static missingDiscriminator(\n className: string,\n rowId?: string,\n ): DatabaseError {\n return new DatabaseError(\n `Missing discriminator (_meta_type) for STI class ${className}${rowId ? ` (row id: ${rowId})` : ''}. ` +\n `STI classes require a discriminator column to determine the correct subclass. ` +\n `This may indicate a schema mismatch or manual database modification.`,\n 'DB_MISSING_DISCRIMINATOR',\n { className, rowId },\n );\n }\n\n static stiDiscriminatorConflict(details: {\n className: string;\n tableName: string;\n id: string;\n slug: string;\n context: string;\n conflictIdentity: Record<string, unknown>;\n legacyMetaType: string;\n qualifiedMetaType: string;\n duplicateId: string;\n }): DatabaseError {\n const identityText = Object.entries(details.conflictIdentity)\n .map(([key, value]) => `${key} '${String(value)}'`)\n .join(', ');\n\n return new DatabaseError(\n `Legacy STI discriminator collision for ${details.className} (${details.tableName}). ` +\n `Row '${details.id}' would upgrade _meta_type from '${details.legacyMetaType}' to '${details.qualifiedMetaType}', ` +\n `but row '${details.duplicateId}' already uses the qualified discriminator for ${identityText || 'the same conflict identity'}. ` +\n `Merge or remove the duplicate legacy/qualified rows before saving.`,\n 'DB_STI_DISCRIMINATOR_CONFLICT',\n details,\n );\n }\n\n static schemaMissing(tableName: string, className: string): DatabaseError {\n return new DatabaseError(\n `Table '${tableName}' does not exist for class '${className}'. ` +\n `Run 'smrt db:migrate' to create database schema.`,\n 'DB_SCHEMA_MISSING',\n { tableName, className },\n );\n }\n}\n\n/**\n * Errors from AI provider integrations.\n *\n * Use the static factory methods:\n * - `AIError.providerError(provider, operation, cause)` — generic provider failure\n * - `AIError.rateLimitExceeded(provider, retryAfter)` — rate limit hit\n * - `AIError.invalidResponse(provider, response)` — unexpected response shape\n * - `AIError.authenticationFailed(provider)` — bad API key / credentials\n *\n * All errors have `category: 'ai'` and codes prefixed with `AI_`.\n * AI errors are considered retryable by `ErrorUtils.isRetryable()`.\n */\nexport class AIError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'ai', details, cause);\n }\n\n static providerError(\n provider: string,\n operation: string,\n cause?: Error,\n ): AIError {\n return new AIError(\n `AI provider '${provider}' failed during ${operation}`,\n 'AI_PROVIDER_ERROR',\n { provider, operation },\n cause,\n );\n }\n\n static rateLimitExceeded(provider: string, retryAfter?: number): AIError {\n return new AIError(\n `AI provider '${provider}' rate limit exceeded`,\n 'AI_RATE_LIMIT',\n { provider, retryAfter },\n );\n }\n\n static invalidResponse(provider: string, response: unknown): AIError {\n return new AIError(\n `AI provider '${provider}' returned invalid response`,\n 'AI_INVALID_RESPONSE',\n { provider, response },\n );\n }\n\n static authenticationFailed(provider: string): AIError {\n return new AIError(\n `AI provider '${provider}' authentication failed`,\n 'AI_AUTH_FAILED',\n { provider },\n );\n }\n}\n\n/**\n * Errors from filesystem operations.\n *\n * Use the static factory methods:\n * - `FilesystemError.fileNotFound(path)` — file does not exist\n * - `FilesystemError.permissionDenied(path, operation)` — access denied\n * - `FilesystemError.diskSpaceExceeded(path, requiredBytes)` — insufficient space\n *\n * All errors have `category: 'filesystem'` and codes prefixed with `FS_`.\n */\nexport class FilesystemError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'filesystem', details, cause);\n }\n\n static fileNotFound(path: string): FilesystemError {\n return new FilesystemError(`File not found: ${path}`, 'FS_FILE_NOT_FOUND', {\n path,\n });\n }\n\n static permissionDenied(path: string, operation: string): FilesystemError {\n return new FilesystemError(\n `Permission denied for ${operation} on: ${path}`,\n 'FS_PERMISSION_DENIED',\n { path, operation },\n );\n }\n\n static diskSpaceExceeded(\n path: string,\n requiredBytes: number,\n ): FilesystemError {\n return new FilesystemError(\n `Insufficient disk space for operation on: ${path}`,\n 'FS_DISK_SPACE_EXCEEDED',\n { path, requiredBytes },\n );\n }\n}\n\n/**\n * Input/data validation errors thrown before or during a database operation.\n *\n * `save()` throws `ValidationError` when field validation fails. The collection's\n * `convertWhereKeys()` throws it for invalid WHERE clause operators or field names.\n * `ValidationError` is **not** retried by `ErrorUtils.withRetry()`.\n *\n * Use the static factory methods:\n * - `ValidationError.requiredField(field, objectType)` — missing required field\n * - `ValidationError.invalidValue(field, value, expected)` — wrong type/format\n * - `ValidationError.uniqueConstraint(field, value)` — duplicate unique value\n * - `ValidationError.rangeError(field, value, min?, max?)` — out of allowed range\n *\n * All errors have `category: 'validation'` and codes prefixed with `VALIDATION_`.\n */\nexport class ValidationError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'validation', details, cause);\n }\n\n static requiredField(fieldName: string, objectType: string): ValidationError {\n return new ValidationError(\n `Required field '${fieldName}' is missing for ${objectType}`,\n 'VALIDATION_REQUIRED_FIELD',\n { fieldName, objectType },\n );\n }\n\n static invalidValue(\n fieldName: string,\n value: unknown,\n expectedType: string,\n ): ValidationError {\n return new ValidationError(\n `Invalid value for field '${fieldName}': expected ${expectedType}, got ${typeof value}`,\n 'VALIDATION_INVALID_VALUE',\n { fieldName, value, expectedType },\n );\n }\n\n static uniqueConstraint(fieldName: string, value: unknown): ValidationError {\n return new ValidationError(\n `Unique constraint violation for field '${fieldName}' with value: ${String(value)}`,\n 'VALIDATION_UNIQUE_CONSTRAINT',\n { fieldName, value },\n );\n }\n\n static rangeError(\n fieldName: string,\n value: number,\n min?: number,\n max?: number,\n ): ValidationError {\n const range =\n min !== undefined && max !== undefined\n ? `between ${min} and ${max}`\n : min !== undefined\n ? `>= ${min}`\n : `<= ${max}`;\n\n return new ValidationError(\n `Value for field '${fieldName}' must be ${range}, got: ${value}`,\n 'VALIDATION_RANGE_ERROR',\n { fieldName, value, min, max },\n );\n }\n}\n\n/**\n * Errors from HTTP and external network operations.\n *\n * Use the static factory methods:\n * - `NetworkError.requestFailed(url, status?, body?)` — non-2xx response or connection failure\n * - `NetworkError.timeout(url, timeoutMs)` — request exceeded timeout\n * - `NetworkError.serviceUnavailable(service, reason?)` — external service down\n *\n * All errors have `category: 'network'` and codes prefixed with `NETWORK_`.\n * Network errors are considered retryable by `ErrorUtils.isRetryable()`.\n */\nexport class NetworkError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'network', details, cause);\n }\n\n static requestFailed(\n url: string,\n status?: number,\n responseBody?: string | Error,\n ): NetworkError {\n const cause = responseBody instanceof Error ? responseBody : undefined;\n const body = typeof responseBody === 'string' ? responseBody : undefined;\n return new NetworkError(\n `Network request failed: ${url}${status ? ` (Status: ${status})` : ''}${body ? ` - ${body.substring(0, 200)}` : ''}`,\n 'NETWORK_REQUEST_FAILED',\n { url, status, responseBody: body },\n cause,\n );\n }\n\n static timeout(url: string, timeoutMs: number): NetworkError {\n return new NetworkError(\n `Network request timed out after ${timeoutMs}ms: ${url}`,\n 'NETWORK_TIMEOUT',\n { url, timeoutMs },\n );\n }\n\n static serviceUnavailable(service: string, reason?: string): NetworkError {\n return new NetworkError(\n reason\n ? `External service unavailable: ${service} - ${reason}`\n : `External service unavailable: ${service}`,\n 'NETWORK_SERVICE_UNAVAILABLE',\n { service, reason },\n );\n }\n}\n\n/**\n * Errors from misconfigured or incompatible class/framework setup.\n *\n * These are typically thrown during class registration (i.e. at module load time),\n * not during normal request handling.\n *\n * Use the static factory methods:\n * - `ConfigurationError.missingConfiguration(key, context?)` — missing required config\n * - `ConfigurationError.invalidConfiguration(key, value, expected)` — wrong config type/value\n * - `ConfigurationError.initializationFailed(component, cause?)` — component failed to start\n * - `ConfigurationError.circularInheritance(class, chain)` — circular class inheritance\n * - `ConfigurationError.incompatibleStrategy(class, strategy, parent, parentStrategy)` — STI mismatch\n * - `ConfigurationError.unregisteredBaseClass(child, base)` — STI base not yet registered\n *\n * All errors have `category: 'configuration'` and codes prefixed with `CONFIG_`.\n * Configuration errors are **not** retried by `ErrorUtils.withRetry()`.\n */\nexport class ConfigurationError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'configuration', details, cause);\n }\n\n static missingConfiguration(\n configKey: string,\n context?: string,\n ): ConfigurationError {\n return new ConfigurationError(\n `Missing required configuration: ${configKey}${context ? ` in ${context}` : ''}`,\n 'CONFIG_MISSING',\n { configKey, context },\n );\n }\n\n static invalidConfiguration(\n configKey: string,\n value: unknown,\n expected: string,\n ): ConfigurationError {\n return new ConfigurationError(\n `Invalid configuration for ${configKey}: expected ${expected}, got ${typeof value}`,\n 'CONFIG_INVALID',\n { configKey, value, expected },\n );\n }\n\n static initializationFailed(\n component: string,\n cause?: Error,\n ): ConfigurationError {\n return new ConfigurationError(\n `Failed to initialize component: ${component}`,\n 'CONFIG_INIT_FAILED',\n { component },\n cause,\n );\n }\n\n static circularInheritance(\n className: string,\n inheritanceChain: string[],\n ): ConfigurationError {\n return new ConfigurationError(\n `Circular inheritance detected for class '${className}'. ` +\n `Inheritance chain: ${inheritanceChain.join(' → ')} → ${className}. ` +\n `Classes cannot inherit from themselves directly or indirectly.`,\n 'CONFIG_CIRCULAR_INHERITANCE',\n { className, inheritanceChain },\n );\n }\n\n static incompatibleStrategy(\n className: string,\n classStrategy: string,\n parentClass: string,\n parentStrategy: string,\n ): ConfigurationError {\n return new ConfigurationError(\n `Incompatible table strategy for class '${className}' (${classStrategy}). ` +\n `Parent class '${parentClass}' uses ${parentStrategy} strategy. ` +\n `Child classes must use the same table strategy as their parent. ` +\n `Either change ${className} to use ${parentStrategy}, or remove the inheritance.`,\n 'CONFIG_INCOMPATIBLE_STRATEGY',\n { className, classStrategy, parentClass, parentStrategy },\n );\n }\n\n static unregisteredBaseClass(\n childClass: string,\n baseClass: string,\n ): ConfigurationError {\n return new ConfigurationError(\n `STI base class '${baseClass}' is not registered for child class '${childClass}'. ` +\n `When using Single Table Inheritance, the base class must be registered before any child classes. ` +\n `Ensure ${baseClass} is decorated with @smrt({ tableStrategy: 'sti' }) and imported before ${childClass}.`,\n 'CONFIG_UNREGISTERED_BASE',\n { childClass, baseClass },\n );\n }\n}\n\n/**\n * Errors representing unexpected runtime failures not covered by other categories.\n *\n * `RuntimeError` is the catch-all for internal framework errors — invalid object\n * state, exhausted resources, or failures in operations like `save()` and `loadFromId()`\n * that propagate from an unknown cause.\n *\n * Use the static factory methods:\n * - `RuntimeError.operationFailed(operation, context?, cause?)` — generic operation failure\n * - `RuntimeError.invalidState(message, context?)` — unexpected object/system state\n * - `RuntimeError.resourceExhausted(resource, limit)` — limit exceeded (e.g. connections)\n *\n * All errors have `category: 'runtime'` and codes prefixed with `RUNTIME_`.\n */\nexport class RuntimeError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'runtime', details, cause);\n }\n\n static operationFailed(\n operation: string,\n context?: string,\n cause?: Error,\n ): RuntimeError {\n return new RuntimeError(\n `Operation failed: ${operation}${context ? ` in ${context}` : ''}`,\n 'RUNTIME_OPERATION_FAILED',\n { operation, context },\n cause,\n );\n }\n\n static invalidState(\n message: string,\n context?: Record<string, unknown>,\n ): RuntimeError {\n return new RuntimeError(message, 'RUNTIME_INVALID_STATE', context);\n }\n\n static resourceExhausted(resource: string, limit: number): RuntimeError {\n return new RuntimeError(\n `Resource exhausted: ${resource} exceeded limit of ${limit}`,\n 'RUNTIME_RESOURCE_EXHAUSTED',\n { resource, limit },\n );\n }\n}\n\n/**\n * Error thrown when a tenant isolation boundary is crossed while resolving a\n * relationship.\n *\n * Raised by {@link SmrtObject.loadRelated} / {@link SmrtObject.loadRelatedMany}\n * (and {@link SmrtObject.getRelated}, which delegates to them) when a\n * tenant-scoped object resolves a relationship to an object belonging to a\n * *different*, non-null tenant — the genuine cross-tenant data leak. The guard\n * is a no-op when either side has a `null` tenant (global / non-tenant-scoped\n * models) and when both sides share the same tenant, so it only fires on real\n * leaks. Pass `{ allowCrossTenant: true }` to the loader to deliberately opt out.\n *\n * The `code` is always `'TENANT_ISOLATION_VIOLATION'` and the category is\n * `'validation'`. It is never retried — `ErrorUtils.withRetry()` rethrows it\n * immediately and `ErrorUtils.isRetryable()` returns `false` — because a tenant\n * boundary violation is deterministic. `tenantId` is the owning object's tenant\n * and `attemptedTenantId` is the tenant of the object that was reached.\n *\n * This shares its stable `code`, `name`, `tenantId`, and `attemptedTenantId`\n * shape with the interceptor-level `TenantIsolationError` in\n * `@happyvertical/smrt-tenancy`, so cross-cutting handlers can match either via\n * `err.code === 'TENANT_ISOLATION_VIOLATION'`. They are intentionally distinct\n * classes because `@happyvertical/smrt-core` cannot depend on the tenancy\n * package (the dependency runs the other way).\n *\n * @example\n * ```typescript\n * try {\n * await order.loadRelated('customerId');\n * } catch (err) {\n * if (err instanceof TenantIsolationError) {\n * // err.tenantId — the order's tenant\n * // err.attemptedTenantId — the customer's tenant\n * }\n * }\n * ```\n *\n * @see SmrtObject.loadRelated\n * @see SmrtObject.loadRelatedMany\n */\nexport class TenantIsolationError extends SmrtError {\n /** The tenant ID of the object that owns the relationship. */\n public readonly tenantId?: string;\n /** The tenant ID of the related object that was reached (and rejected). */\n public readonly attemptedTenantId?: string;\n\n constructor(\n message: string,\n details?: {\n tenantId?: string;\n attemptedTenantId?: string;\n [key: string]: unknown;\n },\n cause?: Error,\n ) {\n super(message, 'TENANT_ISOLATION_VIOLATION', 'validation', details, cause);\n this.tenantId = details?.tenantId;\n this.attemptedTenantId = details?.attemptedTenantId;\n }\n\n /**\n * Builds a {@link TenantIsolationError} for a blocked cross-tenant\n * relationship resolution, with a descriptive message and structured details.\n */\n static crossTenantReference(details: {\n sourceClass: string;\n fieldName: string;\n sourceTenantId: string;\n targetClass?: string;\n targetTenantId: string;\n }): TenantIsolationError {\n const target = details.targetClass\n ? `${details.targetClass} (tenant '${details.targetTenantId}')`\n : `tenant '${details.targetTenantId}'`;\n return new TenantIsolationError(\n `Cross-tenant relationship access blocked on ${details.sourceClass}.${details.fieldName}: ` +\n `owning tenant '${details.sourceTenantId}' does not match ${target}. ` +\n `Pass { allowCrossTenant: true } to loadRelated()/loadRelatedMany()/getRelated() to override.`,\n {\n tenantId: details.sourceTenantId,\n attemptedTenantId: details.targetTenantId,\n sourceClass: details.sourceClass,\n fieldName: details.fieldName,\n targetClass: details.targetClass,\n },\n );\n }\n}\n\n/**\n * Utility functions for error handling\n */\nexport class ErrorUtils {\n /**\n * Wraps a function with error handling and automatic retry logic\n */\n static async withRetry<T>(\n operation: () => Promise<T>,\n maxRetries = 3,\n delay = 1000,\n backoffMultiplier = 2,\n ): Promise<T> {\n let lastError: Error = new Error('Operation failed without error details');\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n if (attempt === maxRetries) {\n throw lastError;\n }\n\n // Skip retry for certain error types. A tenant isolation violation is\n // deterministic — retrying re-fetches the same cross-tenant target — and\n // is a security boundary, so it must never be retried.\n if (\n error instanceof ValidationError ||\n error instanceof ConfigurationError ||\n error instanceof TenantIsolationError\n ) {\n throw error;\n }\n\n // Wait before retrying with exponential backoff\n // Wrap in try-catch to handle any potential timer errors\n try {\n await new Promise<void>((resolve) => {\n setTimeout(() => resolve(), delay * backoffMultiplier ** attempt);\n });\n } catch (timerError) {\n // Log timer error but don't fail the retry\n logger.error('Timer error during retry', { error: timerError });\n }\n }\n }\n\n throw lastError;\n }\n\n /**\n * Checks if an error is retryable\n */\n static isRetryable(error: Error): boolean {\n if (error instanceof SmrtError) {\n return error.category === 'network' || error.category === 'ai';\n }\n\n // Check for common retryable error patterns\n const retryablePatterns = [\n /ECONNRESET/,\n /ETIMEDOUT/,\n /ENOTFOUND/,\n /rate.?limit/i,\n /timeout/i,\n /503/,\n /502/,\n /500/,\n ];\n\n return retryablePatterns.some((pattern) => pattern.test(error.message));\n }\n\n /**\n * Sanitizes an error for safe logging (removes sensitive information)\n */\n static sanitizeError(error: Error): Record<string, unknown> {\n const sanitized: Record<string, unknown> = {\n name: error.name,\n message: error.message,\n stack: error.stack,\n };\n\n if (error instanceof SmrtError) {\n sanitized.code = error.code;\n sanitized.category = error.category;\n\n // Sanitize details to remove potential sensitive information\n if (error.details) {\n const details: Record<string, unknown> = { ...error.details };\n sanitized.details = details;\n\n // Remove common sensitive fields\n const sensitiveFields = [\n 'password',\n 'token',\n 'key',\n 'secret',\n 'apiKey',\n ];\n for (const field of sensitiveFields) {\n if (details[field]) {\n details[field] = '[REDACTED]';\n }\n }\n }\n }\n\n return sanitized;\n }\n}\n\n/**\n * Validation report that collects multiple validation errors\n *\n * Useful for validating an entire object and reporting all errors\n * at once rather than stopping at the first error.\n *\n * @example\n * ```typescript\n * const report = new ValidationReport('Product');\n * report.addError(ValidationError.requiredField('name', 'Product'));\n * report.addError(ValidationError.rangeError('price', -10, 0));\n *\n * if (report.hasErrors()) {\n * console.error(report.toString());\n * // Output:\n * // Validation failed for Product with 2 errors:\n * // - name: Required field 'name' is missing for Product\n * // - price: Value -10 for field 'price' is outside allowed range [0, undefined]\n * }\n * ```\n */\nexport class ValidationReport {\n private errors: ValidationError[] = [];\n private objectType: string;\n\n constructor(objectType: string) {\n this.objectType = objectType;\n }\n\n /**\n * Add a validation error to the report\n */\n addError(error: ValidationError): void {\n this.errors.push(error);\n }\n\n /**\n * Check if there are any validation errors\n */\n hasErrors(): boolean {\n return this.errors.length > 0;\n }\n\n /**\n * Get all validation errors\n */\n getErrors(): ValidationError[] {\n return [...this.errors];\n }\n\n /**\n * Get the number of validation errors\n */\n getErrorCount(): number {\n return this.errors.length;\n }\n\n /**\n * Convert to a human-readable string\n */\n toString(): string {\n if (this.errors.length === 0) {\n return `Validation passed for ${this.objectType}`;\n }\n\n const errorList = this.errors\n .map((err, idx) => ` ${idx + 1}. ${err.message}`)\n .join('\\n');\n\n return `Validation failed for ${this.objectType} with ${this.errors.length} error(s):\\n${errorList}`;\n }\n\n /**\n * Convert to JSON format\n */\n toJSON(): object {\n return {\n objectType: this.objectType,\n errorCount: this.errors.length,\n errors: this.errors.map((err) => err.toJSON()),\n };\n }\n\n /**\n * Throw the first error if there are any errors\n */\n throwIfErrors(): void {\n if (this.errors.length > 0) {\n throw this.errors[0];\n }\n }\n\n /**\n * Clear all errors\n */\n clear(): void {\n this.errors = [];\n }\n}\n\n/**\n * Validation utility functions\n */\nexport class ValidationUtils {\n /**\n * Validate a single field value\n *\n * @param fieldName - Name of the field\n * @param value - Value to validate\n * @param options - Validation options (required, min, max, etc.)\n * @returns ValidationError if validation fails, null otherwise\n */\n static async validateField(\n fieldName: string,\n value: unknown,\n options: {\n required?: boolean;\n min?: number;\n max?: number;\n minLength?: number;\n maxLength?: number;\n pattern?: string | RegExp;\n type?: string;\n customValidator?: (value: unknown) => boolean | Promise<boolean>;\n customMessage?: string;\n },\n objectType: string = 'Object',\n ): Promise<ValidationError | null> {\n // Required check\n if (\n options.required &&\n (value === null || value === undefined || value === '')\n ) {\n return ValidationError.requiredField(fieldName, objectType);\n }\n\n // Skip further validation if value is null/undefined and not required\n if (value === null || value === undefined) {\n return null;\n }\n\n // Numeric range validation\n if (typeof value === 'number') {\n if (options.min !== undefined && value < options.min) {\n return ValidationError.rangeError(\n fieldName,\n value,\n options.min,\n options.max,\n );\n }\n if (options.max !== undefined && value > options.max) {\n return ValidationError.rangeError(\n fieldName,\n value,\n options.min,\n options.max,\n );\n }\n }\n\n // String length validation\n if (typeof value === 'string') {\n if (options.minLength !== undefined && value.length < options.minLength) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string with minimum length ${options.minLength}`,\n );\n }\n if (options.maxLength !== undefined && value.length > options.maxLength) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string with maximum length ${options.maxLength}`,\n );\n }\n\n // Pattern validation\n if (options.pattern) {\n const regex =\n typeof options.pattern === 'string'\n ? new RegExp(options.pattern)\n : options.pattern;\n if (!regex.test(value)) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string matching pattern ${options.pattern}`,\n );\n }\n }\n }\n\n // Custom validator\n if (options.customValidator) {\n try {\n const isValid = await options.customValidator(value);\n if (!isValid) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n options.customMessage || 'custom validation failed',\n );\n }\n } catch (error) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `custom validation error: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n return null;\n }\n\n /**\n * Validate required field\n */\n static validateRequired(\n fieldName: string,\n value: unknown,\n objectType: string = 'Object',\n ): ValidationError | null {\n if (value === null || value === undefined || value === '') {\n return ValidationError.requiredField(fieldName, objectType);\n }\n return null;\n }\n\n /**\n * Validate numeric range\n */\n static validateRange(\n fieldName: string,\n value: number,\n min?: number,\n max?: number,\n ): ValidationError | null {\n if (min !== undefined && value < min) {\n return ValidationError.rangeError(fieldName, value, min, max);\n }\n if (max !== undefined && value > max) {\n return ValidationError.rangeError(fieldName, value, min, max);\n }\n return null;\n }\n\n /**\n * Validate string length\n */\n static validateLength(\n fieldName: string,\n value: string,\n minLength?: number,\n maxLength?: number,\n ): ValidationError | null {\n if (minLength !== undefined && value.length < minLength) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string with minimum length ${minLength}`,\n );\n }\n if (maxLength !== undefined && value.length > maxLength) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string with maximum length ${maxLength}`,\n );\n }\n return null;\n }\n\n /**\n * Validate string pattern\n */\n static validatePattern(\n fieldName: string,\n value: string,\n pattern: string | RegExp,\n ): ValidationError | null {\n const regex = typeof pattern === 'string' ? new RegExp(pattern) : pattern;\n if (!regex.test(value)) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string matching pattern ${pattern}`,\n );\n }\n return null;\n }\n}\n"],"names":[],"mappings":";AAmCA,MAAM,SAAS,aAAa,EAAE,OAAO,QAAQ;AAEtC,MAAe,kBAAkB,MAAM;AAAA,EAC5B;AAAA,EACA;AAAA,EAQA;AAAA,EACA;AAAA,EAEhB,YACE,SACA,MACA,UACA,SACA,OACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO,KAAK,YAAY;AAC7B,SAAK,OAAO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,KACA,KACwB;AACxB,QAAI,QAAQ,UAAa,QAAQ,KAAK;AACpC,aAAO,gBAAgB,WAAW,WAAW,OAAO,KAAK,GAAG;AAAA,IAC9D;AACA,QAAI,QAAQ,UAAa,QAAQ,KAAK;AACpC,aAAO,gBAAgB,WAAW,WAAW,OAAO,KAAK,GAAG;AAAA,IAC9D;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,eACL,WACA,OACA,WACA,WACwB;AACxB,QAAI,cAAc,UAAa,MAAM,SAAS,WAAW;AACvD,aAAO,gBAAgB;AAAA,QACrB;AAAA,QACA;AAAA,QACA,8BAA8B,SAAS;AAAA,MAAA;AAAA,IAE3C;AACA,QAAI,cAAc,UAAa,MAAM,SAAS,WAAW;AACvD,aAAO,gBAAgB;AAAA,QACrB;AAAA,QACA;AAAA,QACA,8BAA8B,SAAS;AAAA,MAAA;AAAA,IAE3C;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,gBACL,WACA,OACA,SACwB;AACxB,UAAM,QAAQ,OAAO,YAAY,WAAW,IAAI,OAAO,OAAO,IAAI;AAClE,QAAI,CAAC,MAAM,KAAK,KAAK,GAAG;AACtB,aAAO,gBAAgB;AAAA,QACrB;AAAA,QACA;AAAA,QACA,2BAA2B,OAAO;AAAA,MAAA;AAAA,IAEtC;AACA,WAAO;AAAA,EACT;AACF;"}
@@ -1,23 +1,5 @@
1
- /**
2
- * CLI command generator for smrt objects
3
- *
4
- * Exposes registered `@smrt()` objects as a runnable admin CLI: each object gets
5
- * `list`/`get`/`create`/`update`/`delete` commands plus its public custom
6
- * methods, dispatched as `objectname:action`.
7
- *
8
- * Security parity with the REST/MCP generators (#1540, #1547, #1554, #1556):
9
- * - **Mass-assignment guard** — create/update bodies are filtered through the
10
- * `@smrt({ api: { writable: [...] } })` allowlist, dropping server-managed and
11
- * `@field({ readonly })` fields ({@link CLIGenerator.applyWritablePolicy}).
12
- * - **Exhaustive include** — an `include` list is the COMPLETE allowlist for the
13
- * surface; custom methods are gated on `isPublic`.
14
- * - **Sensitive redaction** — command *output* is serialized through
15
- * {@link CLIGenerator.toPublicData} so `@field({ sensitive })` values never
16
- * print (input bodies are guarded by the writable allowlist above).
17
- * - **Fail-closed tenant context** — tenant-scoped reads/writes run inside the
18
- * tenancy gate; without `--tenant <id>` / `--all-tenants` (and with tenancy
19
- * enabled) the command throws rather than ranging across all tenants.
20
- */
1
+ import { AIClient, AIClientOptions } from '@happyvertical/ai';
2
+ import { DatabaseConfig } from '../database.js';
21
3
  /**
22
4
  * Configuration for a generated CLI.
23
5
  */
@@ -34,9 +16,9 @@ export interface CLIConfig {
34
16
  */
35
17
  export interface CLIContext {
36
18
  /** Database handle passed to collections. */
37
- db?: any;
19
+ db?: DatabaseConfig;
38
20
  /** AI provider passed to collections. */
39
- ai?: any;
21
+ ai?: AIClientOptions | AIClient;
40
22
  /** Authenticated operator, when the host establishes one. */
41
23
  user?: {
42
24
  id: string;
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../src/generators/cli.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAMH;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,8CAA8C;IAC9C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,mBAAmB;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,uBAAuB;IACvB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,6CAA6C;IAC7C,EAAE,CAAC,EAAE,GAAG,CAAC;IACT,yCAAyC;IACzC,EAAE,CAAC,EAAE,GAAG,CAAC;IACT,6DAA6D;IAC7D,IAAI,CAAC,EAAE;QACL,EAAE,EAAE,MAAM,CAAC;QACX,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;KAClB,CAAC;IACF;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CA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AO,CAAC,IAAI,CAAC;IAMpD;;;;OAIG;IACG,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IA4CxC;;;;OAIG;IACH,OAAO,CAAC,SAAS;IAkDjB;;;OAGG;IACH,OAAO,CAAC,YAAY;IAWpB;;;;OAIG;YACW,oBAAoB;IA+ClC;;;;;;OAMG;YACW,aAAa;IAS3B;;OAEG;YACW,aAAa;IAkF3B;;;OAGG;YACW,mBAAmB;IAgCjC;;;;OAIG;YACW,WAAW;IAsBzB,2DAA2D;IAC3D,OAAO,CAAC,aAAa;IAWrB;;;;;OAKG;IACH,OAAO,CAAC,mBAAmB;IA+C3B;;;;OAIG;IACH,OAAO,CAAC,YAAY;IA0BpB,qEAAqE;IAC/D,YAAY,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;YAmCzB,QAAQ;IAoBtB,OAAO,CAAC,QAAQ;IAShB,OAAO,CAAC,UAAU;IAIlB,2EAA2E;IAC3E,OAAO,CAAC,WAAW;CAiBpB;AAED;;;;;;;GAOG;AACH,wBAAgB,QAAQ,CAAC,MAAM,GAAE,SAAc,EAAE,OAAO,GAAE,UAAe;gBAGnD,MAAM,EAAE;;EAM7B;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAC3B,MAAM,GAAE,SAAc,EACtB,OAAO,GAAE,UAAe,UA1iBE,MAAM,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CA8iBrD"}
@@ -264,13 +264,15 @@ class CLIGenerator {
264
264
  if (id) {
265
265
  const object = await collection.get(id);
266
266
  if (!object) throw new Error("Object not found");
267
- if (typeof object[action] !== "function") {
267
+ const candidate = object[action];
268
+ if (typeof candidate !== "function") {
268
269
  throw new Error(`Method '${action}' not found on object instance`);
269
270
  }
270
- return object[action](options);
271
+ return candidate.call(object, options);
271
272
  }
272
- if (typeof collection[action] === "function") {
273
- return collection[action](options);
273
+ const collectionCandidate = collection[action];
274
+ if (typeof collectionCandidate === "function") {
275
+ return collectionCandidate.call(collection, options);
274
276
  }
275
277
  throw new Error(
276
278
  `Method '${action}' not found on collection. Provide an id for object-specific actions.`
@@ -355,7 +357,9 @@ class CLIGenerator {
355
357
  */
356
358
  toPublicData(value, seen = /* @__PURE__ */ new WeakSet()) {
357
359
  if (value === null || typeof value !== "object") return value;
358
- if (typeof value.toPublicJSON === "function") return value.toPublicJSON();
360
+ if (typeof value.toPublicJSON === "function") {
361
+ return value.toPublicJSON();
362
+ }
359
363
  if (Array.isArray(value)) {
360
364
  if (seen.has(value)) return value;
361
365
  seen.add(value);