@framers/sql-storage-adapter 0.7.1 → 0.7.3

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 (192) hide show
  1. package/README.md +43 -0
  2. package/dist/adapters/electron/preload.cjs +289 -0
  3. package/dist/adapters/electron/renderer.d.ts +9 -0
  4. package/dist/adapters/electron/renderer.d.ts.map +1 -0
  5. package/dist/adapters/electron/renderer.js +8 -0
  6. package/dist/adapters/electron/renderer.js.map +1 -0
  7. package/dist/cjs/adapters/__tests__/indexedDbAdapter.spec.d.ts +2 -0
  8. package/dist/cjs/adapters/__tests__/indexedDbAdapter.spec.js +133 -0
  9. package/dist/cjs/adapters/baseStorageAdapter.d.ts +368 -0
  10. package/dist/cjs/adapters/baseStorageAdapter.js +744 -0
  11. package/dist/cjs/adapters/betterSqliteAdapter.d.ts +124 -0
  12. package/dist/cjs/adapters/betterSqliteAdapter.js +334 -0
  13. package/dist/cjs/adapters/capacitorSqliteAdapter.d.ts +83 -0
  14. package/dist/cjs/adapters/capacitorSqliteAdapter.js +250 -0
  15. package/dist/cjs/adapters/electron/electronMainAdapter.d.ts +251 -0
  16. package/dist/cjs/adapters/electron/electronMainAdapter.js +392 -0
  17. package/dist/cjs/adapters/electron/electronRendererAdapter.d.ts +177 -0
  18. package/dist/cjs/adapters/electron/electronRendererAdapter.js +283 -0
  19. package/dist/cjs/adapters/electron/index.d.ts +74 -0
  20. package/dist/cjs/adapters/electron/index.js +86 -0
  21. package/dist/cjs/adapters/electron/ipc/channels.d.ts +196 -0
  22. package/dist/cjs/adapters/electron/ipc/channels.js +127 -0
  23. package/dist/cjs/adapters/electron/ipc/index.d.ts +11 -0
  24. package/dist/cjs/adapters/electron/ipc/index.js +38 -0
  25. package/dist/cjs/adapters/electron/ipc/protocol.d.ts +78 -0
  26. package/dist/cjs/adapters/electron/ipc/protocol.js +341 -0
  27. package/dist/cjs/adapters/electron/ipc/types.d.ts +248 -0
  28. package/dist/cjs/adapters/electron/ipc/types.js +15 -0
  29. package/dist/cjs/adapters/electron/migration/autoMigrator.d.ts +184 -0
  30. package/dist/cjs/adapters/electron/migration/autoMigrator.js +441 -0
  31. package/dist/cjs/adapters/electron/migration/index.d.ts +9 -0
  32. package/dist/cjs/adapters/electron/migration/index.js +29 -0
  33. package/dist/cjs/adapters/electron/preload.d.ts +126 -0
  34. package/dist/cjs/adapters/electron/preload.js +233 -0
  35. package/dist/cjs/adapters/electron/recovery/corruptionDetector.d.ts +214 -0
  36. package/dist/cjs/adapters/electron/recovery/corruptionDetector.js +359 -0
  37. package/dist/cjs/adapters/electron/recovery/index.d.ts +11 -0
  38. package/dist/cjs/adapters/electron/recovery/index.js +34 -0
  39. package/dist/cjs/adapters/electron/recovery/walCheckpoint.d.ts +186 -0
  40. package/dist/cjs/adapters/electron/recovery/walCheckpoint.js +263 -0
  41. package/dist/cjs/adapters/electron/renderer.d.ts +9 -0
  42. package/dist/cjs/adapters/electron/renderer.js +33 -0
  43. package/dist/cjs/adapters/electron/window/index.d.ts +9 -0
  44. package/dist/cjs/adapters/electron/window/index.js +29 -0
  45. package/dist/cjs/adapters/electron/window/windowManager.d.ts +190 -0
  46. package/dist/cjs/adapters/electron/window/windowManager.js +321 -0
  47. package/dist/cjs/adapters/indexedDbAdapter.d.ts +490 -0
  48. package/dist/cjs/adapters/indexedDbAdapter.js +993 -0
  49. package/dist/cjs/adapters/postgresAdapter.d.ts +424 -0
  50. package/dist/cjs/adapters/postgresAdapter.js +889 -0
  51. package/dist/cjs/adapters/sqlJsAdapter.d.ts +64 -0
  52. package/dist/cjs/adapters/sqlJsAdapter.js +268 -0
  53. package/dist/cjs/adapters/supabase.d.ts +58 -0
  54. package/dist/cjs/adapters/supabase.js +401 -0
  55. package/dist/cjs/codecs/BrowserBlobCodec.d.ts +14 -0
  56. package/dist/cjs/codecs/BrowserBlobCodec.js +57 -0
  57. package/dist/cjs/codecs/NodeBlobCodec.d.ts +14 -0
  58. package/dist/cjs/codecs/NodeBlobCodec.js +59 -0
  59. package/dist/cjs/core/contracts/blobCodec.d.ts +15 -0
  60. package/dist/cjs/core/contracts/blobCodec.js +15 -0
  61. package/dist/cjs/core/contracts/context.d.ts +221 -0
  62. package/dist/cjs/core/contracts/context.js +15 -0
  63. package/dist/cjs/core/contracts/dialect.d.ts +154 -0
  64. package/dist/cjs/core/contracts/dialect.js +15 -0
  65. package/dist/cjs/core/contracts/events.d.ts +225 -0
  66. package/dist/cjs/core/contracts/events.js +15 -0
  67. package/dist/cjs/core/contracts/exporter.d.ts +13 -0
  68. package/dist/cjs/core/contracts/exporter.js +15 -0
  69. package/dist/cjs/core/contracts/extensions.d.ts +73 -0
  70. package/dist/cjs/core/contracts/extensions.js +15 -0
  71. package/dist/cjs/core/contracts/features.d.ts +25 -0
  72. package/dist/cjs/core/contracts/features.js +61 -0
  73. package/dist/cjs/core/contracts/fts.d.ts +66 -0
  74. package/dist/cjs/core/contracts/fts.js +15 -0
  75. package/dist/cjs/core/contracts/hooks.d.ts +481 -0
  76. package/dist/cjs/core/contracts/hooks.js +140 -0
  77. package/dist/cjs/core/contracts/index.d.ts +260 -0
  78. package/dist/cjs/core/contracts/index.js +41 -0
  79. package/dist/cjs/core/contracts/limitations.d.ts +46 -0
  80. package/dist/cjs/core/contracts/limitations.js +218 -0
  81. package/dist/cjs/core/contracts/performance.d.ts +308 -0
  82. package/dist/cjs/core/contracts/performance.js +144 -0
  83. package/dist/cjs/core/database.d.ts +220 -0
  84. package/dist/cjs/core/database.js +136 -0
  85. package/dist/cjs/core/portable.d.ts +23 -0
  86. package/dist/cjs/core/portable.js +66 -0
  87. package/dist/cjs/core/resolver.d.ts +77 -0
  88. package/dist/cjs/core/resolver.js +235 -0
  89. package/dist/cjs/dialects/PostgresDialect.d.ts +35 -0
  90. package/dist/cjs/dialects/PostgresDialect.js +143 -0
  91. package/dist/cjs/dialects/SqliteDialect.d.ts +35 -0
  92. package/dist/cjs/dialects/SqliteDialect.js +142 -0
  93. package/dist/cjs/dialects/shared.d.ts +17 -0
  94. package/dist/cjs/dialects/shared.js +90 -0
  95. package/dist/cjs/exporters/PostgresExporter.d.ts +14 -0
  96. package/dist/cjs/exporters/PostgresExporter.js +61 -0
  97. package/dist/cjs/exporters/SqliteFileExporter.d.ts +16 -0
  98. package/dist/cjs/exporters/SqliteFileExporter.js +43 -0
  99. package/dist/cjs/features/backup/cloudBackup.d.ts +219 -0
  100. package/dist/cjs/features/backup/cloudBackup.js +209 -0
  101. package/dist/cjs/features/kv/idb.d.ts +79 -0
  102. package/dist/cjs/features/kv/idb.js +32 -0
  103. package/dist/cjs/features/kv/index.d.ts +14 -0
  104. package/dist/cjs/features/kv/index.js +40 -0
  105. package/dist/cjs/features/kv/indexedDbKeyValueStore.d.ts +77 -0
  106. package/dist/cjs/features/kv/indexedDbKeyValueStore.js +116 -0
  107. package/dist/cjs/features/kv/keyValueStore.d.ts +48 -0
  108. package/dist/cjs/features/kv/keyValueStore.js +67 -0
  109. package/dist/cjs/features/kv/sqlKeyValueStore.d.ts +34 -0
  110. package/dist/cjs/features/kv/sqlKeyValueStore.js +81 -0
  111. package/dist/cjs/features/kv/valueCodec.d.ts +35 -0
  112. package/dist/cjs/features/kv/valueCodec.js +426 -0
  113. package/dist/cjs/features/migrations/dataExport.d.ts +77 -0
  114. package/dist/cjs/features/migrations/dataExport.js +194 -0
  115. package/dist/cjs/features/migrations/dataImport.d.ts +54 -0
  116. package/dist/cjs/features/migrations/dataImport.js +300 -0
  117. package/dist/cjs/features/migrations/migration.d.ts +89 -0
  118. package/dist/cjs/features/migrations/migration.js +187 -0
  119. package/dist/cjs/features/migrations/schemaMigrations.d.ts +93 -0
  120. package/dist/cjs/features/migrations/schemaMigrations.js +220 -0
  121. package/dist/cjs/features/sync/conflicts/conflictResolver.d.ts +222 -0
  122. package/dist/cjs/features/sync/conflicts/conflictResolver.js +366 -0
  123. package/dist/cjs/features/sync/conflicts/index.d.ts +9 -0
  124. package/dist/cjs/features/sync/conflicts/index.js +21 -0
  125. package/dist/cjs/features/sync/crossPlatformSync.d.ts +281 -0
  126. package/dist/cjs/features/sync/crossPlatformSync.js +551 -0
  127. package/dist/cjs/features/sync/devices/deviceManager.d.ts +243 -0
  128. package/dist/cjs/features/sync/devices/deviceManager.js +450 -0
  129. package/dist/cjs/features/sync/devices/index.d.ts +10 -0
  130. package/dist/cjs/features/sync/devices/index.js +21 -0
  131. package/dist/cjs/features/sync/index.d.ts +37 -0
  132. package/dist/cjs/features/sync/index.js +111 -0
  133. package/dist/cjs/features/sync/protocol/index.d.ts +11 -0
  134. package/dist/cjs/features/sync/protocol/index.js +23 -0
  135. package/dist/cjs/features/sync/protocol/messages.d.ts +348 -0
  136. package/dist/cjs/features/sync/protocol/messages.js +215 -0
  137. package/dist/cjs/features/sync/protocol/vectorClock.d.ts +164 -0
  138. package/dist/cjs/features/sync/protocol/vectorClock.js +256 -0
  139. package/dist/cjs/features/sync/syncManager.d.ts +348 -0
  140. package/dist/cjs/features/sync/syncManager.js +455 -0
  141. package/dist/cjs/features/sync/tables/index.d.ts +10 -0
  142. package/dist/cjs/features/sync/tables/index.js +21 -0
  143. package/dist/cjs/features/sync/tables/syncLogManager.d.ts +216 -0
  144. package/dist/cjs/features/sync/tables/syncLogManager.js +423 -0
  145. package/dist/cjs/features/sync/transport/httpTransport.d.ts +123 -0
  146. package/dist/cjs/features/sync/transport/httpTransport.js +346 -0
  147. package/dist/cjs/features/sync/transport/index.d.ts +12 -0
  148. package/dist/cjs/features/sync/transport/index.js +25 -0
  149. package/dist/cjs/features/sync/transport/transport.d.ts +259 -0
  150. package/dist/cjs/features/sync/transport/transport.js +163 -0
  151. package/dist/cjs/features/sync/transport/websocketTransport.d.ts +126 -0
  152. package/dist/cjs/features/sync/transport/websocketTransport.js +342 -0
  153. package/dist/cjs/fts/PostgresFts.d.ts +29 -0
  154. package/dist/cjs/fts/PostgresFts.js +77 -0
  155. package/dist/cjs/fts/SqliteFts5.d.ts +22 -0
  156. package/dist/cjs/fts/SqliteFts5.js +58 -0
  157. package/dist/cjs/index.d.ts +30 -0
  158. package/dist/cjs/index.js +101 -0
  159. package/dist/cjs/package.json +3 -0
  160. package/dist/cjs/shared/connectionGate.d.ts +94 -0
  161. package/dist/cjs/shared/connectionGate.js +77 -0
  162. package/dist/cjs/shared/errors.d.ts +23 -0
  163. package/dist/cjs/shared/errors.js +45 -0
  164. package/dist/cjs/shared/logger.d.ts +26 -0
  165. package/dist/cjs/shared/logger.js +40 -0
  166. package/dist/cjs/shared/parameterUtils.d.ts +16 -0
  167. package/dist/cjs/shared/parameterUtils.js +59 -0
  168. package/dist/cjs/shared/postgresTarget.d.ts +11 -0
  169. package/dist/cjs/shared/postgresTarget.js +30 -0
  170. package/dist/cjs/shared/segment.d.ts +43 -0
  171. package/dist/cjs/shared/segment.js +63 -0
  172. package/dist/cjs/shared/serializedTransaction.d.ts +14 -0
  173. package/dist/cjs/shared/serializedTransaction.js +74 -0
  174. package/dist/cjs/shared/splitSqlStatements.d.ts +27 -0
  175. package/dist/cjs/shared/splitSqlStatements.js +163 -0
  176. package/dist/cjs/shared/sqlPlaceholders.d.ts +48 -0
  177. package/dist/cjs/shared/sqlPlaceholders.js +263 -0
  178. package/dist/cjs/types/index.d.ts +29 -0
  179. package/dist/cjs/types/index.js +33 -0
  180. package/dist/core/portable.d.ts +23 -0
  181. package/dist/core/portable.d.ts.map +1 -0
  182. package/dist/core/portable.js +23 -0
  183. package/dist/core/portable.js.map +1 -0
  184. package/dist/features/migrations/schemaMigrations.d.ts +93 -0
  185. package/dist/features/migrations/schemaMigrations.d.ts.map +1 -0
  186. package/dist/features/migrations/schemaMigrations.js +216 -0
  187. package/dist/features/migrations/schemaMigrations.js.map +1 -0
  188. package/dist/index.d.ts +1 -0
  189. package/dist/index.d.ts.map +1 -1
  190. package/dist/index.js +1 -0
  191. package/dist/index.js.map +1 -1
  192. package/package.json +139 -24
