noormme 1.0.0 → 1.0.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 (137) hide show
  1. package/LICENSE +89 -21
  2. package/README.md +195 -578
  3. package/dist/cjs/cli/commands/analyze.js +4 -1
  4. package/dist/cjs/cli/commands/generate.js +48 -8
  5. package/dist/cjs/cli/commands/init.js +54 -14
  6. package/dist/cjs/cli/commands/inspect.js +10 -3
  7. package/dist/cjs/cli/commands/migrate.js +38 -2
  8. package/dist/cjs/cli/commands/optimize.js +4 -1
  9. package/dist/cjs/cli/commands/status.js +41 -5
  10. package/dist/cjs/cli/commands/watch.js +4 -1
  11. package/dist/cjs/cli/index.js +4 -1
  12. package/dist/cjs/dialect/database-introspector.js +16 -21
  13. package/dist/cjs/dialect/sqlite/sqlite-introspector.js +13 -24
  14. package/dist/cjs/dynamic/dynamic.d.ts +20 -0
  15. package/dist/cjs/dynamic/dynamic.js +25 -0
  16. package/dist/cjs/edge-runtime/edge-config.d.ts +125 -0
  17. package/dist/cjs/edge-runtime/edge-config.js +323 -0
  18. package/dist/cjs/errors/NoormError.d.ts +27 -4
  19. package/dist/cjs/errors/NoormError.js +142 -21
  20. package/dist/cjs/logging/logger.d.ts +7 -2
  21. package/dist/cjs/logging/logger.js +21 -7
  22. package/dist/cjs/noormme.d.ts +12 -8
  23. package/dist/cjs/noormme.js +133 -61
  24. package/dist/cjs/operation-node/column-node.js +4 -0
  25. package/dist/cjs/operation-node/identifier-node.js +4 -0
  26. package/dist/cjs/operation-node/table-node.js +7 -0
  27. package/dist/cjs/parser/reference-parser.js +5 -0
  28. package/dist/cjs/parser/table-parser.js +2 -0
  29. package/dist/cjs/performance/index.d.ts +44 -0
  30. package/dist/cjs/performance/index.js +64 -0
  31. package/dist/cjs/performance/query-optimizer.d.ts +134 -0
  32. package/dist/cjs/performance/query-optimizer.js +391 -0
  33. package/dist/cjs/performance/services/cache-service.d.ts +177 -0
  34. package/dist/cjs/performance/services/cache-service.js +415 -0
  35. package/dist/cjs/performance/services/connection-factory.d.ts +198 -0
  36. package/dist/cjs/performance/services/connection-factory.js +498 -0
  37. package/dist/cjs/performance/services/metrics-collector.d.ts +162 -0
  38. package/dist/cjs/performance/services/metrics-collector.js +406 -0
  39. package/dist/cjs/performance/utils/query-parser.d.ts +123 -0
  40. package/dist/cjs/performance/utils/query-parser.js +295 -0
  41. package/dist/cjs/raw-builder/sql.d.ts +73 -26
  42. package/dist/cjs/raw-builder/sql.js +9 -0
  43. package/dist/cjs/repository/repository-factory.d.ts +10 -42
  44. package/dist/cjs/repository/repository-factory.js +276 -394
  45. package/dist/cjs/schema/core/coordinators/schema-discovery.coordinator.js +6 -4
  46. package/dist/cjs/schema/core/factories/discovery-factory.js +5 -5
  47. package/dist/cjs/schema/core/utils/name-generator.js +34 -2
  48. package/dist/cjs/schema/core/utils/type-mapper.d.ts +19 -14
  49. package/dist/cjs/schema/core/utils/type-mapper.js +4 -7
  50. package/dist/cjs/schema/dialects/sqlite/discovery/sqlite-constraint-discovery.js +3 -2
  51. package/dist/cjs/schema/dialects/sqlite/sqlite-discovery.coordinator.d.ts +2 -0
  52. package/dist/cjs/schema/dialects/sqlite/sqlite-discovery.coordinator.js +19 -5
  53. package/dist/cjs/schema/test/dialect-capabilities.test.js +6 -0
  54. package/dist/cjs/schema/test/error-handling.test.js +52 -33
  55. package/dist/cjs/schema/test/integration.test.js +51 -5
  56. package/dist/cjs/schema/test/sqlite-discovery-coordinator.test.js +8 -4
  57. package/dist/cjs/sqlite-migration/index.js +35 -2
  58. package/dist/cjs/testing/test-utils.d.ts +5 -0
  59. package/dist/cjs/testing/test-utils.js +66 -6
  60. package/dist/cjs/types/index.d.ts +78 -13
  61. package/dist/cjs/types/index.js +23 -0
  62. package/dist/cjs/types/type-generator.d.ts +8 -0
  63. package/dist/cjs/types/type-generator.js +86 -17
  64. package/dist/cjs/util/safe-sql-helpers.d.ts +124 -0
  65. package/dist/cjs/util/safe-sql-helpers.js +221 -0
  66. package/dist/cjs/util/security-validator.d.ts +44 -0
  67. package/dist/cjs/util/security-validator.js +256 -0
  68. package/dist/cjs/util/security.d.ts +60 -0
  69. package/dist/cjs/util/security.js +137 -0
  70. package/dist/cjs/watch/schema-watcher.js +26 -7
  71. package/dist/esm/cli/commands/generate.js +10 -6
  72. package/dist/esm/cli/commands/init.js +15 -11
  73. package/dist/esm/cli/commands/inspect.js +6 -2
  74. package/dist/esm/cli/commands/status.js +3 -3
  75. package/dist/esm/dialect/database-introspector.js +16 -21
  76. package/dist/esm/dialect/sqlite/sqlite-introspector.js +13 -24
  77. package/dist/esm/dynamic/dynamic.d.ts +20 -0
  78. package/dist/esm/dynamic/dynamic.js +25 -0
  79. package/dist/esm/edge-runtime/edge-config.d.ts +125 -0
  80. package/dist/esm/edge-runtime/edge-config.js +281 -0
  81. package/dist/esm/errors/NoormError.d.ts +27 -4
  82. package/dist/esm/errors/NoormError.js +134 -18
  83. package/dist/esm/logging/logger.d.ts +7 -2
  84. package/dist/esm/logging/logger.js +21 -7
  85. package/dist/esm/noormme.d.ts +12 -8
  86. package/dist/esm/noormme.js +130 -61
  87. package/dist/esm/operation-node/column-node.js +4 -0
  88. package/dist/esm/operation-node/identifier-node.js +4 -0
  89. package/dist/esm/operation-node/table-node.js +7 -0
  90. package/dist/esm/parser/reference-parser.js +5 -0
  91. package/dist/esm/parser/table-parser.js +2 -0
  92. package/dist/esm/performance/index.d.ts +44 -0
  93. package/dist/esm/performance/index.js +48 -0
  94. package/dist/esm/performance/query-optimizer.d.ts +134 -0
  95. package/dist/esm/performance/query-optimizer.js +387 -0
  96. package/dist/esm/performance/services/cache-service.d.ts +177 -0
  97. package/dist/esm/performance/services/cache-service.js +410 -0
  98. package/dist/esm/performance/services/connection-factory.d.ts +198 -0
  99. package/dist/esm/performance/services/connection-factory.js +493 -0
  100. package/dist/esm/performance/services/metrics-collector.d.ts +162 -0
  101. package/dist/esm/performance/services/metrics-collector.js +402 -0
  102. package/dist/esm/performance/utils/query-parser.d.ts +123 -0
  103. package/dist/esm/performance/utils/query-parser.js +292 -0
  104. package/dist/esm/raw-builder/sql.d.ts +73 -26
  105. package/dist/esm/raw-builder/sql.js +9 -0
  106. package/dist/esm/repository/repository-factory.d.ts +10 -42
  107. package/dist/esm/repository/repository-factory.js +277 -395
  108. package/dist/esm/schema/core/coordinators/schema-discovery.coordinator.js +6 -4
  109. package/dist/esm/schema/core/factories/discovery-factory.js +5 -5
  110. package/dist/esm/schema/core/utils/name-generator.js +34 -2
  111. package/dist/esm/schema/core/utils/type-mapper.d.ts +19 -14
  112. package/dist/esm/schema/core/utils/type-mapper.js +4 -7
  113. package/dist/esm/schema/dialects/sqlite/discovery/sqlite-constraint-discovery.js +3 -2
  114. package/dist/esm/schema/dialects/sqlite/sqlite-discovery.coordinator.d.ts +2 -0
  115. package/dist/esm/schema/dialects/sqlite/sqlite-discovery.coordinator.js +19 -5
  116. package/dist/esm/schema/test/dialect-capabilities.test.js +6 -0
  117. package/dist/esm/schema/test/error-handling.test.js +52 -33
  118. package/dist/esm/schema/test/integration.test.js +18 -5
  119. package/dist/esm/schema/test/sqlite-discovery-coordinator.test.js +8 -4
  120. package/dist/esm/testing/test-utils.d.ts +5 -0
  121. package/dist/esm/testing/test-utils.js +66 -6
  122. package/dist/esm/types/index.d.ts +78 -13
  123. package/dist/esm/types/index.js +22 -1
  124. package/dist/esm/types/type-generator.d.ts +8 -0
  125. package/dist/esm/types/type-generator.js +86 -17
  126. package/dist/esm/util/safe-sql-helpers.d.ts +124 -0
  127. package/dist/esm/util/safe-sql-helpers.js +209 -0
  128. package/dist/esm/util/security-validator.d.ts +44 -0
  129. package/dist/esm/util/security-validator.js +246 -0
  130. package/dist/esm/util/security.d.ts +60 -0
  131. package/dist/esm/util/security.js +114 -0
  132. package/dist/esm/watch/schema-watcher.js +26 -7
  133. package/package.json +1 -1
  134. package/dist/cjs/performance/query-analyzer.d.ts +0 -89
  135. package/dist/cjs/performance/query-analyzer.js +0 -263
  136. package/dist/esm/performance/query-analyzer.d.ts +0 -89
  137. package/dist/esm/performance/query-analyzer.js +0 -260
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DynamicModule = void 0;
4
4
  const dynamic_reference_builder_js_1 = require("./dynamic-reference-builder.js");
