@ckirg/corelib 0.1.22

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.
@@ -0,0 +1,879 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import * as serialize_error from 'serialize-error';
3
+ import { ErrorObject } from 'serialize-error';
4
+ import { S as StrictLogger } from './flight-recorder-BCSVZvWQ.js';
5
+ export { F as FlightRecorderExtras, L as LogMethod, n as nextCid } from './flight-recorder-BCSVZvWQ.js';
6
+ import { Options } from 'ky';
7
+ import { Cron } from 'croner';
8
+
9
+ /**
10
+ * ConfigManager handles the lifecycle of the application's configuration.
11
+ * It manages globalThis.sysconfig and provides an event-driven interface
12
+ * for runtime updates.
13
+ * * Priority: CLI > Environment Variables > Config Files > Defaults
14
+ */
15
+ declare class ConfigManager extends EventEmitter {
16
+ private static instance;
17
+ private _config;
18
+ private _defaultsPath;
19
+ private static _logger;
20
+ /** Single-flight guard for initialize(); null until first call, evicted on failure. */
21
+ private _initPromise;
22
+ private _isInitialized;
23
+ /** Async mutex: every async mutator chains onto this so they never interleave. */
24
+ private _mutationChain;
25
+ /** The staging object of an in-flight staged build, or null. Lets a synchronous
26
+ * updateValue() between awaits survive the final clearAndFill swap. */
27
+ private _inFlightTempConfig;
28
+ /** Throttle: emit the premature-read warning at most once per process (get()
29
+ * is called pervasively, so a per-call warn would flood dev logs). */
30
+ private static _prematureWarnEmitted;
31
+ private constructor();
32
+ /**
33
+ * Singleton accessor for the ConfigManager
34
+ */
35
+ static getInstance(): ConfigManager;
36
+ /**
37
+ * Retrieves a nested configuration value by string path (e.g., "db.mysql.port").
38
+ * @param {string} path - The dot-notation path to the configuration value.
39
+ * @returns The value at the specified path, or undefined if not found.
40
+ */
41
+ get(path: string): unknown;
42
+ /**
43
+ * Static helper to retrieve a configuration value from the singleton instance.
44
+ */
45
+ static get(path: string): unknown;
46
+ /**
47
+ * Idempotent under concurrency: simultaneous calls share one in-flight
48
+ * promise (-01). On failure the promise is evicted so a transient error can
49
+ * self-heal on a later call. Signature unchanged (still awaitable Promise<void>).
50
+ */
51
+ initialize(args?: string[]): Promise<void>;
52
+ /**
53
+ * Main initialization sequence (formerly the body of initialize()).
54
+ * 1. Load Defaults 2. Detect CLI -C 3. Process Hierarchy 4. Env 5. CLI overrides.
55
+ */
56
+ private runInitSequence;
57
+ /**
58
+ * Serializes an async mutator against all other mutators (initialize +
59
+ * loadExternalConfig) via _mutationChain. The work runs after the previous
60
+ * op settles (success OR failure — `.then(work, work)` so a prior rejection
61
+ * never wedges the chain). The chain itself swallows results/errors so it
62
+ * stays resolved; the caller still receives this op's real result/error.
63
+ *
64
+ * Note: the chain's swallow-handler means a `loadExternalConfig` rejection is
65
+ * absorbed if the caller discards the returned promise. `initialize()` is
66
+ * different — it wraps this result in `_initPromise`, which is NOT on the
67
+ * chain, so an un-awaited failed `initialize()` surfaces as an unhandled
68
+ * rejection in Node strict mode. Callers should await/catch both.
69
+ */
70
+ private _enqueue;
71
+ /**
72
+ * Retrieves the current active configuration object.
73
+ */
74
+ getConfig(): Record<string, unknown>;
75
+ /** True once a call to initialize() has settled successfully. */
76
+ get isInitialized(): boolean;
77
+ /**
78
+ * Resolves when the first initialize() settles successfully (rejects if that
79
+ * in-flight initialize fails). If initialize() was never started — OR a prior
80
+ * attempt failed and was evicted — this resolves immediately and does NOT
81
+ * imply the manager is initialized; callers needing guaranteed initialization
82
+ * must call initialize() first and catch its rejection.
83
+ */
84
+ whenReady(): Promise<void>;
85
+ /**
86
+ * Public method to load and merge a new configuration from a URL or file path on demand.
87
+ * Respects the established configuration hierarchy and maintains Env overrides.
88
+ * @param source - The URL or local file path to the configuration.
89
+ */
90
+ loadExternalConfig(source: string): Promise<void>;
91
+ private loadExternalConfigInner;
92
+ /**
93
+ * Loads the base ConfigManager.json from the local directory.
94
+ * Always seeds from the bundled JSON (available in all runtimes, including edge).
95
+ * If the JSON file is also found on disk, it replaces the bundled defaults.
96
+ */
97
+ private loadDefaults;
98
+ /**
99
+ * Fetches and parses configuration from a URL or Local Path.
100
+ * Supports .enc decryption and dynamic confbox parsing by extension.
101
+ */
102
+ private fetchExternalConfig;
103
+ private validateConfigObject;
104
+ /**
105
+ * Processes the specific hierarchy:
106
+ * commonAll -> [AppName].common -> [AppName].[platform] -> [AppName].[platform].[mode]
107
+ */
108
+ private processHierarchy;
109
+ /**
110
+ * Maps CORELIB_ prefixed environment variables to config keys.
111
+ * Example: CORELIB_DB_PORT -> config.db.port
112
+ */
113
+ private applyEnvOverrides;
114
+ /**
115
+ * Maps the parsed Kebab-case CLI overrides to the config structure.
116
+ * Unsafe keys (__proto__/constructor/prototype segments) are dropped.
117
+ */
118
+ private applyCliOverrides;
119
+ /**
120
+ * Core update method that updates both the local object
121
+ * and the active globalThis object, then emits events.
122
+ */
123
+ updateValue(path: string, value: unknown): void;
124
+ /**
125
+ * Helper to set nested object values by string path (e.g., "db.mysql.port")
126
+ */
127
+ private setPath;
128
+ /**
129
+ * Parses values from Env/CLI, automatically handling JSON strings for arrays/objects.
130
+ */
131
+ private parseValue;
132
+ private getAppName;
133
+ /**
134
+ * Logs errors internally. If the global pino logger is available, it uses it
135
+ * along with `serialize-error` to structure the error object for Vector sidecars.
136
+ */
137
+ private logError;
138
+ toJsonString(): string;
139
+ toBuffer(): Buffer;
140
+ /**
141
+ * Test-only: reset init/concurrency state so single-flight and failed-init
142
+ * eviction can be exercised on the singleton. Does NOT clear _config.
143
+ */
144
+ __resetForTests(): void;
145
+ }
146
+
147
+ declare global {
148
+ const __EDGE_RUNTIME__: boolean | undefined;
149
+ }
150
+
151
+ /**
152
+ * Raw FFI exports from the native binary.
153
+ * Use with caution and proper type casting.
154
+ */
155
+ declare const coreFFI: any;
156
+ /**
157
+ * Checks if the native FFI library is loaded and available.
158
+ * @returns {boolean} True if FFI is available, false otherwise.
159
+ */
160
+ declare function isFfiAvailable(): boolean;
161
+ /**
162
+ * Native FFI function: Logs a message from Rust and returns the doubled value.
163
+ * @param {string} msg - The message to log.
164
+ * @param {number} value - The number to double.
165
+ * @returns {number} The doubled value returned from Rust.
166
+ * @throws {Error} If FFI is not loaded or incompatible.
167
+ */
168
+ declare function logAndDouble(msg: string, value: number): number;
169
+ /**
170
+ * Native FFI function: Gets the version of the native library.
171
+ * @returns {string} The version string from Rust.
172
+ * @throws {Error} If FFI is not loaded or incompatible.
173
+ */
174
+ declare function getVersion(): string;
175
+ /**
176
+ * Core section containing FFI and basic runtime information.
177
+ */
178
+ declare const Core: {
179
+ /**
180
+ * Checks if FFI is available.
181
+ */
182
+ isFfiAvailable: typeof isFfiAvailable;
183
+ /**
184
+ * Gets the native library version.
185
+ */
186
+ getVersion: typeof getVersion;
187
+ /**
188
+ * Calls the native log and double function.
189
+ */
190
+ logAndDouble: typeof logAndDouble;
191
+ /**
192
+ * Runs a core task or simply logs the current runtime status.
193
+ * @param {string} [task] - Optional task name to log.
194
+ * @param {Record<string, unknown>} [options] - Optional options for the task.
195
+ */
196
+ run: (task?: string, options?: Record<string, unknown>) => void;
197
+ };
198
+
199
+ /**
200
+ * The standard Result pattern used across the database module to ensure safe error handling.
201
+ * It can be either a success with a value or an error with a reason.
202
+ *
203
+ * @template T The type of the value on success.
204
+ */
205
+ type DatabaseResult<T = unknown> = {
206
+ /** Status of the operation. */
207
+ status: "success";
208
+ /** The result value. */
209
+ value: T;
210
+ /** Optional additional details about the operation. */
211
+ details?: unknown;
212
+ } | {
213
+ /** Status of the operation. */
214
+ status: "error";
215
+ /** The reason for the failure, either as a serialized error or a simple message. */
216
+ reason: ErrorObject | {
217
+ message: string;
218
+ [key: string]: unknown;
219
+ };
220
+ };
221
+ /**
222
+ * Wraps a successful value in a DatabaseResult.
223
+ *
224
+ * @template T The type of the value.
225
+ * @param {T} value - The value to wrap.
226
+ * @param {unknown} [details] - Optional additional details.
227
+ * @returns {DatabaseResult<T>} A success DatabaseResult.
228
+ */
229
+ declare const wrapSuccess: <T>(value: T, details?: unknown) => DatabaseResult<T>;
230
+ /**
231
+ * Wraps an error in a DatabaseResult, serializing it for cross-runtime safety.
232
+ *
233
+ * @template T The expected type of the value (will be unused since this is an error).
234
+ * @param {unknown} error - The error to wrap.
235
+ * @returns {DatabaseResult<T>} An error DatabaseResult.
236
+ */
237
+ declare const wrapError: <T = unknown>(error: unknown) => DatabaseResult<T>;
238
+
239
+ /**
240
+ * Type alias for the library's strict logger.
241
+ */
242
+ type LibraryLogger = StrictLogger;
243
+ /**
244
+ * Database operation mode.
245
+ * - 'stateless': Connects and disconnects for each operation (suitable for serverless/edge).
246
+ * - 'stateful': Maintains persistent connections (suitable for long-running servers).
247
+ */
248
+ type DbMode = "stateless" | "stateful";
249
+ /**
250
+ * Base configuration for all database dialects.
251
+ */
252
+ interface BaseDbConfig {
253
+ /** Database dialect to use. */
254
+ dialect: "sqlite" | "postgres";
255
+ /** Database URL (e.g., 'file:local.db' for SQLite, 'postgres://user:pass@host/db' for Postgres). */
256
+ url: string;
257
+ /** Operation mode. */
258
+ mode: DbMode;
259
+ /** Logger instance (defaults to global logger.child({ section: 'Database' })). */
260
+ logger?: LibraryLogger;
261
+ /** Query timeout in milliseconds. */
262
+ timeoutMs?: number;
263
+ /**
264
+ * Opt-in param logging for the Flight-Recorder query traces. When set, each query's
265
+ * params are passed through this redactor and logged under `params` on `query: exec`.
266
+ * Unset (the default) means params are NOT logged. Use the exported `defaultRedactor`
267
+ * (or a stricter one); the consuming project owns the residual leak risk.
268
+ */
269
+ paramRedactor?: ParamRedactor;
270
+ /**
271
+ * Optional provider for a logical-operation trace id, threaded onto query logs so an AI can
272
+ * follow one operation across many queries/requests. The consuming app populates it (e.g.
273
+ * from an AsyncLocalStorage request/operation context); corelib stays ALS-ignorant.
274
+ */
275
+ getTraceId?: () => string | undefined;
276
+ }
277
+ /** Parameters for SQL queries (positional or named). */
278
+ type QueryParams = unknown[] | Record<string, unknown>;
279
+ /** A param-redaction policy: receives ONE param value, returns its log-safe representation. */
280
+ type ParamRedactor = (value: unknown) => unknown;
281
+ /** Standard data structure for successful query results. */
282
+ interface QueryResponse<T = unknown> {
283
+ /** Array of rows returned by the query. */
284
+ rows: T[];
285
+ /** Number of rows affected by the operation (e.g. on INSERT, UPDATE, DELETE). */
286
+ affectedRows?: number;
287
+ /** Last insert ID (optional for Postgres; use RETURNING clauses). */
288
+ lastInsertId?: string | number | bigint;
289
+ }
290
+ /**
291
+ * Common interface for high-level Database implementations (SqliteDb, PostgresDb).
292
+ * Provides methods for querying and transaction management.
293
+ */
294
+ interface Database {
295
+ /**
296
+ * Executes an SQL query and returns the results.
297
+ * @template T The expected type of the rows.
298
+ * @param {string} sql The SQL query string.
299
+ * @param {QueryParams} [params] Optional query parameters.
300
+ * @returns {Promise<import("./result").DatabaseResult<QueryResponse<T>>>} A promise resolving to the query result.
301
+ */
302
+ query<T = unknown>(sql: string, params?: QueryParams): Promise<DatabaseResult<QueryResponse<T>>>;
303
+ /**
304
+ * Executes a callback within a database transaction.
305
+ * @template T The return type of the callback.
306
+ * @param {() => Promise<import("./result").DatabaseResult<T>>} callback The function to execute within the transaction.
307
+ * @returns {Promise<import("./result").DatabaseResult<T>>} A promise resolving to the result of the callback.
308
+ */
309
+ transaction<T>(callback: () => Promise<DatabaseResult<T>>): Promise<DatabaseResult<T>>;
310
+ /**
311
+ * Disconnects from the database (only useful in 'stateful' mode).
312
+ * @returns {Promise<void>}
313
+ */
314
+ disconnect(): Promise<void>;
315
+ }
316
+
317
+ /**
318
+ * Configuration for Postgres dialect.
319
+ */
320
+ interface PostgresConfig extends BaseDbConfig {
321
+ dialect: "postgres";
322
+ maxConnections?: number;
323
+ ssl?: boolean | {
324
+ rejectUnauthorized?: boolean;
325
+ ca?: string;
326
+ key?: string;
327
+ cert?: string;
328
+ };
329
+ }
330
+
331
+ /**
332
+ * Configuration for SQLite dialect.
333
+ */
334
+ interface SqliteConfig extends BaseDbConfig {
335
+ dialect: "sqlite";
336
+ authToken?: string;
337
+ localPath?: string;
338
+ maxConnections?: number;
339
+ /**
340
+ * Opt-in SQLite journal mode. When set on a local-file url, connect() issues
341
+ * `PRAGMA journal_mode=<value>` immediately after opening the connection.
342
+ * Has no effect on remote libsql (Turso) urls.
343
+ * Default: undefined (no PRAGMA issued — preserves existing behavior).
344
+ */
345
+ journalMode?: "WAL" | "DELETE";
346
+ /**
347
+ * Opt-in SQLite synchronous mode. Issued as `PRAGMA synchronous=<value>` when
348
+ * `journalMode` is also set and the url is a local file.
349
+ * "NORMAL" cuts per-commit fsync cost (~120ms → ~1-5ms for WAL appends).
350
+ * Default: undefined (no PRAGMA issued).
351
+ */
352
+ synchronous?: "NORMAL" | "FULL";
353
+ }
354
+
355
+ /**
356
+ * Public SqliteDb implementation.
357
+ * Provides high-level API for SQLite/LibSQL, handling connections, transactions, and result normalization.
358
+ */
359
+ declare class SqliteDb {
360
+ private config;
361
+ private driver;
362
+ constructor(config: SqliteConfig);
363
+ /**
364
+ * Executes a single SQL query.
365
+ * Joins active transaction if called within a transaction block.
366
+ */
367
+ query<T = unknown>(sql: string, params?: QueryParams): Promise<DatabaseResult<QueryResponse<T>>>;
368
+ /**
369
+ * Disconnects from the database.
370
+ */
371
+ disconnect(): Promise<void>;
372
+ /**
373
+ * Executes operations within a transaction using AsyncLocalStorage for context.
374
+ */
375
+ transaction<T>(callback: () => Promise<DatabaseResult<T>>): Promise<DatabaseResult<T>>;
376
+ }
377
+
378
+ /**
379
+ * Interface for prepared statements in the driver.
380
+ * Prepared statements are pre-compiled SQL queries that can be executed multiple times with different parameters.
381
+ */
382
+ interface PreparedDriverStatement {
383
+ /**
384
+ * Executes the prepared statement with the given parameters.
385
+ * @template T The expected type of the rows in the result.
386
+ * @param {QueryParams} [params] Optional parameters for the query.
387
+ * @returns {Promise<DatabaseResult<QueryResponse<T>>>} A promise resolving to the database result.
388
+ */
389
+ execute<T = unknown>(params?: QueryParams): Promise<DatabaseResult<QueryResponse<T>>>;
390
+ /**
391
+ * Closes the prepared statement and releases associated resources.
392
+ * @returns {Promise<void>}
393
+ */
394
+ close(): Promise<void>;
395
+ }
396
+ /**
397
+ * Core interface for database drivers. All dialect-specific drivers (Postgres, SQLite, etc.) must implement this.
398
+ * This ensures a consistent API for database operations across different storage engines.
399
+ */
400
+ interface DbDriver {
401
+ /**
402
+ * Establishes a connection to the database.
403
+ * @returns {Promise<void>}
404
+ */
405
+ connect(): Promise<void>;
406
+ /**
407
+ * Closes the connection to the database.
408
+ * @returns {Promise<void>}
409
+ */
410
+ disconnect(): Promise<void>;
411
+ /**
412
+ * Executes a one-off SQL query.
413
+ * @template T The expected type of the rows in the result.
414
+ * @param {string} sql The SQL query string.
415
+ * @param {QueryParams} [params] Optional parameters for the query.
416
+ * @returns {Promise<DatabaseResult<QueryResponse<T>>>} A promise resolving to the database result.
417
+ */
418
+ query<T = unknown>(sql: string, params?: QueryParams): Promise<DatabaseResult<QueryResponse<T>>>;
419
+ /**
420
+ * Prepares an SQL query for execution.
421
+ * @param {string} sql The SQL query string to prepare.
422
+ * @returns {Promise<DatabaseResult<PreparedDriverStatement>>} A promise resolving to the prepared statement.
423
+ */
424
+ prepare(sql: string): Promise<DatabaseResult<PreparedDriverStatement>>;
425
+ /**
426
+ * Begins a new database transaction.
427
+ * @returns {Promise<void>}
428
+ */
429
+ beginTransaction(): Promise<void>;
430
+ /**
431
+ * Commits the current database transaction.
432
+ * @returns {Promise<void>}
433
+ */
434
+ commitTransaction(): Promise<void>;
435
+ /**
436
+ * Rolls back the current database transaction.
437
+ * @returns {Promise<void>}
438
+ */
439
+ rollbackTransaction(): Promise<void>;
440
+ /**
441
+ * Streams the results of an SQL query row by row.
442
+ * @template T The expected type of each row.
443
+ * @param {string} sql The SQL query string.
444
+ * @param {QueryParams} params Parameters for the query.
445
+ * @param {(row: T) => void} onRow Callback function called for each row.
446
+ * @returns {Promise<DatabaseResult<void>>} A promise that resolves when the stream finishes.
447
+ */
448
+ stream<T = unknown>(sql: string, params: QueryParams, onRow: (row: T) => void): Promise<DatabaseResult<void>>;
449
+ }
450
+
451
+ /**
452
+ * Handles and logs database errors, returning a serialized error object.
453
+ */
454
+ declare function handleDbError(logger: LibraryLogger, message: string, error: unknown): serialize_error.ErrorObject;
455
+
456
+ /**
457
+ * High-performance polyfill/loader for AsyncLocalStorage across runtimes.
458
+ * Node/Bun use node:async_hooks, while Deno uses std/node compatibility.
459
+ */
460
+ interface AsyncLocalStorageLike<T> {
461
+ run<R>(store: T, callback: () => R): R;
462
+ getStore(): T | undefined;
463
+ }
464
+ /** Active-transaction context carried via AsyncLocalStorage. */
465
+ interface TransactionContext {
466
+ driver: DbDriver;
467
+ /** Flight-recorder id for the transaction; stamped on every query run within it. */
468
+ txId: number;
469
+ }
470
+ declare const transactionStorage: AsyncLocalStorageLike<TransactionContext> | undefined;
471
+ /**
472
+ * Gets the active transaction driver from context.
473
+ */
474
+ declare function getActiveTransaction(): DbDriver | undefined;
475
+ /**
476
+ * Gets the active transaction's flight-recorder id, or undefined outside a transaction.
477
+ */
478
+ declare function getActiveTxId(): number | undefined;
479
+ /**
480
+ * Runs a callback within a transaction context.
481
+ * Internal helper used by DB implementations.
482
+ */
483
+ declare function runInTransaction<T>(driver: DbDriver, txId: number, callback: () => Promise<T>): Promise<T>;
484
+
485
+ /**
486
+ * Public PostgresDb implementation.
487
+ * Provides high-level API for Postgres, handling connections, transactions, and result normalization.
488
+ * Note: For lastInsertId, use RETURNING clauses in your INSERT queries as Postgres does not provide it natively.
489
+ */
490
+ declare class PostgresDb {
491
+ private config;
492
+ private driver;
493
+ constructor(config: PostgresConfig);
494
+ /**
495
+ * Executes a single SQL query.
496
+ * Joins active transaction if called within a transaction block.
497
+ */
498
+ query<T = unknown>(sql: string, params?: QueryParams): Promise<DatabaseResult<QueryResponse<T>>>;
499
+ /**
500
+ * Disconnects from the database.
501
+ */
502
+ disconnect(): Promise<void>;
503
+ /**
504
+ * Executes operations within a transaction using AsyncLocalStorage for context.
505
+ */
506
+ transaction<T>(callback: () => Promise<DatabaseResult<T>>): Promise<DatabaseResult<T>>;
507
+ }
508
+
509
+ declare class PostgresDriver implements DbDriver {
510
+ private config;
511
+ private client;
512
+ constructor(config: PostgresConfig);
513
+ connect(): Promise<void>;
514
+ disconnect(): Promise<void>;
515
+ query<T = unknown>(sql: string, params?: QueryParams): Promise<DatabaseResult<QueryResponse<T>>>;
516
+ prepare(sql: string): Promise<DatabaseResult<PreparedDriverStatement>>;
517
+ beginTransaction(): Promise<void>;
518
+ commitTransaction(): Promise<void>;
519
+ rollbackTransaction(): Promise<void>;
520
+ stream<T>(sql: string, params: QueryParams, onRow: (row: T) => void): Promise<DatabaseResult<void>>;
521
+ }
522
+
523
+ /**
524
+ * Default per-value redactor. Scalars (number/boolean/bigint/null/undefined) pass through —
525
+ * they carry forensic value (ids, equity, timestamps, flags) and are not secrets. Strings
526
+ * that look like tokens/keys (JWT, long hex, long base64) or are very long are masked.
527
+ * Objects/arrays are never deep-logged.
528
+ */
529
+ declare function defaultRedactor(value: unknown): unknown;
530
+ /**
531
+ * Apply `redactor` to a query's params for logging. Positional arrays are capped to the first
532
+ * {@link ARRAY_CAP} (with a `…(+N more)` marker) and each value redacted. Named params redact
533
+ * each value AND mask any value whose KEY looks sensitive. Returns a log-safe shape, or
534
+ * `undefined` when there are no params.
535
+ */
536
+ declare function redactParams(params: QueryParams | undefined, redactor: ParamRedactor): unknown;
537
+
538
+ declare class SqliteDriver implements DbDriver {
539
+ private config;
540
+ private client;
541
+ constructor(config: SqliteConfig);
542
+ connect(): Promise<void>;
543
+ disconnect(): Promise<void>;
544
+ query<T = unknown>(sql: string, params?: QueryParams): Promise<DatabaseResult<QueryResponse<T>>>;
545
+ prepare(sql: string): Promise<DatabaseResult<PreparedDriverStatement>>;
546
+ beginTransaction(): Promise<void>;
547
+ commitTransaction(): Promise<void>;
548
+ rollbackTransaction(): Promise<void>;
549
+ stream<T>(sql: string, params: QueryParams, onRow: (row: T) => void): Promise<DatabaseResult<void>>;
550
+ }
551
+
552
+ /**
553
+ * @file ts-core/src/database/index.ts
554
+ * @description Main entry point for the database module, exporting factory functions and core components.
555
+ */
556
+
557
+ /**
558
+ * Factory function to create a database instance based on the configuration.
559
+ * It automatically selects the correct implementation (Postgres or SQLite) based on the `dialect` field.
560
+ *
561
+ * @param {SqliteConfig | PostgresConfig} config - The database configuration.
562
+ * @returns {Promise<Database>} A promise resolving to a Database instance.
563
+ */
564
+ declare function createDatabase(config: SqliteConfig | PostgresConfig): Promise<Database>;
565
+ /**
566
+ * Database section containing metadata and core components.
567
+ */
568
+ declare const DatabaseSection: {
569
+ /**
570
+ * Current status of the database section.
571
+ */
572
+ status: "active";
573
+ /**
574
+ * Reference to the default Database implementation (SqliteDb).
575
+ */
576
+ Database: typeof SqliteDb;
577
+ /**
578
+ * Factory function to create a database instance.
579
+ */
580
+ createDatabase: typeof createDatabase;
581
+ };
582
+
583
+ declare global {
584
+ var logger: StrictLogger | undefined;
585
+ }
586
+ declare const _default: StrictLogger;
587
+
588
+ /**
589
+ * Standardized structure for serialized HTTP responses.
590
+ * @template T - The expected type of the body if parsed as JSON; otherwise falls back to string.
591
+ */
592
+ interface SerializedResponse<T = unknown> {
593
+ ok: boolean;
594
+ status: number;
595
+ statusText: string;
596
+ headers: Record<string, string>;
597
+ url: string;
598
+ redirected: boolean;
599
+ type: string;
600
+ body: T | string;
601
+ }
602
+ /**
603
+ * Serializes a Fetch API Response object into a plain structure.
604
+ * Attempts to parse the body as JSON if the Content-Type indicates it; otherwise, treats as text.
605
+ * Falls back to raw text on JSON parse errors. Logs warnings if body reading fails.
606
+ * @param response - The Response object to serialize (or null/undefined).
607
+ * @returns A Promise resolving to the SerializedResponse or null if no response provided.
608
+ * @template T - The expected type of the body if JSON-parsed.
609
+ */
610
+ declare function serializeResponse<T = unknown>(response: Response | null | undefined): Promise<SerializedResponse<T> | null>;
611
+ /**
612
+ * @deprecated Use serializeResponse instead.
613
+ */
614
+ declare const RequestResponseSerialize: {
615
+ serialize: typeof serializeResponse;
616
+ };
617
+
618
+ /**
619
+ * Discriminated union for request results, ensuring type-safe success/error handling.
620
+ * @template T - The expected response body type.
621
+ */
622
+ type RequestResult<T = unknown> = {
623
+ status: "success";
624
+ value: SerializedResponse<T>;
625
+ } | {
626
+ status: "error";
627
+ reason: SerializedResponse<T> | ErrorObject;
628
+ };
629
+ /**
630
+ * Makes an HTTP request to a single URL with resilience features.
631
+ * @param url - The URL or Request object to fetch.
632
+ * @param options - Optional ky configuration to override defaults.
633
+ * @returns A Promise resolving to the RequestResult (success or error).
634
+ * @template T - The expected response body type.
635
+ */
636
+ declare function endPoint<T = unknown>(url: string | URL | Request, options?: Options): Promise<RequestResult<T>>;
637
+ /**
638
+ * Makes parallel HTTP requests to multiple URLs.
639
+ * @param urls - Array of URLs or Request objects to fetch.
640
+ * @param options - Optional ky configuration to apply to all requests.
641
+ * @returns A Promise resolving to an array of RequestResults (in input order).
642
+ * @template T - The expected response body type for each request.
643
+ */
644
+ declare function endPoints<T = unknown>(urls: (string | URL | Request)[], options?: Options): Promise<RequestResult<T>[]>;
645
+ /**
646
+ * @deprecated Use endPoint/endPoints functions directly.
647
+ */
648
+ declare const RequestUnlimited: {
649
+ defaults: Options;
650
+ endPoint: typeof endPoint;
651
+ endPoints: typeof endPoints;
652
+ };
653
+
654
+ /**
655
+ * Proxied HTTP client with automatic rotation, fallback, and load-balancing.
656
+ *
657
+ * Public API is identical to RequestUnlimited (same return types, same Options merging, same discriminated union).
658
+ * All heavy lifting (retries, serialization, logging, error handling) is delegated to RequestUnlimited.
659
+ */
660
+ declare class RequestProxied {
661
+ private activeProxies;
662
+ private failureStreaks;
663
+ private currentIndex;
664
+ /**
665
+ * @param proxies - Array of proxy base URLs (e.g. ["https://proxy1...", "https://proxy2..."]).
666
+ * At least one proxy is required. The array is cloned internally.
667
+ * @throws Error if no proxies are provided.
668
+ */
669
+ constructor(proxies: string[]);
670
+ /**
671
+ * Builds the final proxy URL using the URL constructor.
672
+ * Guarantees correct query string handling (? vs &) and URL encoding of the original target.
673
+ */
674
+ private buildProxyUrl;
675
+ /**
676
+ * Records a successful request for a proxy (resets failure streak).
677
+ */
678
+ private trackSuccess;
679
+ /**
680
+ * Records a failure for a proxy.
681
+ * After 3 consecutive failures the proxy is permanently removed from the active list for this session.
682
+ */
683
+ private trackFailure;
684
+ /**
685
+ * Makes a single proxied HTTP request with full fallback.
686
+ *
687
+ * @param url - Original target URL (same as RequestUnlimited).
688
+ * @param suffix - Optional path to append to the proxy base (default "").
689
+ * @param options - Ky options passed through to RequestUnlimited (headers, method, body, etc.).
690
+ */
691
+ endPoint<T = unknown>(url: string | URL | Request, suffix?: string, options?: Options): Promise<RequestResult<T>>;
692
+ /**
693
+ * Makes parallel proxied requests with explicit round-robin load balancing.
694
+ *
695
+ * Each original URL is assigned to a proxy via round-robin.
696
+ * The constructed proxy URLs are then passed to RequestUnlimited.endPoints (parallelism + retries handled there).
697
+ *
698
+ * Note: failure tracking / auto-removal is currently only implemented for endPoint().
699
+ * endPoints uses the current activeProxies snapshot at call time.
700
+ *
701
+ * @param urls - Array of original target URLs.
702
+ * @param suffix - Optional suffix applied to every proxy (default "").
703
+ * @param options - Ky options applied to all requests.
704
+ */
705
+ endPoints<T = unknown>(urls: (string | URL | Request)[], suffix?: string, options?: Options): Promise<RequestResult<T>[]>;
706
+ }
707
+
708
+ declare const Retrieve: {
709
+ run: () => void;
710
+ };
711
+
712
+ /**
713
+ * Run a handler when ANY include cron matches AND
714
+ * NONE of the exclude crons match.
715
+ *
716
+ * Supports 6-field cron expressions (seconds).
717
+ *
718
+ * @param timezone - Optional IANA timezone name (e.g. "America/New_York").
719
+ * Pattern matching uses the wall-clock time in that zone.
720
+ * Defaults to the local system timezone when omitted.
721
+ */
722
+ declare function includeExcludeCron(includeExprs: string[], excludeExprs: string[], handler: () => void, timezone?: string): Cron<undefined>;
723
+
724
+ /**
725
+ * Supported runtimes for the core library.
726
+ */
727
+ type Runtime = "node" | "bun" | "deno" | "cloudflare" | "aws-lambda" | "gcp-cloudrun";
728
+ /**
729
+ * Detects the current execution environment.
730
+ * Uses various global signals and environment variables to distinguish between Node.js, Bun, Deno,
731
+ * and different cloud platforms like Cloudflare Workers, AWS Lambda, and Google Cloud Run.
732
+ *
733
+ * @returns {Runtime} The detected runtime identifier. Defaults to 'node' if unable to determine.
734
+ */
735
+ declare function detectRuntime(): Runtime;
736
+
737
+ /**
738
+ * Main entry point for collecting system telemetry.
739
+ * Automatically detects the runtime and gathers relevant system, process, and environment information.
740
+ *
741
+ * @returns {object} Comprehensive system information.
742
+ */
743
+ declare function getSysInfo(): {
744
+ /** Current runtime name. */
745
+ runtime: "node" | "bun";
746
+ /** Operating system platform. */
747
+ os: NodeJS.Platform;
748
+ /** System architecture. */
749
+ arch: NodeJS.Architecture;
750
+ /** Process ID. */
751
+ pid: number;
752
+ /** Parent process ID. */
753
+ ppid: number;
754
+ /** Current working directory. */
755
+ cwd: string;
756
+ /** Process uptime in seconds. */
757
+ uptime: number;
758
+ /** Operating system version/release. */
759
+ osVersion: any;
760
+ /** System load averages for 1, 5, and 15 minutes. */
761
+ loadAvg: any;
762
+ /** Memory usage statistics. */
763
+ memory: {
764
+ /** Resident Set Size. */
765
+ rss: number;
766
+ /** Total heap size. */
767
+ heapTotal: number;
768
+ /** Used heap size. */
769
+ heapUsed: number;
770
+ /** Memory used by C++ objects bound to JavaScript objects. */
771
+ external: number;
772
+ };
773
+ /** Redacted environment variables. */
774
+ env: Record<string, string>;
775
+ } | {
776
+ runtime: string;
777
+ os: any;
778
+ arch: any;
779
+ pid: any;
780
+ ppid: any;
781
+ cwd: any;
782
+ uptime: number;
783
+ osVersion: any;
784
+ loadAvg: any;
785
+ memory: {
786
+ rss: any;
787
+ heapTotal: null;
788
+ heapUsed: null;
789
+ external: null;
790
+ };
791
+ env: Record<string, string>;
792
+ };
793
+ /**
794
+ * @deprecated Use getSysInfo or detectRuntime instead.
795
+ */
796
+ declare const SysInfo: {
797
+ /**
798
+ * Gets system information.
799
+ */
800
+ get: typeof getSysInfo;
801
+ };
802
+
803
+ /**
804
+ * Gets a `require` function suitable for the current runtime.
805
+ * In Node-like runtimes, it uses `createRequire`. In other runtimes, it returns a function that throws.
806
+ * @returns {Function} The require function.
807
+ */
808
+ declare const getRequire: () => any;
809
+
810
+ /**
811
+ * General utility methods.
812
+ */
813
+ declare const Utils: {
814
+ /**
815
+ * Logs the current runtime information.
816
+ */
817
+ run: () => void;
818
+ };
819
+ /**
820
+ * Gets an environment variable value in a runtime-agnostic way.
821
+ * Supports Node.js (`process.env`) and Deno (`Deno.env`).
822
+ * @param {string} key - The environment variable name.
823
+ * @returns {string | undefined} The value of the environment variable, or undefined if not set.
824
+ */
825
+ declare const getEnv: (key: string) => string | undefined;
826
+ /**
827
+ * Gets all environment variables as a record.
828
+ * Supports Node.js and Deno.
829
+ * @returns {Record<string, string | undefined>} An object containing all environment variables.
830
+ */
831
+ declare const getAllEnv: () => Record<string, string | undefined>;
832
+ /**
833
+ * Reads a text file synchronously in a runtime-agnostic way.
834
+ * @param {string} file - The path to the file.
835
+ * @returns {string} The contents of the file as a string.
836
+ */
837
+ declare const readTextFileSync: (file: string) => string;
838
+ /**
839
+ * Checks if a file or directory exists synchronously.
840
+ * @param {string} file - The path to the file or directory.
841
+ * @returns {boolean} True if it exists, false otherwise.
842
+ */
843
+ declare const existsSync: (file: string) => boolean;
844
+ /**
845
+ * Gets the current working directory in a runtime-agnostic way.
846
+ * @returns {string} The current working directory path.
847
+ */
848
+ declare const getCwd: () => string;
849
+ /**
850
+ * Gets the directory name of the current module.
851
+ * Handles `file:` URLs and edge runtimes.
852
+ * @returns {string} The directory name.
853
+ */
854
+ declare const getDirname: () => any;
855
+ /**
856
+ * Gets the current platform section name.
857
+ * @returns {"linux" | "windows"} The platform identifier.
858
+ */
859
+ declare const getPlatform: () => "linux" | "windows";
860
+ /**
861
+ * Gets the environment mode from `NODE_ENV`.
862
+ * Defaults to 'development' if not set to 'production'.
863
+ * @returns {"development" | "production"} The environment mode.
864
+ */
865
+ declare const getMode: () => "development" | "production";
866
+ /**
867
+ * Gets the path to the system temporary directory.
868
+ * @returns {string} The temporary directory path.
869
+ */
870
+ declare const getTempDir: () => string;
871
+ /**
872
+ * Pauses execution for a specified number of milliseconds.
873
+ *
874
+ * @param {number} ms - The number of milliseconds to wait.
875
+ * @returns {Promise<void>} A promise that resolves after the delay.
876
+ */
877
+ declare const sleep: (ms: number) => Promise<void>;
878
+
879
+ export { type AsyncLocalStorageLike, type BaseDbConfig, ConfigManager, Core, type Database, type DatabaseResult, DatabaseSection, type DbDriver, type DbMode, type LibraryLogger, type ParamRedactor, type PostgresConfig, PostgresDb, PostgresDriver, type PreparedDriverStatement, type QueryParams, type QueryResponse, RequestProxied, RequestResponseSerialize, type RequestResult, RequestUnlimited, Retrieve, type Runtime, type SerializedResponse, type SqliteConfig, SqliteDb, SqliteDriver, StrictLogger, SysInfo, Utils, coreFFI, createDatabase, defaultRedactor, detectRuntime, endPoint, endPoints, existsSync, getActiveTransaction, getActiveTxId, getAllEnv, getCwd, getDirname, getEnv, getMode, getPlatform, getRequire, getSysInfo, getTempDir, getVersion, handleDbError, includeExcludeCron, isFfiAvailable, logAndDouble, _default as logger, readTextFileSync, redactParams, runInTransaction, sleep, transactionStorage, wrapError, wrapSuccess };