@@ -0,0 +1,308 @@
1
+ /**
2
+ * Performance Configuration Types for SQL Storage Adapter
3
+ *
4
+ * This module defines the performance tier system, caching configuration,
5
+ * and optimization options that enable cost/accuracy tradeoffs across
6
+ * all adapter implementations.
7
+ *
8
+ * @packageDocumentation
9
+ * @module @framers/sql-storage-adapter/performance
10
+ *
11
+ * @remarks
12
+ * The performance system is designed to be:
13
+ * - **Platform-agnostic**: Same API across browser, mobile, desktop, cloud
14
+ * - **Extensible**: Hooks and metadata support for custom extensions
15
+ * - **Configurable**: Sensible defaults with full override capability
16
+ * - **Observable**: Built-in metrics and slow query logging
17
+ *
18
+ * @example Basic usage with tier presets
19
+ * ```typescript
20
+ * import { createDatabase } from '@framers/sql-storage-adapter';
21
+ *
22
+ * // Development: prioritize speed
23
+ * const devDb = await createDatabase({
24
+ * performance: { tier: 'fast' }
25
+ * });
26
+ *
27
+ * // Production analytics: prioritize accuracy
28
+ * const analyticsDb = await createDatabase({
29
+ * performance: { tier: 'accurate', trackMetrics: true }
30
+ * });
31
+ * ```
32
+ */
33
+ /**
34
+ * Performance tier presets for common use cases.
35
+ *
36
+ * Each tier provides sensible defaults that can be individually overridden.
37
+ * The tier affects caching, batching, validation, and query optimization.
38
+ *
39
+ * | Tier | Use Case | Caching | Batching | Validation |
40
+ * |------|----------|---------|----------|------------|
41
+ * | `fast` | Development, testing | Aggressive | Yes | Minimal |
42
+ * | `balanced` | General production | Moderate | No | Standard |
43
+ * | `accurate` | Analytics, reporting | Disabled | No | Full |
44
+ * | `efficient` | Mobile, battery-constrained | Moderate | Yes | Minimal |
45
+ * | `custom` | Full manual control | Manual | Manual | Manual |
46
+ *
47
+ * @example
48
+ * ```typescript
49
+ * // Mobile app with battery optimization
50
+ * const db = await createDatabase({
51
+ * performance: { tier: 'efficient' }
52
+ * });
53
+ * ```
54
+ */
55
+ export type PerformanceTier = 'fast' | 'balanced' | 'accurate' | 'efficient' | 'custom';
56
+ /**
57
+ * Default settings for each performance tier.
58
+ *
59
+ * @internal
60
+ */
61
+ export declare const TIER_DEFAULTS: Record<Exclude<PerformanceTier, 'custom'>, Readonly<PerformanceSettings>>;
62
+ /**
63
+ * Individual performance settings (all fields required).
64
+ *
65
+ * @internal
66
+ * Used internally after merging tier defaults with user overrides.
67
+ */
68
+ export interface PerformanceSettings {
69
+ /** Enable query result caching */
70
+ readonly cacheEnabled: boolean;
71
+ /** Cache TTL in milliseconds */
72
+ readonly cacheTtlMs: number;
73
+ /** Maximum cache entries */
74
+ readonly cacheMaxEntries: number;
75
+ /** Enable write batching */
76
+ readonly batchWrites: boolean;
77
+ /** Batch flush interval in ms */
78
+ readonly batchFlushIntervalMs: number;
79
+ /** Maximum batch size before auto-flush */
80
+ readonly batchMaxSize: number;
81
+ /** Validate SQL before execution */
82
+ readonly validateSql: boolean;
83
+ /** Track performance metrics */
84
+ readonly trackMetrics: boolean;
85
+ /** Log slow queries above this threshold in ms */
86
+ readonly slowQueryThresholdMs: number;
87
+ /** Retry transient errors */
88
+ readonly retryOnError: boolean;
89
+ /** Maximum retry attempts */
90
+ readonly maxRetries: number;
91
+ /** Retry delay in ms */
92
+ readonly retryDelayMs: number;
93
+ }
94
+ /**
95
+ * Performance configuration options provided by users.
96
+ *
97
+ * All fields are optional; unspecified fields use tier defaults.
98
+ *
99
+ * @example Override specific settings while using a tier
100
+ * ```typescript
101
+ * const db = await createDatabase({
102
+ * performance: {
103
+ * tier: 'balanced',
104
+ * cacheTtlMs: 30000, // Override: longer cache
105
+ * trackMetrics: true, // Override: enable metrics
106
+ * }
107
+ * });
108
+ * ```
109
+ */
110
+ export interface PerformanceConfig {
111
+ /**
112
+ * Performance tier preset.
113
+ *
114
+ * @defaultValue 'balanced'
115
+ */
116
+ tier?: PerformanceTier;
117
+ /**
118
+ * Enable query result caching.
119
+ *
120
+ * When enabled, identical SELECT queries return cached results
121
+ * until the cache TTL expires or cache is invalidated.
122
+ *
123
+ * @remarks
124
+ * - Caching is per-adapter instance (not shared)
125
+ * - Cache is invalidated on any write operation to affected tables
126
+ * - Use `accurate` tier for systems where stale data is unacceptable
127
+ *
128
+ * @defaultValue tier-dependent
129
+ */
130
+ cacheEnabled?: boolean;
131
+ /**
132
+ * Cache time-to-live in milliseconds.
133
+ *
134
+ * After this duration, cached query results are considered stale
135
+ * and will be re-fetched on next access.
136
+ *
137
+ * @defaultValue 5000 for balanced tier
138
+ */
139
+ cacheTtlMs?: number;
140
+ /**
141
+ * Maximum number of cached query results.
142
+ *
143
+ * When exceeded, least-recently-used entries are evicted.
144
+ *
145
+ * @defaultValue 1000 for balanced tier
146
+ */
147
+ cacheMaxEntries?: number;
148
+ /**
149
+ * Enable write batching.
150
+ *
151
+ * When enabled, write operations (INSERT, UPDATE, DELETE) are
152
+ * collected and executed in batches to reduce I/O operations.
153
+ *
154
+ * @remarks
155
+ * - Recommended for mobile/browser environments
156
+ * - Not recommended for systems requiring immediate consistency
157
+ * - Batch is flushed on `batchFlushIntervalMs` or `batchMaxSize`
158
+ *
159
+ * @defaultValue false for balanced tier, true for efficient tier
160
+ */
161
+ batchWrites?: boolean;
162
+ /**
163
+ * Batch flush interval in milliseconds.
164
+ *
165
+ * Accumulated writes are flushed after this interval.
166
+ *
167
+ * @defaultValue 100 for balanced tier
168
+ */
169
+ batchFlushIntervalMs?: number;
170
+ /**
171
+ * Maximum batch size before auto-flush.
172
+ *
173
+ * When batch reaches this size, it is immediately flushed
174
+ * regardless of the flush interval.
175
+ *
176
+ * @defaultValue 50 for balanced tier
177
+ */
178
+ batchMaxSize?: number;
179
+ /**
180
+ * Validate SQL statements before execution.
181
+ *
182
+ * Performs basic syntax and injection checks.
183
+ *
184
+ * @defaultValue true for balanced tier
185
+ */
186
+ validateSql?: boolean;
187
+ /**
188
+ * Track performance metrics.
189
+ *
190
+ * When enabled, the adapter tracks:
191
+ * - Total queries/mutations/transactions
192
+ * - Average query duration
193
+ * - Error counts
194
+ * - Uptime
195
+ *
196
+ * Retrieve metrics via `adapter.getMetrics()`.
197
+ *
198
+ * @defaultValue true for balanced tier
199
+ */
200
+ trackMetrics?: boolean;
201
+ /**
202
+ * Slow query logging threshold in milliseconds.
203
+ *
204
+ * Queries exceeding this duration are logged at warn level.
205
+ *
206
+ * @defaultValue 100 for balanced tier
207
+ */
208
+ slowQueryThresholdMs?: number;
209
+ /**
210
+ * Retry operations on transient errors.
211
+ *
212
+ * Transient errors include network timeouts, connection resets,
213
+ * and deadlocks.
214
+ *
215
+ * @defaultValue true for balanced tier
216
+ */
217
+ retryOnError?: boolean;
218
+ /**
219
+ * Maximum retry attempts.
220
+ *
221
+ * @defaultValue 3 for balanced tier
222
+ */
223
+ maxRetries?: number;
224
+ /**
225
+ * Delay between retry attempts in milliseconds.
226
+ *
227
+ * Uses exponential backoff: delay * 2^attempt.
228
+ *
229
+ * @defaultValue 100 for balanced tier
230
+ */
231
+ retryDelayMs?: number;
232
+ }
233
+ /**
234
+ * Cache entry for query results.
235
+ *
236
+ * @internal
237
+ */
238
+ export interface CacheEntry<T = unknown> {
239
+ /** Cached result data */
240
+ readonly data: T;
241
+ /** Timestamp when entry was created (ms since epoch) */
242
+ readonly createdAt: number;
243
+ /** Timestamp when entry expires (ms since epoch) */
244
+ readonly expiresAt: number;
245
+ /** Tables affected by this query (for invalidation) */
246
+ readonly affectedTables: ReadonlyArray<string>;
247
+ /** Cache hit count for LRU tracking */
248
+ hits: number;
249
+ /** Last access timestamp for LRU tracking */
250
+ lastAccessedAt: number;
251
+ }
252
+ /**
253
+ * Cache statistics for monitoring (public API is readonly).
254
+ */
255
+ export interface CacheStats {
256
+ /** Total cache hits */
257
+ readonly hits: number;
258
+ /** Total cache misses */
259
+ readonly misses: number;
260
+ /** Hit ratio (hits / (hits + misses)) */
261
+ readonly hitRatio: number;
262
+ /** Current number of entries */
263
+ readonly size: number;
264
+ /** Total bytes used (approximate) */
265
+ readonly bytesUsed: number;
266
+ /** Number of evictions */
267
+ readonly evictions: number;
268
+ /** Number of invalidations */
269
+ readonly invalidations: number;
270
+ }
271
+ /**
272
+ * Mutable version of CacheStats for internal use.
273
+ */
274
+ export type MutableCacheStats = {
275
+ -readonly [K in keyof CacheStats]: CacheStats[K];
276
+ };
277
+ /**
278
+ * Resolves performance configuration by merging tier defaults with user overrides.
279
+ *
280
+ * @param config - User-provided performance configuration
281
+ * @returns Fully resolved performance settings
282
+ *
283
+ * @example
284
+ * ```typescript
285
+ * const settings = resolvePerformanceConfig({ tier: 'fast', cacheTtlMs: 10000 });
286
+ * // Returns fast tier defaults with cacheTtlMs overridden to 10000
287
+ * ```
288
+ */
289
+ export declare function resolvePerformanceConfig(config?: PerformanceConfig): PerformanceSettings;
290
+ /**
291
+ * Checks if an error is transient and should be retried.
292
+ *
293
+ * @param error - The error to check
294
+ * @returns true if the error is transient
295
+ *
296
+ * @example
297
+ * ```typescript
298
+ * try {
299
+ * await db.run('INSERT INTO users (name) VALUES (?)', ['Alice']);
300
+ * } catch (error) {
301
+ * if (isTransientError(error)) {
302
+ * // Retry the operation
303
+ * }
304
+ * }
305
+ * ```
306
+ */
307
+ export declare function isTransientError(error: unknown): boolean;
308
+ //# sourceMappingURL=performance.d.ts.map
@@ -0,0 +1,144 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var performance_exports = {};
19
+ __export(performance_exports, {
20
+ TIER_DEFAULTS: () => TIER_DEFAULTS,
21
+ isTransientError: () => isTransientError,
22
+ resolvePerformanceConfig: () => resolvePerformanceConfig
23
+ });
24
+ module.exports = __toCommonJS(performance_exports);
25
+ const TIER_DEFAULTS = {
26
+ fast: {
27
+ cacheEnabled: true,
28
+ cacheTtlMs: 3e4,
29
+ cacheMaxEntries: 500,
30
+ batchWrites: true,
31
+ batchFlushIntervalMs: 50,
32
+ batchMaxSize: 100,
33
+ validateSql: false,
34
+ trackMetrics: false,
35
+ slowQueryThresholdMs: 500,
36
+ retryOnError: false,
37
+ maxRetries: 1,
38
+ retryDelayMs: 100
39
+ },
40
+ balanced: {
41
+ cacheEnabled: true,
42
+ cacheTtlMs: 5e3,
43
+ cacheMaxEntries: 1e3,
44
+ batchWrites: false,
45
+ batchFlushIntervalMs: 100,
46
+ batchMaxSize: 50,
47
+ validateSql: true,
48
+ trackMetrics: true,
49
+ slowQueryThresholdMs: 100,
50
+ retryOnError: true,
51
+ maxRetries: 3,
52
+ retryDelayMs: 100
53
+ },
54
+ accurate: {
55
+ cacheEnabled: false,
56
+ cacheTtlMs: 0,
57
+ cacheMaxEntries: 0,
58
+ batchWrites: false,
59
+ batchFlushIntervalMs: 0,
60
+ batchMaxSize: 1,
61
+ validateSql: true,
62
+ trackMetrics: true,
63
+ slowQueryThresholdMs: 50,
64
+ retryOnError: true,
65
+ maxRetries: 5,
66
+ retryDelayMs: 200
67
+ },
68
+ efficient: {
69
+ cacheEnabled: true,
70
+ cacheTtlMs: 6e4,
71
+ cacheMaxEntries: 200,
72
+ batchWrites: true,
73
+ batchFlushIntervalMs: 500,
74
+ batchMaxSize: 20,
75
+ validateSql: false,
76
+ trackMetrics: false,
77
+ slowQueryThresholdMs: 200,
78
+ retryOnError: true,
79
+ maxRetries: 3,
80
+ retryDelayMs: 500
81
+ }
82
+ };
83
+ function resolvePerformanceConfig(config = {}) {
84
+ const tier = config.tier ?? "balanced";
85
+ if (tier === "custom") {
86
+ return {
87
+ cacheEnabled: config.cacheEnabled ?? false,
88
+ cacheTtlMs: config.cacheTtlMs ?? 0,
89
+ cacheMaxEntries: config.cacheMaxEntries ?? 0,
90
+ batchWrites: config.batchWrites ?? false,
91
+ batchFlushIntervalMs: config.batchFlushIntervalMs ?? 0,
92
+ batchMaxSize: config.batchMaxSize ?? 1,
93
+ validateSql: config.validateSql ?? true,
94
+ trackMetrics: config.trackMetrics ?? false,
95
+ slowQueryThresholdMs: config.slowQueryThresholdMs ?? 100,
96
+ retryOnError: config.retryOnError ?? false,
97
+ maxRetries: config.maxRetries ?? 1,
98
+ retryDelayMs: config.retryDelayMs ?? 100
99
+ };
100
+ }
101
+ const defaults = TIER_DEFAULTS[tier];
102
+ return {
103
+ cacheEnabled: config.cacheEnabled ?? defaults.cacheEnabled,
104
+ cacheTtlMs: config.cacheTtlMs ?? defaults.cacheTtlMs,
105
+ cacheMaxEntries: config.cacheMaxEntries ?? defaults.cacheMaxEntries,
106
+ batchWrites: config.batchWrites ?? defaults.batchWrites,
107
+ batchFlushIntervalMs: config.batchFlushIntervalMs ?? defaults.batchFlushIntervalMs,
108
+ batchMaxSize: config.batchMaxSize ?? defaults.batchMaxSize,
109
+ validateSql: config.validateSql ?? defaults.validateSql,
110
+ trackMetrics: config.trackMetrics ?? defaults.trackMetrics,
111
+ slowQueryThresholdMs: config.slowQueryThresholdMs ?? defaults.slowQueryThresholdMs,
112
+ retryOnError: config.retryOnError ?? defaults.retryOnError,
113
+ maxRetries: config.maxRetries ?? defaults.maxRetries,
114
+ retryDelayMs: config.retryDelayMs ?? defaults.retryDelayMs
115
+ };
116
+ }
117
+ function isTransientError(error) {
118
+ if (!(error instanceof Error)) {
119
+ return false;
120
+ }
121
+ const message = error.message.toLowerCase();
122
+ const transientPatterns = [
123
+ "timeout",
124
+ "connection reset",
125
+ "connection refused",
126
+ "econnreset",
127
+ "econnrefused",
128
+ "etimedout",
129
+ "network",
130
+ "deadlock",
131
+ "lock wait timeout",
132
+ "too many connections",
133
+ "connection pool",
134
+ "busy",
135
+ "temporarily unavailable"
136
+ ];
137
+ return transientPatterns.some((pattern) => message.includes(pattern));
138
+ }
139
+ // Annotate the CommonJS export names for ESM import in node:
140
+ 0 && (module.exports = {
141
+ TIER_DEFAULTS,
142
+ isTransientError,
143
+ resolvePerformanceConfig
144
+ });
@@ -0,0 +1,220 @@
1
+ /**
2
+ * High-level, user-friendly API for SQL storage.
3
+ *
4
+ * This module provides simple functions like:
5
+ * - createDatabase() - Automatically picks the best database for your environment
6
+ * - connectDatabase() - Explicit connection with clear options
7
+ * - openDatabase() - Simple file-based database
8
+ */
9
+ import { type StorageAdapter } from './contracts/index.js';
10
+ import { type AdapterKind } from './resolver.js';
11
+ import type { PostgresAdapterOptions } from '../adapters/postgresAdapter.js';
12
+ import type { CapacitorAdapterOptions } from '../adapters/capacitorSqliteAdapter.js';
13
+ import type { IndexedDbAdapterOptions } from '../adapters/indexedDbAdapter.js';
14
+ import type { StorageLogger } from '../shared/logger.js';
15
+ /**
16
+ * Database connection options.
17
+ */
18
+ export interface DatabaseOptions {
19
+ /**
20
+ * Database URL (e.g., postgresql://user:pass@host/db).
21
+ * If provided, PostgreSQL is used on Node, with no fallback to SQLite,
22
+ * unless `priority` or `type` says otherwise.
23
+ */
24
+ url?: string;
25
+ /**
26
+ * File path for SQLite database.
27
+ * Used for local/offline storage.
28
+ */
29
+ file?: string;
30
+ /**
31
+ * PostgreSQL-specific configuration, passed on to the Postgres adapter whole.
32
+ * When it names a server (a pool of the caller's, a connection string, or a
33
+ * host, database or user), PostgreSQL is used on Node, with no fallback to
34
+ * SQLite, unless `priority` or `type` says otherwise.
35
+ * `{ connectionString: process.env.DATABASE_URL }` with DATABASE_URL unset
36
+ * names none, and the local default is used.
37
+ */
38
+ postgres?: PostgresAdapterOptions;
39
+ /**
40
+ * Mobile (Capacitor) configuration.
41
+ * Automatically detected on mobile platforms.
42
+ */
43
+ mobile?: CapacitorAdapterOptions;
44
+ /**
45
+ * IndexedDB configuration for browser-native persistence, passed on to the
46
+ * IndexedDB adapter whole (`durability`, `crossTab` and the rest).
47
+ * Uses sql.js (WASM) for SQL execution + IndexedDB for storage.
48
+ *
49
+ * @example
50
+ * ```typescript
51
+ * const db = await createDatabase({
52
+ * priority: ['indexeddb', 'sqljs'],
53
+ * indexedDb: {
54
+ * dbName: 'my-app-db',
55
+ * sqlJsConfig: {
56
+ * locateFile: (file) => `/wasm/${file}`
57
+ * }
58
+ * }
59
+ * });
60
+ * ```
61
+ */
62
+ indexedDb?: IndexedDbAdapterOptions;
63
+ /**
64
+ * Force a specific database type.
65
+ * Leave empty to auto-detect.
66
+ */
67
+ type?: 'postgres' | 'sqlite' | 'browser' | 'mobile' | 'memory';
68
+ /**
69
+ * Custom priority order for adapter selection.
70
+ * Advanced: Only use if you need fine-grained control.
71
+ */
72
+ priority?: AdapterKind[];
73
+ /**
74
+ * Strict resolution, for servers: no local database stands in for a
75
+ * Postgres the options configure. Default: false.
76
+ *
77
+ * - A `url` or `postgres` option that names no server (an empty or unset
78
+ * connection string and no host, database or user) fails on Node instead
79
+ * of opening the local default, unless `file` is given.
80
+ * - A postgres candidate that fails ends resolution with an error, whatever
81
+ * `priority` lists after it.
82
+ *
83
+ * `DATABASE_URL` in the environment does not count here, strict or not.
84
+ * See `StorageResolutionOptions.strict` for the resolver's side.
85
+ */
86
+ strict?: boolean;
87
+ /**
88
+ * SQLite: `true` turns foreign-key enforcement on and `false` turns it off
89
+ * when the adapter opens, and the setting holds when sql.js reopens its
90
+ * connection. Left out, each engine keeps its default: better-sqlite3
91
+ * enforces foreign keys, sql.js, IndexedDB and Capacitor do not.
92
+ * PostgreSQL always enforces them and ignores this. On the resolver, pass
93
+ * `openOptions: { foreignKeys: true }`.
94
+ */
95
+ foreignKeys?: boolean;
96
+ /**
97
+ * Keeps this database's tables apart from other users of the same database:
98
+ * a schema of its own on PostgreSQL, a file with the segment in its name on
99
+ * SQLite, a database name with the segment appended on IndexedDB and
100
+ * Capacitor. See `StorageResolutionOptions.segment`.
101
+ *
102
+ * @example
103
+ * ```typescript
104
+ * // AgentOS's tables beside the app's, in one PostgreSQL database
105
+ * const agentos = await createDatabase({ url: process.env.DATABASE_URL, segment: 'agentos' });
106
+ * ```
107
+ */
108
+ segment?: string;
109
+ /**
110
+ * The logger for this call's resolver lines (pino's fits). Default: the one
111
+ * `setStorageLogger()` set, else the console.
112
+ */
113
+ logger?: StorageLogger;
114
+ }
115
+ /**
116
+ * Create a database connection.
117
+ * Automatically picks the best database for your environment.
118
+ *
119
+ * @example
120
+ * ```typescript
121
+ * // The local default: better-sqlite3 (sql.js without it) on Node, IndexedDB in
122
+ * // a browser. DATABASE_URL in the environment does not change it.
123
+ * const db = await createDatabase();
124
+ *
125
+ * // PostgreSQL from DATABASE_URL on a server; strict fails when it is unset
126
+ * // instead of opening a local file
127
+ * const db = await createDatabase({
128
+ * url: process.env.DATABASE_URL,
129
+ * strict: true
130
+ * });
131
+ *
132
+ * // Specify file path
133
+ * const db = await createDatabase({
134
+ * file: './my-app.db'
135
+ * });
136
+ *
137
+ * // Full PostgreSQL config
138
+ * const db = await createDatabase({
139
+ * postgres: {
140
+ * host: 'db.example.com',
141
+ * database: 'myapp',
142
+ * user: 'dbuser',
143
+ * password: process.env.DB_PASSWORD,
144
+ * ssl: true
145
+ * }
146
+ * });
147
+ * ```
148
+ */
149
+ /**
150
+ * Create (or auto-resolve) the most appropriate database adapter for the current
151
+ * runtime environment. Priority selection logic:
152
+ *
153
+ * 1. Explicit `options.priority` (caller-specified) wins entirely.
154
+ * 2. Explicit `options.type` is mapped to a single adapter priority.
155
+ * 3. Otherwise we auto-detect environment:
156
+ * - Browser: ['indexeddb', 'sqljs']: the database is kept in IndexedDB,
157
+ * with in-memory sql.js where IndexedDB cannot open. `file: ':memory:'`
158
+ * (`createMemoryDatabase()`) keeps ['sqljs'], in memory.
159
+ * - A Capacitor app on a phone: ['capacitor', 'indexeddb', 'sqljs'], as
160
+ * the resolver chooses.
161
+ * - Deno: ['sqljs']
162
+ * - Node.js with a Postgres URL, or Postgres options that name a server:
163
+ * ['postgres']. There is no fallback to SQLite: data meant for Postgres
164
+ * would land in a local file. DATABASE_URL in the environment does not
165
+ * count here.
166
+ * - Node.js otherwise: ['better-sqlite3', 'sqljs'] (native first, wasm fallback)
167
+ *
168
+ * With `strict` on Node, a `url` or `postgres` option that names no server
169
+ * throws instead of choosing the local default (unless `file` is given), and a
170
+ * postgres candidate that fails ends resolution.
171
+ *
172
+ * The function never throws solely due to a native adapter absence; it falls
173
+ * back to next candidates. Only when no candidate can open will it bubble an error.
174
+ */
175
+ export declare function createDatabase(options?: DatabaseOptions): Promise<StorageAdapter>;
176
+ /**
177
+ * Connect to a remote database.
178
+ *
179
+ * @example
180
+ * ```typescript
181
+ * // Simple connection string
182
+ * const db = await connectDatabase('postgresql://user:pass@host/db');
183
+ *
184
+ * // With full config
185
+ * const db = await connectDatabase({
186
+ * host: 'db.example.com',
187
+ * database: 'myapp',
188
+ * user: 'dbuser',
189
+ * password: process.env.DB_PASSWORD,
190
+ * ssl: true
191
+ * });
192
+ * ```
193
+ */
194
+ export declare function connectDatabase(config: string | PostgresAdapterOptions): Promise<StorageAdapter>;
195
+ /**
196
+ * Open a local database file.
197
+ *
198
+ * @example
199
+ * ```typescript
200
+ * // SQLite file
201
+ * const db = await openDatabase('./my-app.db');
202
+ *
203
+ * // In-memory database
204
+ * const db = await openDatabase(':memory:');
205
+ * ```
206
+ */
207
+ export declare function openDatabase(filePath: string): Promise<StorageAdapter>;
208
+ /**
209
+ * Create an in-memory database.
210
+ * Perfect for testing or temporary storage.
211
+ *
212
+ * @example
213
+ * ```typescript
214
+ * const db = await createMemoryDatabase();
215
+ * await db.exec('CREATE TABLE users (id INTEGER, name TEXT)');
216
+ * ```
217
+ */
218
+ export declare function createMemoryDatabase(): Promise<StorageAdapter>;
219
+ export { resolveStorageAdapter } from './resolver.js';
220
+ //# sourceMappingURL=database.d.ts.map