5
5
  const dynamic_table_builder_js_1 = require("./dynamic-table-builder.js");
6
+ const security_validator_js_1 = require("../util/security-validator.js");
6
7
  class DynamicModule {
7
8
  /**
8
9
  * Creates a dynamic reference to a column that is not know at compile time.
@@ -20,6 +21,10 @@ class DynamicModule {
20
21
  * create an SQL injection vulnerability. Always __always__ validate the user
21
22
  * input before passing it to this method.
22
23
  *
24
+ * SECURITY: This method now includes built-in validation to prevent SQL injection
25
+ * through malicious column references. However, you should still validate that
26
+ * the column reference is from a trusted source or whitelist of allowed columns.
27
+ *
23
28
  * There are couple of examples below for some use cases, but you can pass
24
29
  * `ref` to other methods as well. If the types allow you to pass a `ref`
25
30
  * value to some place, it should work.
@@ -32,6 +37,12 @@ class DynamicModule {
32
37
  * async function someQuery(filterColumn: string, filterValue: string) {
33
38
  * const { ref } = db.dynamic
34
39
  *
40
+ * // Validate input against a whitelist of allowed columns
41
+ * const allowedColumns = ['first_name', 'last_name', 'email']
42
+ * if (!allowedColumns.includes(filterColumn)) {
43
+ * throw new Error('Invalid column')
44
+ * }
45
+ *
35
46
  * return await db
36
47
  * .selectFrom('person')
37
48
  * .selectAll()
@@ -49,6 +60,12 @@ class DynamicModule {
49
60
  * async function someQuery(orderBy: string) {
50
61
  * const { ref } = db.dynamic
51
62
  *
63
+ * // Validate against allowed columns
64
+ * const allowedColumns = ['first_name', 'last_name', 'created_at']
65
+ * if (!allowedColumns.includes(orderBy)) {
66
+ * throw new Error('Invalid order column')
67
+ * }
68
+ *
52
69
  * return await db
53
70
  * .selectFrom('person')
54
71
  * .select('person.first_name as fn')
@@ -90,6 +107,8 @@ class DynamicModule {
90
107
  * ```
91
108
  */
92
109
  ref(reference) {
110
+ // Security validation to prevent SQL injection
111
+ (0, security_validator_js_1.validateColumnReference)(reference);
93
112
  return new dynamic_reference_builder_js_1.DynamicReferenceBuilder(reference);
94
113
  }
95
114
  /**
@@ -97,6 +116,10 @@ class DynamicModule {
97
116
  *
98
117
  * The type `T` is allowed to be a union of multiple tables.
99
118
  *
119
+ * SECURITY: This method now includes built-in validation to prevent SQL injection
120
+ * through malicious table references. However, you should still validate that
121
+ * the table reference is from a trusted source or whitelist of allowed tables.
122
+ *
100
123
  * <!-- siteExample("select", "Generic find query", 130) -->
101
124
  *
102
125
  * A generic type-safe helper function for finding a row by a column value:
@@ -126,6 +149,8 @@ class DynamicModule {
126
149
  * ```
127
150
  */
128
151
  table(table) {
152
+ // Security validation to prevent SQL injection
153
+ (0, security_validator_js_1.validateTableReference)(table);
129
154
  return new dynamic_table_builder_js_1.DynamicTableBuilder(table);
130
155
  }
131
156
  }
@@ -0,0 +1,125 @@
1
+ import { NOORMConfig } from '../types';
2
+ /**
3
+ * Edge Runtime compatible configuration for NOORMME
4
+ *
5
+ * Edge Runtime has specific limitations:
6
+ * - No file system access (use in-memory database)
7
+ * - No WAL mode support
8
+ * - Limited memory and CPU resources
9
+ * - No persistent storage
10
+ * - Minimal logging capabilities
11
+ */
12
+ export declare function getEdgeRuntimeConfig(): NOORMConfig;
13
+ /**
14
+ * Check if current environment is Edge Runtime
15
+ */
16
+ export declare function isEdgeRuntime(): boolean;
17
+ /**
18
+ * Get appropriate configuration based on runtime environment
19
+ */
20
+ export declare function getRuntimeConfig(): NOORMConfig;
21
+ /**
22
+ * Edge Runtime compatible database operations
23
+ */
24
+ export declare class EdgeRuntimeDB {
25
+ private config;
26
+ constructor(config?: NOORMConfig);
27
+ /**
28
+ * Create a new database instance optimized for Edge Runtime
29
+ */
30
+ createInstance(): Promise<import("../noormme").NOORMME>;
31
+ /**
32
+ * Execute a simple query in Edge Runtime
33
+ */
34
+ executeQuery(query: string, params?: any[]): Promise<unknown>;
35
+ /**
36
+ * Perform a read operation in Edge Runtime
37
+ */
38
+ read(table: string, conditions?: Record<string, any>): Promise<unknown[]>;
39
+ /**
40
+ * Perform a write operation in Edge Runtime
41
+ */
42
+ write(table: string, data: Record<string, any>): Promise<unknown>;
43
+ }
44
+ /**
45
+ * Edge Runtime compatible middleware
46
+ */
47
+ export declare function createEdgeMiddleware(): {
48
+ /**
49
+ * Handle database operations in Edge Runtime
50
+ */
51
+ handleRequest(request: Request): Promise<Response>;
52
+ /**
53
+ * Handle API requests in Edge Runtime
54
+ */
55
+ handleAPIRequest(request: Request, edgeDB: EdgeRuntimeDB): Promise<Response>;
56
+ };
57
+ /**
58
+ * Edge Runtime compatible error handler
59
+ */
60
+ export declare function createEdgeErrorHandler(): {
61
+ /**
62
+ * Handle errors in Edge Runtime
63
+ */
64
+ handleError(error: Error, context?: string): Response;
65
+ };
66
+ /**
67
+ * Edge Runtime performance monitoring
68
+ */
69
+ export declare class EdgeRuntimeMonitor {
70
+ private metrics;
71
+ /**
72
+ * Record a performance metric
73
+ */
74
+ recordMetric(name: string, value: number): void;
75
+ /**
76
+ * Get performance metrics
77
+ */
78
+ getMetrics(): {
79
+ [k: string]: number;
80
+ };
81
+ /**
82
+ * Monitor a function execution
83
+ */
84
+ monitor<T>(name: string, fn: () => Promise<T>): Promise<T>;
85
+ /**
86
+ * Get performance report
87
+ */
88
+ getReport(): {
89
+ totalOperations: number;
90
+ metrics: {
91
+ [k: string]: number;
92
+ };
93
+ timestamp: string;
94
+ runtime: string;
95
+ };
96
+ }
97
+ /**
98
+ * Edge Runtime utilities
99
+ */
100
+ export declare const EdgeRuntimeUtils: {
101
+ /**
102
+ * Check if running in Edge Runtime
103
+ */
104
+ isEdgeRuntime: typeof isEdgeRuntime;
105
+ /**
106
+ * Get Edge Runtime configuration
107
+ */
108
+ getConfig: typeof getEdgeRuntimeConfig;
109
+ /**
110
+ * Create Edge Runtime database instance
111
+ */
112
+ createDB: () => EdgeRuntimeDB;
113
+ /**
114
+ * Create Edge Runtime middleware
115
+ */
116
+ createMiddleware: typeof createEdgeMiddleware;
117
+ /**
118
+ * Create Edge Runtime error handler
119
+ */
120
+ createErrorHandler: typeof createEdgeErrorHandler;
121
+ /**
122
+ * Create Edge Runtime monitor
123
+ */
124
+ createMonitor: () => EdgeRuntimeMonitor;
125
+ };
@@ -0,0 +1,323 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.EdgeRuntimeUtils = exports.EdgeRuntimeMonitor = exports.EdgeRuntimeDB = void 0;
37
+ exports.getEdgeRuntimeConfig = getEdgeRuntimeConfig;
38
+ exports.isEdgeRuntime = isEdgeRuntime;
39
+ exports.getRuntimeConfig = getRuntimeConfig;
40
+ exports.createEdgeMiddleware = createEdgeMiddleware;
41
+ exports.createEdgeErrorHandler = createEdgeErrorHandler;
42
+ /**
43
+ * Edge Runtime compatible configuration for NOORMME
44
+ *
45
+ * Edge Runtime has specific limitations:
46
+ * - No file system access (use in-memory database)
47
+ * - No WAL mode support
48
+ * - Limited memory and CPU resources
49
+ * - No persistent storage
50
+ * - Minimal logging capabilities
51
+ */
52
+ function getEdgeRuntimeConfig() {
53
+ return {
54
+ dialect: 'sqlite',
55
+ connection: {
56
+ database: ':memory:'
57
+ },
58
+ optimization: {
59
+ enableWALMode: false, // WAL mode not supported in Edge Runtime
60
+ enableForeignKeys: true,
61
+ cacheSize: -2000, // 2MB cache (smaller for Edge Runtime)
62
+ synchronous: 'NORMAL',
63
+ tempStore: 'MEMORY' // Use memory for temporary storage
64
+ },
65
+ logging: {
66
+ level: 'error', // Minimal logging for performance
67
+ enabled: false // Disable logging in Edge Runtime
68
+ }
69
+ };
70
+ }
71
+ /**
72
+ * Check if current environment is Edge Runtime
73
+ */
74
+ function isEdgeRuntime() {
75
+ return ((typeof globalThis !== 'undefined' && 'EdgeRuntime' in globalThis) ||
76
+ (typeof process !== 'undefined' && process.env.NEXT_RUNTIME === 'edge'));
77
+ }
78
+ /**
79
+ * Get appropriate configuration based on runtime environment
80
+ */
81
+ function getRuntimeConfig() {
82
+ if (isEdgeRuntime()) {
83
+ return getEdgeRuntimeConfig();
84
+ }
85
+ // Default configuration for Node.js runtime
86
+ return {
87
+ dialect: 'sqlite',
88
+ connection: {
89
+ database: process.env.DATABASE_URL || './app.db'
90
+ },
91
+ optimization: {
92
+ enableWALMode: true,
93
+ enableForeignKeys: true,
94
+ cacheSize: -64000, // 64MB cache
95
+ synchronous: 'NORMAL',
96
+ tempStore: 'DEFAULT'
97
+ },
98
+ logging: {
99
+ level: process.env.NODE_ENV === 'development' ? 'info' : 'error',
100
+ enabled: true
101
+ }
102
+ };
103
+ }
104
+ /**
105
+ * Edge Runtime compatible database operations
106
+ */
107
+ class EdgeRuntimeDB {
108
+ config;
109
+ constructor(config) {
110
+ this.config = config || getEdgeRuntimeConfig();
111
+ }
112
+ /**
113
+ * Create a new database instance optimized for Edge Runtime
114
+ */
115
+ async createInstance() {
116
+ const { NOORMME } = await Promise.resolve().then(() => __importStar(require('../noormme')));
117
+ return new NOORMME(this.config);
118
+ }
119
+ /**
120
+ * Execute a simple query in Edge Runtime
121
+ */
122
+ async executeQuery(query, params) {
123
+ const db = await this.createInstance();
124
+ await db.initialize();
125
+ try {
126
+ const result = await db.execute(query, params);
127
+ return result;
128
+ }
129
+ finally {
130
+ await db.close();
131
+ }
132
+ }
133
+ /**
134
+ * Perform a read operation in Edge Runtime
135
+ */
136
+ async read(table, conditions = {}) {
137
+ const db = await this.createInstance();
138
+ await db.initialize();
139
+ try {
140
+ const repo = db.getRepository(table);
141
+ return await repo.findAll();
142
+ }
143
+ finally {
144
+ await db.close();
145
+ }
146
+ }
147
+ /**
148
+ * Perform a write operation in Edge Runtime
149
+ */
150
+ async write(table, data) {
151
+ const db = await this.createInstance();
152
+ await db.initialize();
153
+ try {
154
+ const repo = db.getRepository(table);
155
+ return await repo.create(data);
156
+ }
157
+ finally {
158
+ await db.close();
159
+ }
160
+ }
161
+ }
162
+ exports.EdgeRuntimeDB = EdgeRuntimeDB;
163
+ /**
164
+ * Edge Runtime compatible middleware
165
+ */
166
+ function createEdgeMiddleware() {
167
+ return {
168
+ /**
169
+ * Handle database operations in Edge Runtime
170
+ */
171
+ async handleRequest(request) {
172
+ const edgeDB = new EdgeRuntimeDB();
173
+ try {
174
+ const url = new URL(request.url);
175
+ const pathname = url.pathname;
176
+ if (pathname.startsWith('/api/')) {
177
+ return await this.handleAPIRequest(request, edgeDB);
178
+ }
179
+ return new Response('Not found', { status: 404 });
180
+ }
181
+ catch (error) {
182
+ console.error('Edge Runtime error:', error);
183
+ return new Response('Internal Server Error', { status: 500 });
184
+ }
185
+ },
186
+ /**
187
+ * Handle API requests in Edge Runtime
188
+ */
189
+ async handleAPIRequest(request, edgeDB) {
190
+ const url = new URL(request.url);
191
+ const method = request.method;
192
+ const pathname = url.pathname;
193
+ // Simple routing for Edge Runtime
194
+ if (pathname === '/api/health') {
195
+ return new Response(JSON.stringify({
196
+ status: 'healthy',
197
+ runtime: 'edge',
198
+ timestamp: new Date().toISOString()
199
+ }), {
200
+ headers: { 'Content-Type': 'application/json' }
201
+ });
202
+ }
203
+ if (pathname === '/api/users' && method === 'GET') {
204
+ const users = await edgeDB.read('users');
205
+ return new Response(JSON.stringify(users), {
206
+ headers: { 'Content-Type': 'application/json' }
207
+ });
208
+ }
209
+ if (pathname === '/api/users' && method === 'POST') {
210
+ const data = await request.json();
211
+ const user = await edgeDB.write('users', data);
212
+ return new Response(JSON.stringify(user), {
213
+ status: 201,
214
+ headers: { 'Content-Type': 'application/json' }
215
+ });
216
+ }
217
+ return new Response('Not found', { status: 404 });
218
+ }
219
+ };
220
+ }
221
+ /**
222
+ * Edge Runtime compatible error handler
223
+ */
224
+ function createEdgeErrorHandler() {
225
+ return {
226
+ /**
227
+ * Handle errors in Edge Runtime
228
+ */
229
+ handleError(error, context) {
230
+ // Log error (minimal logging in Edge Runtime)
231
+ console.error(`Edge Runtime Error${context ? ` in ${context}` : ''}:`, error.message);
232
+ // Return appropriate response
233
+ return new Response(JSON.stringify({
234
+ error: 'Internal Server Error',
235
+ message: process.env.NODE_ENV === 'development' ? error.message : 'Something went wrong',
236
+ timestamp: new Date().toISOString()
237
+ }), {
238
+ status: 500,
239
+ headers: { 'Content-Type': 'application/json' }
240
+ });
241
+ }
242
+ };
243
+ }
244
+ /**
245
+ * Edge Runtime performance monitoring
246
+ */
247
+ class EdgeRuntimeMonitor {
248
+ metrics = new Map();
249
+ /**
250
+ * Record a performance metric
251
+ */
252
+ recordMetric(name, value) {
253
+ this.metrics.set(name, value);
254
+ }
255
+ /**
256
+ * Get performance metrics
257
+ */
258
+ getMetrics() {
259
+ return Object.fromEntries(this.metrics);
260
+ }
261
+ /**
262
+ * Monitor a function execution
263
+ */
264
+ async monitor(name, fn) {
265
+ const start = performance.now();
266
+ try {
267
+ const result = await fn();
268
+ const duration = performance.now() - start;
269
+ this.recordMetric(`${name}_duration`, duration);
270
+ this.recordMetric(`${name}_success`, 1);
271
+ return result;
272
+ }
273
+ catch (error) {
274
+ const duration = performance.now() - start;
275
+ this.recordMetric(`${name}_duration`, duration);
276
+ this.recordMetric(`${name}_error`, 1);
277
+ throw error;
278
+ }
279
+ }
280
+ /**
281
+ * Get performance report
282
+ */
283
+ getReport() {
284
+ const metrics = this.getMetrics();
285
+ const totalOperations = Object.keys(metrics).length;
286
+ return {
287
+ totalOperations,
288
+ metrics,
289
+ timestamp: new Date().toISOString(),
290
+ runtime: 'edge'
291
+ };
292
+ }
293
+ }
294
+ exports.EdgeRuntimeMonitor = EdgeRuntimeMonitor;
295
+ /**
296
+ * Edge Runtime utilities
297
+ */
298
+ exports.EdgeRuntimeUtils = {
299
+ /**
300
+ * Check if running in Edge Runtime
301
+ */
302
+ isEdgeRuntime,
303
+ /**
304
+ * Get Edge Runtime configuration
305
+ */
306
+ getConfig: getEdgeRuntimeConfig,
307
+ /**
308
+ * Create Edge Runtime database instance
309
+ */
310
+ createDB: () => new EdgeRuntimeDB(),
311
+ /**
312
+ * Create Edge Runtime middleware
313
+ */
314
+ createMiddleware: createEdgeMiddleware,
315
+ /**
316
+ * Create Edge Runtime error handler
317
+ */
318
+ createErrorHandler: createEdgeErrorHandler,
319
+ /**
320
+ * Create Edge Runtime monitor
321
+ */
322
+ createMonitor: () => new EdgeRuntimeMonitor()
323
+ };
@@ -44,13 +44,36 @@ export declare class TableNotFoundError extends NoormError {
44
44
  }
45
45
  export declare class ColumnNotFoundError extends NoormError {
46
46
  constructor(columnName: string, tableName: string, availableColumns?: string[]);
47
+ private static calculateSimilarity;
48
+ private static levenshteinDistance;
49
+ }
50
+ export declare class ConnectionError extends NoormError {
51
+ constructor(message: string, originalError?: Error);
52
+ }
53
+ export declare class DatabaseInitializationError extends NoormError {
54
+ constructor(originalError: Error, databasePath: string);
55
+ }
56
+ export declare class ValidationError extends NoormError {
57
+ constructor(message: string, validationIssues?: string[]);
47
58
  }
48
59
  export declare class RelationshipNotFoundError extends NoormError {
49
60
  constructor(relationshipName: string, tableName: string, availableRelationships?: string[]);
50
61
  }
51
- export declare class ValidationError extends NoormError {
52
- constructor(message: string, field?: string, tableName?: string);
62
+ export declare class QueryExecutionError extends NoormError {
63
+ constructor(query: string, originalError: Error, context?: {
64
+ table?: string;
65
+ operation?: string;
66
+ });
67
+ private static getQuerySuggestion;
53
68
  }
54
- export declare class ConnectionError extends NoormError {
55
- constructor(message: string, originalError?: Error);
69
+ export declare class SchemaDiscoveryError extends NoormError {
70
+ constructor(tableName: string, originalError: Error);
71
+ }
72
+ export declare class MigrationError extends NoormError {
73
+ constructor(migrationName: string, originalError: Error, context?: {
74
+ step?: string;
75
+ });
76
+ }
77
+ export declare class TypeGenerationError extends NoormError {
78
+ constructor(tableName: string, originalError: Error);
56
79
  }