/** * TypeScript Type Definitions for FLASH DB * Next-Gen Ultra-Fast Zero-Knowledge Encrypted Embedded Document Database Engine * * No `any` types — full IntelliSense autocomplete and type safety. */ // ============================================================================ // Core Result & Option Types // ============================================================================ export interface FlashEngineOptions { /** @default 'balanced' */ durability?: "strict" | "balanced" | "throughput"; /** Preset tuning: turbo = max throughput, strict = max durability. @default 'balanced' */ performanceProfile?: "strict" | "balanced" | "turbo"; /** Memtable flush threshold in bytes. @default 4194304 (4 MB) */ memtableThreshold?: number; /** Use worker thread for large SSTable flushes. @default true */ useWorkerFlush?: boolean; /** Defer Merkle rebuild on bulk write paths. @default true */ deferMerkleOnWrite?: boolean; /** Skip Merkle tree entirely (turbo default). @default false */ disableMerkle?: boolean; /** Skip persisting index metadata to disk. @default false */ skipIndexPersist?: boolean; /** SSTable deflate level 1–9. @default 1 (6 when storageProfile is compact) */ compressionLevel?: number; /** Passed from client storageProfile — affects SSTable compression default */ storageProfile?: "standard" | "compact"; } export interface FlashClientOptions { secretKey: string | Buffer; dbName?: string; storagePath?: string; /** Pure in-memory engine — no filesystem I/O. Also enabled when storagePath is ':memory:' */ inMemory?: boolean; uri?: string; authKey?: string; pqcHardened?: boolean; autoTimestamps?: boolean; fieldPolicy?: Record; /** `compact` minimizes disk: binary ciphertext, optional blind index, deflate L6 */ storageProfile?: "standard" | "compact"; engineOptions?: FlashEngineOptions; } export interface FlashLifecycleOptions { expireAfterMs?: number; maxDocuments?: number; timeField?: string; archivePath?: string; } export interface FlashPaginationResult> { docs: T[]; nextCursor: string | null; hasMore: boolean; } export interface FlashMaintenanceOptions { sweepIntervalMs?: number; flushIntervalMs?: number; compactIntervalMs?: number; autoStart?: boolean; } export interface FlashPlugin { name: string; onRegister?: (client: FlashClient) => void; beforeInsert?: ( doc: Record, collection: FlashClientCollection, ) => Record | Promise>; afterInsert?: ( doc: Record, collection: FlashClientCollection, ) => void | Promise; beforeUpdate?: ( doc: Record, collection: FlashClientCollection, previous?: Record, ) => Record | Promise>; afterUpdate?: ( doc: Record, collection: FlashClientCollection, ) => void | Promise; } export type FieldPolicyType = "searchable" | "exact" | "encrypted" | "counter" | "plaintext" | "zk-secret"; export interface QueryOptions { limit?: number; skip?: number; sort?: Record; select?: Record | string[]; populate?: PopulateOptions[]; } export interface PopulateOptions { from: string; localField: string; foreignField: string; as: string; single?: boolean; } export interface InsertResult { insertedId: string; merkleRoot: string; } export interface InsertManyResult { insertedCount: number; insertedIds: string[]; } export interface DeleteResult { deletedCount: number; } export interface UpdateResult { matchedCount: number; modifiedCount: number; upsertedId?: string; } export interface VectorSearchResult { docId: string; score: number; } export interface BulkWriteResult { insertedCount: number; matchedCount: number; modifiedCount: number; deletedCount: number; upsertedCount: number; insertedIds: Record; upsertedIds: Record; errors: string[]; } export interface BackupResult { bytesWritten: number; files: string[]; timestamp: string; } export interface RestoreResult { filesRestored: number; destinationPath: string; } export interface AggregateStage { $match?: Record; $group?: Record; $sort?: Record; $limit?: number; $unwind?: string | { path: string }; $addFields?: Record; $project?: Record; $lookup?: { from: string; localField: string; foreignField: string; as: string; single?: boolean; }; } export interface MerkleProofResult { isValid: boolean; leafHash: string; root: string; } export interface IndexSpecification { [field: string]: 1 | -1; } export interface CreateIndexOptions { unique?: boolean; name?: string; } export interface IndexInfo { name: string; spec: IndexSpecification; fields: string[]; unique: boolean; } // ============================================================================ // Schema Types // ============================================================================ export interface SchemaRule { type?: "string" | "number" | "boolean" | "object" | "array" | "date" | "buffer"; required?: boolean; default?: unknown | (() => unknown); min?: number; max?: number; match?: RegExp; enum?: unknown[]; unique?: boolean; trim?: boolean; } export type SchemaDefinition = Record; // ============================================================================ // Binary & Storage // ============================================================================ export type FLASH_TYPE_VALUE = | 0x00 // NULL | 0x01 // BOOLEAN | 0x02 // INT32 | 0x03 // DOUBLE | 0x04 // STRING_UTF8 | 0x05 // BINARY | 0x06 // OBJECT_JSON | 0x07 // ARRAY_JSON | 0x08; // ENCRYPTED_BLOB export interface FLASH_TYPE { NULL: 0x00; BOOLEAN: 0x01; INT32: 0x02; DOUBLE: 0x03; STRING_UTF8: 0x04; BINARY: 0x05; OBJECT_JSON: 0x06; ARRAY_JSON: 0x07; ENCRYPTED_BLOB: 0x08; } export interface FlashBinaryInterface { serialize(doc: Record): Buffer; deserialize(buffer: Buffer): Record; decodeRecord( record: Buffer | Record, ): Record; decodeRecords( records: Array>, ): Record[]; getField( buffer: Buffer, targetKey: string, ): | string | number | boolean | null | undefined | Record | unknown[]; hashKey(str: string): number; } // ============================================================================ // WAL & SSTable // ============================================================================ export type WAL_OPCODE = 0x01 | 0x02 | 0x03 | 0x04; export interface ARC_OP_INTERFACE { INSERT: 0x01; UPDATE: 0x02; DELETE: 0x03; COMMIT: 0x04; } export interface FlashArcOptions { syncOnWrite?: boolean; } export interface FlashSSTableMeta { offset: number; len: number; } // ============================================================================ // Logger // ============================================================================ export type LogLevel = "debug" | "info" | "warn" | "error"; export interface FlashLoggerInterface { setLevel(level: LogLevel): void; debug( module: string, message: string, context?: Record, ): void; info( module: string, message: string, context?: Record, ): void; warn( module: string, message: string, context?: Record, ): void; error( module: string, message: string, context?: Record, ): void; } // ============================================================================ // Class: FlashCipher // ============================================================================ export interface CipherEncryptOptions { aad?: string | Buffer; /** Return raw packed Buffer instead of base64. @default false */ binary?: boolean; } export interface CipherDecryptOptions { asJson?: boolean; aad?: string | Buffer; } export class FlashCipher { readonly key: Buffer; constructor(masterKey: string | Buffer, salt?: string); encrypt( data: string | Buffer | Record, options?: CipherEncryptOptions, ): string | Buffer; decrypt( payload: string | Buffer, asJsonOrOptions?: boolean | CipherDecryptOptions, ): string | Record; encryptDeterministic(plaintext: string, domainKey?: Buffer): string; } // ============================================================================ // Class: FlashBlindIndex // ============================================================================ export interface RangeBucketResult { bucketIndex: number; token: string; exactTrapdoor: string; } export class FlashBlindIndex { readonly ngramSize: number; readonly bucketSize: number; constructor( secretKey: string | Buffer, options?: { ngramSize?: number; bucketSize?: number }, ); generateTrapdoor( fieldName: string, value: string | number | boolean | null, ): string | null; generateTrapdoorBytes( fieldName: string, value: string | number | boolean | null, ): Buffer | null; static trapdoorKey(token: string | Buffer | null | undefined): string | null; static trapdoorBytes(token: string | Buffer): Buffer; generateNGramTrapdoors( fieldName: string, text: string, addHoneyPadding?: boolean, ): string[]; generateNGramTrapdoorsBytes( fieldName: string, text: string, addHoneyPadding?: boolean, ): Buffer[]; generateRangeBuckets( fieldName: string, value: number | Date, ): RangeBucketResult; generateRangeQueryTokens( fieldName: string, min: number, max: number, ): string[]; } // ============================================================================ // Class: FlashHomomorphic // ============================================================================ export interface HomomorphicCiphertext { ciphertext: string; recordId: string; fieldName: string; } export class FlashHomomorphic { constructor(secretKey: string | Buffer); encryptAdd( value: number, recordId: string, fieldName: string, ): HomomorphicCiphertext; aggregateSum(ciphertexts: string[]): string; decryptSum( aggregateCiphertext: string, recordsMetadata: Array<{ recordId: string; fieldName: string }>, ): number; } // ============================================================================ // Class: FlashMerkle // ============================================================================ export class FlashMerkle { constructor(leafHashes: string[]); getRoot(): string; getProof(leafIndex: number): string[]; static verifyProof( leafHash: Buffer | string, proof: string[], root: string, ): boolean; static hash(data: string | Buffer): Buffer; } // ============================================================================ // Class: FlashPQC // ============================================================================ export class FlashPQC { static deriveQuantumHardenedKey(passphrase: string): Buffer; } // ============================================================================ // Class: FlashFuzzyEngine // ============================================================================ export class FlashFuzzyEngine { static levenshteinDistance(a: string, b: string): number; static soundex(str: string): string; static isPhoneticMatch(a: string, b: string, threshold?: number): boolean; } // ============================================================================ // Class: FlashKeyRotationManager // ============================================================================ export class FlashKeyRotationManager { constructor(masterKey: string | Buffer); rotateKey(): { previousVersion: number; newVersion: number; activeKeysCount: number; }; encrypt(data: string | Record): string; decrypt(versionedCiphertext: string): string | Record; needsReEncryption(versionedCiphertext: string): boolean; reEncrypt(oldCiphertext: string): string; batchReEncrypt>( documents: T[], encryptedFields: string[], ): { upgradedCount: number }; } // ============================================================================ // Class: FlashORE // ============================================================================ export class FlashORE { constructor(secretKey: string | Buffer); encrypt(value: number | Date | string, fieldScope?: string): string; static compare(oreTokenA: string, oreTokenB: string): -1 | 0 | 1; static matchesRange( oreToken: string, rangeCriteria: { $gt?: string; $gte?: string; $lt?: string; $lte?: string }, ): boolean; } // ============================================================================ // Class: FlashBinary // ============================================================================ export const FlashBinary: FlashBinaryInterface; // ============================================================================ // Storage: FlashBloomFilter & FlashCompressor // ============================================================================ export class FlashBloomFilter { constructor(expectedItems?: number); add(item: string): void; has(item: string): boolean; toBuffer(): Buffer; static fromBuffer(buffer: Buffer): FlashBloomFilter; } export class FlashCompressor { static compressBlock(data: Buffer, level?: number): Promise; static decompressBlock(data: Buffer): Promise; } // ============================================================================ // Engine: FlashMemTable // ============================================================================ export interface MemTableEntry { key: string; value: Buffer | Record; } export class FlashMemTable { readonly size: number; readonly byteSize: number; set( key: string, value: Buffer | Record, approxBytes?: number, ): void; get(key: string): Buffer | Record | null; delete(key: string): void; scan( minKey?: string | null, maxKey?: string | null, limit?: number, ): MemTableEntry[]; entries(): MemTableEntry[]; clear(): void; } // ============================================================================ // Engine: FlashArc (WAL) // ============================================================================ export { ARC_OP_INTERFACE as ARC_OP }; export { ARC_OP_INTERFACE as WAL_OP }; export type FlashWAL = FlashArc; export class FlashArc { readonly arcPath: string; readonly syncOnWrite: boolean; constructor(arcPath: string, options?: FlashArcOptions); open(): Promise; append(opCode: number, key: string, data: Buffer | string): Promise; recover( onRecord: (opCode: number, key: string, dataBuffer: Buffer) => void, ): Promise; truncate(): Promise; close(): Promise; } // ============================================================================ // Engine: FlashSSTable // ============================================================================ export function fsyncDir(dir: string): Promise; export class FlashSSTable { readonly filePath: string; readonly indexMap: Map; readonly isLoaded: boolean; static write( filePath: string, sortedEntries: MemTableEntry[], options?: { level?: number; compressionLevel?: number }, ): Promise; constructor(filePath: string); load(): Promise; get(key: string): Promise; } // ============================================================================ // Engine: FlashIndexManager // ============================================================================ export type TrapdoorToken = string | Buffer; export interface BlindPayload { exact?: Record; ngrams?: Record; range?: Record; } export class FlashIndexManager { indexDocument(docId: string, blindPayload: BlindPayload): void; removeDocument(docId: string): void; findExact(field: string, trapdoor: TrapdoorToken): Set; findNGrams(field: string, queryTokens: TrapdoorToken[]): Set; findRangeBuckets(field: string, rangeTokens: TrapdoorToken[]): Set; } // ============================================================================ // Engine: FlashCompactor // ============================================================================ export interface CompactionResult { compacted: boolean; originalFiles: number; totalRecordsMerged: number; } export class FlashCompactor { readonly isRunning: boolean; constructor(options?: { maxSSTablesBeforeCompact?: number; compactionIntervalMs?: number; }); start(collections?: FlashCollection[]): void; stop(): void; compactCollection(collection: FlashCollection): Promise; } // ============================================================================ // Engine: FlashUpdateEngine // ============================================================================ export interface UpdateSpecification { $set?: Record; $unset?: Record; $inc?: Record; $mul?: Record; $min?: Record; $max?: Record; $push?: Record; $pull?: Record; $addToSet?: Record; $pop?: Record; $currentDate?: Record; } export class FlashUpdateEngine { static applyUpdate( doc: Record, updateSpec: UpdateSpecification | Record, ): Record; } // ============================================================================ // Engine: FlashQueryEvaluator // ============================================================================ export class FlashQueryEvaluator { static matches( doc: Record, query: Record, ): boolean; } // ============================================================================ // Engine: FlashSecondaryIndexManager // ============================================================================ export class DuplicateKeyError extends Error { readonly code: 11000; readonly keyPattern: Record; readonly keyValue: Record; constructor(field: string, value: unknown, indexName: string); } export class FlashSecondaryIndexManager { createIndex( keySpec: IndexSpecification, options?: CreateIndexOptions, ): string; listIndexes(): IndexInfo[]; dropIndex(name: string): boolean; indexDocument(doc: Record): void; unindexDocument(doc: Record): void; validateUniqueConstraints( doc: Record, excludeId?: string, ): void; } // ============================================================================ // Engine: FlashTTLManager // ============================================================================ export class FlashTTLManager { constructor( collection: FlashCollection, options?: { field?: string; expireAfterSeconds?: number; intervalMs?: number; }, ); start(): void; stop(): void; purgeExpired(): Promise; } // ============================================================================ // Engine: FlashBulkWriter // ============================================================================ export type BulkWriteOperation = | { insertOne: { document: Record } } | { updateOne: { filter: Record; update: UpdateSpecification; upsert?: boolean; }; } | { updateMany: { filter: Record; update: UpdateSpecification; upsert?: boolean; }; } | { deleteOne: { filter: Record } } | { deleteMany: { filter: Record } } | { replaceOne: { filter: Record; replacement: Record; }; }; export class FlashBulkWriter { static execute( collection: FlashClientCollection, operations: BulkWriteOperation[], options?: { ordered?: boolean }, ): Promise; } // ============================================================================ // Engine: FlashBackupManager // ============================================================================ export class FlashBackupManager { static backup( sourcePath: string, destinationPath: string, ): Promise; static restore( backupPath: string, destinationPath: string, ): Promise; } // ============================================================================ // Engine: FlashExplain // ============================================================================ export interface ExplainResult { queryPlanner: { plannerVersion: number; namespace: string; indexFilterSet: boolean; parsedQuery: Record; winningPlan: { stage: "INDEX_SCAN" | "COLL_SCAN"; indexName: string | null; direction: "forward"; }; }; executionStats: { executionSuccess: boolean; nReturned: number; executionTimeMillis: number; totalKeysExamined: number; totalDocsExamined: number; executionStages: { stage: "INDEX_SCAN" | "COLL_SCAN"; nReturned: number; executionTimeMillisEstimate: number; docsExamined: number; }; }; } export class FlashExplain { static analyze( collectionName: string, query: Record, options: QueryOptions, results: Record[], durationMs: number, indexHit?: string | null, ): ExplainResult; } // ============================================================================ // Engine: FlashDeadlockDetector // ============================================================================ export class FlashDeadlockDetector { addDependency(txWaiting: string, txHolding: string): boolean; removeTransaction(txId: string): void; detectCycle(): string[]; } // ============================================================================ // Engine: FlashOnlineIndexer // ============================================================================ export class FlashOnlineIndexer { static buildIndexOnline( collection: FlashCollection, fieldName: string, options?: { chunkSize?: number; onProgress?: (progress: { indexed: number; total: number }) => void; }, ): Promise<{ indexedCount: number; durationMs: number }>; } // ============================================================================ // Schema: FlashSchema // ============================================================================ export class FlashSchema { readonly rules: Record; constructor(definition?: SchemaDefinition); validate(doc: Record): Record; applyDefaults(doc: Record): Record; } // ============================================================================ // ODM: FlashSchemaExtended & FlashModel // ============================================================================ export interface HookNext { (): void; } export class FlashSchemaExtended extends FlashSchema { pre(action: string, fn: (next: HookNext) => void | Promise): this; post( action: string, fn: (doc: Record) => void | Promise, ): this; virtual(name: string): { get(fn: (this: Record) => unknown): { set(fn: (this: Record, value: unknown) => void): void; }; }; method(name: string, fn: (...args: unknown[]) => unknown): this; staticMethod( name: string, fn: (...args: unknown[]) => unknown, ): typeof FlashSchemaExtended; } export interface FlashModelInterface> { create(doc: T): Promise; find(filter?: Record): FlashQuery; findOne(filter?: Record): Promise; findById(id: string): Promise; updateOne( filter: Record, update: UpdateSpecification, ): Promise; deleteOne(filter: Record): Promise; count(filter?: Record): Promise; } export class FlashModel { static compile>( name: string, schema: | FlashSchemaExtended | SchemaDefinition | Record | undefined, collection: FlashClientCollection, ): FlashModelInterface; } // ============================================================================ // Transactions: FlashMVCC // ============================================================================ export interface TransactionInfo { txId: string; readTs: number; } export interface CommitResult { success: boolean; commitTs: number; } export class FlashMVCC { beginTransaction(txId?: string): TransactionInfo; read(txId: string, docId: string): Record | null; write(txId: string, docId: string, doc: Record): void; delete(txId: string, docId: string): void; commit(txId: string): CommitResult; abort(txId: string): void; vacuum(): void; } // ============================================================================ // Transactions: FlashSession // ============================================================================ export class FlashSession { readonly sessionId: string; readonly inTransaction: boolean; constructor(client: FlashClient); startTransaction(): void; commitTransaction(): Promise; abortTransaction(): Promise; } // ============================================================================ // Reactive: FlashChangeStream // ============================================================================ export interface ChangeEvent { operationType: "insert" | "update" | "delete"; doc: Record; id: string; timestamp: number; } export class FlashChangeStream { readonly isOpen: boolean; constructor( filter?: Record | null, onClose?: (() => void) | null, ); emitChange( operationType: "insert" | "update" | "delete", doc: Record, ): void; on(event: "change", listener: (event: ChangeEvent) => void): this; close(): void; } export class FlashEventHub { subscribe( topic: string, handler: (payload: Record, topic?: string) => void, ): () => void; unsubscribe( topic: string, handler: (payload: Record, topic?: string) => void, ): void; publish(topic: string, payload: Record): void; } export class FlashPluginHost { readonly plugins: FlashPlugin[]; use(plugin: FlashPlugin): this; runHook(hook: string, ...args: unknown[]): Promise; } export class FlashLifecycle { constructor( collection: FlashClientCollection, options?: FlashLifecycleOptions, ); sweep(): Promise<{ expired: number; trimmed: number }>; } export class FlashPaginator { static paginate( collection: FlashClientCollection, query?: Record, options?: { cursor?: string; limit?: number; sort?: Record; }, ): Promise; static encodeCursor( doc: Record, sortSpec?: Record, ): string; static decodeCursor( cursor: string, ): { k: string; v: unknown; id: string } | null; } export class FlashMaintenance { start(): this; stop(): void; runNow(): Promise; } export class FlashPipeline { fromNDJSON(filePath: string): this; fromCollection(name: string, query?: Record): this; toCollection(name: string): this; toNDJSON(filePath: string): this; batchSize(n: number): this; run(): Promise>; } export class FlashEventLog { append(data?: Record): Promise>; appendMany(items?: Record[]): Promise; tail( query?: Record, options?: { limit?: number; cursor?: string | null; sort?: Record; }, ): Promise; since( when: Date | number, query?: Record, options?: { limit?: number }, ): Promise[]>; } export class FlashCounter { get(): Promise; increment(by?: number): Promise; decrement(by?: number): Promise; set(value: number): Promise; reset(value?: number): Promise; } export class FlashQueue { enqueue( payload: unknown, options?: { priority?: number }, ): Promise>; dequeue(): Promise | null>; ack(id: string): Promise; fail(id: string, error?: string): Promise; depth(): Promise; } export class FlashHealth { report(): Promise>; } export class FlashSnapshot { exportTo( filePath: string, collectionNames?: string[] | null, ): Promise>; importFrom(filePath: string): Promise>; } // ============================================================================ // Client: FlashQuery (Fluent) // ============================================================================ export interface FlashQueryWhereBuilder> { equals(value: unknown): FlashQuery; gt(value: unknown): FlashQuery; lt(value: unknown): FlashQuery; gte(value: unknown): FlashQuery; lte(value: unknown): FlashQuery; in(values: unknown[]): FlashQuery; regex(pattern: string): FlashQuery; } export class FlashQuery> implements PromiseLike< T[] > { sort(spec: string | Record): this; limit(n: number): this; skip(n: number): this; select(fields: string | Record): this; where(field: string): FlashQueryWhereBuilder; lean(): this; explain(): Promise; stream(): AsyncIterable; then( onfulfilled?: (value: T[]) => TResult1 | PromiseLike, onrejected?: (reason: unknown) => TResult2 | PromiseLike, ): Promise; exec(): Promise; } // ============================================================================ // Client: FlashClientCollection // ============================================================================ export class FlashClientCollection< T extends Record = Record, > { readonly name: string; readonly raw: FlashCollection; insertOne(doc: T): Promise; insertMany(docs: T[]): Promise; find(filter?: Record, options?: QueryOptions): FlashQuery; findOne(filter?: Record): Promise; findById(id: string): Promise; updateOne( filter: Record, update: UpdateSpecification, options?: { upsert?: boolean }, ): Promise; updateMany( filter: Record, update: UpdateSpecification, options?: { upsert?: boolean }, ): Promise; findOneAndUpdate( filter: Record, update: UpdateSpecification, options?: { new?: boolean }, ): Promise; findByIdAndUpdate( id: string, update: UpdateSpecification, options?: { new?: boolean }, ): Promise; deleteOne(filter: Record): Promise; deleteMany(filter: Record): Promise; bulkWrite( operations: BulkWriteOperation[], options?: { ordered?: boolean }, ): Promise; aggregate(pipeline: AggregateStage[]): Promise[]>; count(filter?: Record): Promise; createIndex( keySpec: IndexSpecification, options?: CreateIndexOptions, ): string; listIndexes(): IndexInfo[]; dropIndex(name: string): boolean; watch(filter?: Record | null): FlashChangeStream; paginate( filter?: Record, options?: { cursor?: string; limit?: number; sort?: Record; }, ): Promise>; vectorSearch(params: { vector: number[] | Float32Array; topK?: number; filter?: Record | null; }): Promise<(T & { _score: number })[]>; verifyRecordIntegrity(docId: string): Promise; setSchema( schema: SchemaDefinition | FlashSchema, options?: { expireAfterSeconds?: number; ttlField?: string }, ): this; ask( prompt: string, options?: QueryOptions, ): Promise<(T & { _interpretedQuery?: Record })[]>; timeSeriesBucket( timeField: string, interval: number, aggregations: Record, ): Promise[]>; spatialNear( field: string, nearSpec: Record, ): Promise[]>; } // ============================================================================ // Intelligence Stack (FLASH-exclusive) // ============================================================================ export interface FlashDashboardOptions { port?: number; host?: string; token?: string; } export interface PrivateRAGIngestInput { text: string; title?: string; metadata?: Record; sourceId?: string; } export interface PrivateRAGIngestResult { parentId: string; chunks: number; chunkIds: string[]; } export interface PrivateRAGAskResult { question: string; contextPack: string; sources: Array<{ id: string; text: string; metadata: Record; score: number; }>; tokens: { used: number; savedEstimate: number }; serverSawPlaintext: false; } export interface AgentMemoryEntry { memoryId: string; content: string; tags: string[]; score: number; semantic: number; importance: number; recency: number; } export class FlashPrivateRAG { constructor( client: FlashClient, collectionName?: string, options?: { chunkSize?: number; chunkOverlap?: number; dimensions?: number; }, ); ingest(input: PrivateRAGIngestInput): Promise; ask( question: string, options?: { topK?: number; maxTokens?: number }, ): Promise; exportBundle( question: string, options?: Record, ): Promise>; } export class FlashAgentMemory { constructor( client: FlashClient, namespace?: string, options?: { defaultTtlMs?: number; dimensions?: number }, ); remember( content: string, options?: { tags?: string[]; importance?: number; ttlMs?: number }, ): Promise<{ memoryId: string; expiresAt: number }>; recall( query: string, options?: { topK?: number }, ): Promise; forget(memoryId: string): Promise; pruneExpired(): Promise; } export class FlashSealedVault { readonly isLocked: boolean; unlock(passphrase: string): void; lock(): void; put( recordId: string, payload: Record, ): Promise; get(recordId: string): Promise | null>; list(): Promise[]>; remove(recordId: string): Promise; close(): Promise; } export class FlashEmbeddingVault { ingest( text: string, metadata?: Record, ): Promise>; ask( question: string, options?: Record, ): Promise; exportTextCache(): Record; } export class FlashPortableBundle { exportToFile( collections: string[], filePath: string, options?: Record, ): Promise>; static importFromFile( filePath: string, client: FlashClient, ): Promise>; } export class FlashLangChainAdapter { asVectorStore(): { addDocuments( docs: Array<{ pageContent: string; metadata?: Record }>, ): Promise; similaritySearch( query: string, k?: number, ): Promise< Array<{ pageContent: string; metadata: Record }> >; }; asMemory(): { saveContext(input: string, output: string): Promise; loadMemoryVariables( vars: Record, ): Promise>; }; } export class FlashFederatedQuery { addPeer(name: string, client: FlashClient): this; find( collection: string, filter: Record, options?: QueryOptions, ): Promise[]>; count(collection: string, filter: Record): Promise; } export class FlashMultiAgentSync { registerAgent(agentId: string): void; share(agentId: string, content: string): Promise>; getSharedContext( query: string, options?: { topK?: number }, ): Promise>; } export class FlashComplianceExport { exportSubjectData( collection: string, filter: Record, ): Promise>; eraseSubjectData( collection: string, filter: Record, actor: string, ): Promise>; } export class FlashPromptFirewall { static scan( text: string, options?: { redact?: boolean }, ): { safe: boolean; violations: string[]; redacted: string; originalLength: number; }; static assertSafe(text: string): void; } export class FlashDifferentialPrivacy { static noisyCount(count: number, epsilon?: number): number; static noisySum(sum: number, sensitivity?: number, epsilon?: number): number; } export class FlashKeyCeremony { constructor(shardCount?: number); split(masterKey: string | Buffer): string[]; combine(shards: string[]): string; } export class FlashIntegrityProof { static export( client: FlashClient, collectionName: string, options?: { actor?: string }, ): Promise>; static verify( proof: Record, secretKey: string | Buffer, ): boolean; } export class FlashTimeSeal { seal( event: string, metadata?: Record, ): Record; verify(): { valid: boolean; entries: number }; } export class FlashCloudSync { push(collections: string[], label?: string): Promise>; pull(bundleName?: string): Promise>; listBundles(): Promise; } export class FlashEncryptedCRDT { localWrite(doc: Record): Promise>; applyRemoteDelta(delta: Record): Promise; exportDelta(): Record; } export class FlashBrowserVault { constructor(secretKey: string | Buffer, vaultName?: string); put(key: string, value: Record): Promise; get(key: string): Promise | null>; remove(key: string): Promise; list(): Promise; } export class FlashAuditStream { watch(actor?: string): FlashChangeStream; verify(): { valid: boolean }; getAuditTrail(): Record[]; } export class FlashWireServer { constructor( db: FlashDatabase, options?: { port?: number; host?: string; replicaSet?: string }, ); start(): Promise; stop(): Promise; } export class FlashWireClient { constructor(host?: string, port?: number); command(cmd: Record): Promise>; } export class FlashEdgeNode { constructor(options?: Record); start(): Promise; stop(): Promise; } export class FlashReplicaSet { constructor(options?: Record); addNode( nodeId: string, peers: string[], options?: Record, ): void; startNetworkNodes(): Promise; electLeader(nodeId: string): void; replicateInsert( collection: string, doc: Record, ): Promise; failover(newLeaderId: string): Promise; } // ============================================================================ // Client: Record codec (default buffer pipeline) // ============================================================================ export class FlashRecordCodec { static toBuffer(client: FlashClient, doc: Record): Buffer; static extractId(bufOrObj: Buffer | Record): string | null; static extractBlind(buf: Buffer): Record | null; static extractPlain(buf: Buffer): Record | null; static toEncryptedEnvelope( buf: Buffer, client?: FlashClient, ): EncryptedDocument; static decrypt( client: FlashClient, bufOrObj: Buffer | Record, ): Record; static decryptFields( client: FlashClient, bufOrObj: Buffer | Record, fields: string[], ): Record; static ensureBuffer(docOrBuf: Buffer | Record): Buffer; static encodeForWire(buf: Buffer): { _flashRecord: string }; static decodeFromWire(payload: Buffer | Record): Buffer; } // ============================================================================ // Client: FlashClient // ============================================================================ export class FlashClient { readonly secretKey: string | Buffer; readonly storageProfile: "standard" | "compact"; constructor(config: FlashClientOptions); collection = Record>( name: string, options?: { schema?: SchemaDefinition | FlashSchema }, ): FlashClientCollection; model>( name: string, schema?: FlashSchemaExtended | SchemaDefinition | Record, ): FlashModelInterface; tenant(tenantId: string): FlashClient; startSession(): FlashSession; backup(destinationPath: string): Promise; restore(backupPath: string): Promise; openDashboard(options?: FlashDashboardOptions): import("node:http").Server; privateRAG( collectionName?: string, options?: { chunkSize?: number; chunkOverlap?: number; dimensions?: number; }, ): FlashPrivateRAG; agentMemory( namespace?: string, options?: { defaultTtlMs?: number; dimensions?: number }, ): FlashAgentMemory; sealedVault( vaultName: string, options?: { autoLockMs?: number }, ): FlashSealedVault; integrityProof( collectionName: string, options?: { actor?: string }, ): Promise>; embeddingVault( collectionName?: string, options?: Record, ): FlashEmbeddingVault; portableBundle(): FlashPortableBundle; langChainAdapter(options?: Record): FlashLangChainAdapter; federatedQuery(): FlashFederatedQuery; multiAgentSync(namespace?: string): FlashMultiAgentSync; complianceExport(): FlashComplianceExport; timeSeal(sealPath?: string): FlashTimeSeal; cloudSync(syncDir: string): FlashCloudSync; encryptedCRDT( collectionName: string, nodeId?: string | null, ): FlashEncryptedCRDT; browserVault(vaultName?: string): FlashBrowserVault; auditStream( collectionName: string, options?: Record, ): FlashAuditStream; events(): FlashEventHub; use(plugin: FlashPlugin): FlashPluginHost; lifecycle( collectionName: string, options?: FlashLifecycleOptions, ): FlashLifecycle; maintenance(options?: FlashMaintenanceOptions): FlashMaintenance; pipeline(): FlashPipeline; eventLog( collectionName: string, options?: { timeField?: string }, ): FlashEventLog; counter(name: string, options?: { namespace?: string }): FlashCounter; queue(collectionName: string, options?: { statusField?: string }): FlashQueue; health(): Promise>; snapshot(): FlashSnapshot; listCollections(): Promise; encryptDocument(doc: Record): EncryptedDocument; encryptToBuffer(doc: Record): Buffer; decryptDocument( encryptedRecord: EncryptedDocument | Buffer, ): Record; decryptFromBuffer(buf: Buffer): Record; decryptFieldsFromBuffer( buf: Buffer, fields: string[], ): Record; buildQueryEnvelope(query?: Record): QueryEnvelope; close(): Promise; } // ============================================================================ // Encrypted Document & Query Envelope (internal types exposed for advanced use) // ============================================================================ export interface EncryptedDocument { _id: string; _enc: Record; _blind?: BlindPayload; _homo?: Record; _plain?: Record; } export interface QueryEnvelope { _id?: string; $exact?: Record; $ngrams?: Record; $range?: Record; $plain?: Record; $ids?: string[]; $secondary?: Record; } // ============================================================================ // Core: FlashCollection (Low-Level) // ============================================================================ export class FlashCollection { readonly name: string; readonly storageDir: string; readonly inMemory: boolean; readonly disableMerkle: boolean; readonly compressionLevel: number; readonly memtable: FlashMemTable; readonly sstables: FlashSSTable[]; readonly arc: FlashArc; readonly wal: FlashArc; readonly indexManager: FlashIndexManager; readonly docOrder: string[]; isReady: boolean; init(): Promise; insertOne( docOrBuf: Record | Buffer, options?: { skipOplog?: boolean }, ): Promise; insertMany( docs: Array | Buffer>, options?: { skipOplog?: boolean }, ): Promise; find( queryEnvelope?: QueryEnvelope, options?: QueryOptions, ): Promise; findOne(queryEnvelope?: QueryEnvelope): Promise; deleteOne(queryEnvelope?: QueryEnvelope): Promise; flush(): Promise; compact(): Promise; count(): Promise; getMerkleRoot(): string; getMerkleProof( docId: string, ): { index: number; proof: string[]; root: string } | null; getMerkleProofAsync( docId: string, ): Promise<{ index: number; proof: string[]; root: string } | null>; verifyRecordIntegrity(docId: string): Promise; verifyRecordIntegrityAsync(docId: string): Promise; applyRawInsert( docId: string, binaryBuf: Buffer, blindPayload?: Record | null, options?: { skipOplog?: boolean }, ): Promise; _getRawDoc(docId: string): Promise; } // ============================================================================ // Core: FlashDatabase // ============================================================================ export class FlashDatabase { readonly dbName: string; readonly storagePath: string; readonly inMemory: boolean; readonly engineOptions: FlashEngineOptions; readonly collections: Map; constructor( name?: string, options?: { storagePath?: string; inMemory?: boolean; engineOptions?: FlashEngineOptions; }, ); collection(name: string): FlashCollection; listCollections(): string[]; dropCollection(name: string): Promise; close(): Promise; } // ============================================================================ // Server: FlashServer // ============================================================================ export interface FlashServerOptions { port?: number; host?: string; storagePath?: string; authKey?: string; dbName?: string; engineOptions?: FlashEngineOptions; } export class FlashServer { static start(options?: FlashServerOptions): import("node:http").Server; } // ============================================================================ // Server: FlashMetrics // ============================================================================ export type MetricOp = "insert" | "insertMany" | "find" | "update" | "delete" | "flush" | "compact"; export class FlashMetrics { constructor(options?: { latencyBuckets?: number[] }); recordOp(op: MetricOp, durationMs: number): void; recordError(op: MetricOp): void; setGauge(name: string, value: number): void; toPrometheus(): string; } // ============================================================================ // Logger // ============================================================================ export const logger: FlashLoggerInterface; // ============================================================================ // Vector: FlashVectorIndex & FlashHNSWIndex // ============================================================================ export interface HNSWOptions { M?: number; efConstruction?: number; efSearch?: number; mL?: number; metric?: "cosine" | "euclidean" | "dot"; } export class FlashHNSWIndex { constructor(options?: HNSWOptions); insert(id: string, vector: number[] | Float32Array): void; search( queryVector: number[] | Float32Array, k?: number, options?: { efSearch?: number; filter?: Set }, ): VectorSearchResult[]; size(): number; } export class FlashVectorIndex { constructor(options?: { engine?: "exact" | "hnsw"; hnswOptions?: HNSWOptions; }); set(docId: string, vector: number[] | Float32Array): void; delete(docId: string): void; search( queryVector: number[] | Float32Array, topK?: number, candidateFilter?: Set, ): VectorSearchResult[]; } // ============================================================================ // Vector: FlashQuantizer // ============================================================================ export interface SQ8Quantized { data: Uint8Array; min: number; max: number; scale: number; dimensions: number; format: "sq8"; } export interface BinaryQuantized { data: Uint32Array; dimensions: number; format: "binary1bit"; } export interface MemorySavingsEstimate { vectorCount: number; dimensions: number; rawFloat32MB: string; sq8MB: string; binary1BitMB: string; sq8Savings: string; binary1BitSavings: string; } export class FlashQuantizer { static popcount32(n: number): number; static quantizeSQ8(vector: Float32Array | number[]): SQ8Quantized; static dequantizeSQ8( quantizedData: Uint8Array, min: number, scale: number, ): Float32Array; static asymmetricCosineSQ8( queryVec: Float32Array | number[], targetSQ8Data: Uint8Array, min: number, scale: number, ): number; static quantizeBinary(vector: Float32Array | number[]): BinaryQuantized; static hammingDistance(binA: Uint32Array, binB: Uint32Array): number; static hammingSimilarity( binA: Uint32Array, binB: Uint32Array, totalDimensions?: number, ): number; static cosineApproxFromBinary( binA: Uint32Array, binB: Uint32Array, totalDimensions?: number, ): number; static estimateMemorySavings( count: number, dimensions: number, ): MemorySavingsEstimate; } // ============================================================================ // AI: FlashSemanticCache // ============================================================================ export interface CacheHit { hit: true; response: string; similarity: number; prompt: string; } export interface CacheStats { size: number; hits: number; misses: number; hitRatio: number; } export class FlashSemanticCache { constructor(options?: { similarityThreshold?: number; maxEntries?: number; ttlMs?: number; }); get( queryEmbedding: number[] | Float32Array, promptText?: string, ): CacheHit | null; set( prompt: string, embedding: number[] | Float32Array, response: string, ): void; clear(): void; getStats(): CacheStats; } // ============================================================================ // AI: FlashContextOptimizer // ============================================================================ export interface RRFInput { id?: string; docId?: string; text?: string; metadata?: Record; score?: number; } export interface RRFOutput { id: string; text: string; metadata: Record; rrfScore: number; originalScores: Record; } export interface TokenBudgetResult { packedContext: string; documentsUsed: Array>; totalTokens: number; savedTokensEstimate: number; } export class FlashContextOptimizer { static estimateTokens(text: string): number; static reciprocalRankFusion( rankedLists: RRFInput[][], options?: { k?: number; weights?: number[] }, ): RRFOutput[]; static deduplicate( docs: T[], similarityThreshold?: number, ): T[]; static optimizeTokenBudget( documents: RRFOutput[], options?: { maxTokens?: number; preserveTopK?: number }, ): TokenBudgetResult; } // ============================================================================ // AI: FlashNLQueryEngine & FlashLLMAdapter & FlashAIDatabase // ============================================================================ export interface NLQueryResult { filter: Record; sort?: Record; limit?: number; } export class FlashNLQueryEngine { static parse(prompt: string): NLQueryResult; } export interface ToolDefinition { name: string; description: string; parameters: Record; handler: (args: Record) => Promise>; } export class FlashLLMAdapter { registerTool(tool: ToolDefinition): void; executeToolCall( toolName: string, args: Record, ): Promise>; } export class FlashAIDatabase { constructor(client: FlashClient, options?: { model?: string }); ask(prompt: string): Promise; semanticSearch( collection: string, query: string, topK?: number, ): Promise[]>; } // ============================================================================ // Tools: FlashETL, FlashFaker, FlashMigrator // ============================================================================ export class FlashETL { static exportToNDJSON( collection: FlashCollection, destFilePath: string, ): Promise<{ exportedCount: number; filePath: string }>; static importFromNDJSON( collection: FlashCollection, sourceFilePath: string, batchSize?: number, ): Promise<{ importedCount: number }>; static exportToCSV( collection: FlashCollection, destFilePath: string, fields?: string[], ): Promise<{ exportedCount: number }>; } export class FlashFaker { static mockUser(id?: number): Record; static generateBatch(count?: number): Array>; } export class FlashMigrator { constructor(db: FlashDatabase); register( version: number, name: string, up: (db: FlashDatabase) => Promise, down?: (db: FlashDatabase) => Promise, ): void; up(): Promise>; rollback(): Promise>; } // ============================================================================ // Tools: FlashSIMD // ============================================================================ export class FlashSIMD { static cosineSimilarity(a: Float32Array, b: Float32Array): number; static euclideanDistance(a: Float32Array, b: Float32Array): number; } // ============================================================================ // Tools: FlashSearchEngine (BM25) // ============================================================================ export interface SearchHit { docId: string; score: number; } export class FlashSearchEngine { constructor(options?: { k1?: number; b?: number }); indexDocument(docId: string, text: string): void; search(query: string, limit?: number): SearchHit[]; } // ============================================================================ // Cluster: FlashCluster & FlashDistributedTxCoordinator // ============================================================================ export interface ShardInfo { shardId: string; db: FlashDatabase; } export interface TxCommitResult { success: boolean; state: string; shards: string[]; } export class FlashCluster { constructor(options?: { virtualNodes?: number }); addShard(shardId: string, dbInstance: FlashDatabase): void; removeShard(shardId: string): void; getShardForKey(docKey: string): ShardInfo; listShards(): string[]; getTxCoordinator(): FlashDistributedTxCoordinator; } export class FlashDistributedTxCoordinator { constructor(cluster: FlashCluster); beginTransaction(customTxId?: string): string; stageOperation( dtxId: string, collection: string, docKey: string, type: "insert" | "update" | "delete", payload?: Record, ): void; commitTransaction(dtxId: string): Promise; abortTransaction(dtxId: string): Promise; } // ============================================================================ // Consensus: FlashRaft // ============================================================================ export interface ElectionResult { term: number; votes: number; elected: boolean; } export interface ReplicateResult { logIndex: number; committed: boolean; } export interface AppendEntriesResult { success: boolean; term: number; } export class FlashRaft { constructor( nodeId: string, peerIds?: string[], options?: { electionTimeoutMs?: number; heartbeatIntervalMs?: number }, ); startElection(): ElectionResult; replicate(command: Record): ReplicateResult; handleAppendEntries( leaderId: string, term: number, entries?: Array>[], leaderCommit?: number, ): AppendEntriesResult; } // ============================================================================ // Protocol: FlashGRPCServer & FlashGraphQL // ============================================================================ export class FlashGRPCServer { constructor(db: FlashDatabase, options?: { port?: number }); start(): Promise; stop(): void; } export interface GraphQLResult { data: Record; errors?: string[]; } export class FlashGraphQL { constructor(db: FlashDatabase); execute(queryStr: string): Promise; } // ============================================================================ // Storage: FlashBrowserAdapter & FlashBlobStore // ============================================================================ export class FlashBrowserAdapter { constructor( dbName?: string, options?: { driver?: "indexeddb" | "memory" | "opfs" }, ); set(collection: string, key: string, buffer: Buffer): Promise; get(collection: string, key: string): Promise; delete(collection: string, key: string): Promise; listKeys(collection: string): Promise; } export class FlashBlobStore { constructor(options?: { chunkSizeBytes?: number }); writeBlob( fileId: string, filename: string, buffer: Buffer, mimeType?: string, ): { fileId: string; totalChunks: number; sha256: string }; readBlob(fileId: string): Buffer | null; deleteBlob(fileId: string): boolean; } // ============================================================================ // Graph: FlashGraph // ============================================================================ export interface GraphNode { id: string; label: string; properties: Record; } export interface GraphEdge { fromId: string; toId: string; label: string; weight: number; properties: Record; } export interface NeighborResult { node: GraphNode; edge: GraphEdge; } export interface PathResult { path: string[]; distance: number; } export class FlashGraph { addNode( id: string, label: string, properties?: Record, ): GraphNode; addEdge( fromId: string, toId: string, label: string, weight?: number, properties?: Record, ): void; getNeighbors(nodeId: string, edgeLabel?: string): NeighborResult[]; findShortestPath(startId: string, endId: string): PathResult | null; } // ============================================================================ // Security: FlashAuditVault, FlashDataMasker, FlashRBAC // ============================================================================ export interface AuditEntry { actor: string; action: string; target: string; metadata: Record; timestamp: number; chainHash: string; } export class FlashAuditVault { constructor(vaultSecret?: string); log( actor: string, action: string, target: string, metadata?: Record, ): AuditEntry; verifyChain(): { valid: boolean; totalEntries: number; brokenAt?: number }; } export class FlashDataMasker { static maskEmail(email: string): string; static maskCard(cardNumber: string): string; static maskDocument( doc: Record, rules?: Record, ): Record; } export class FlashRBAC { createRole(roleName: string, permissions: string[]): void; assignRole(userId: string, roleName: string): void; can( userId: string, collection: string, action: "read" | "write" | "delete" | "admin", ): boolean; } // ============================================================================ // Spatial: FlashSpatialRTree & FlashSpatialPlugin // ============================================================================ export interface SpatialPoint { id: string; distanceKm: number; point: { lat: number; lon: number }; data: Record; } export class FlashSpatialRTree { insertPoint( id: string, lat: number, lon: number, data?: Record, ): void; searchBoundingBox( minLat: number, minLon: number, maxLat: number, maxLon: number, ): Array<{ id: string; lat: number; lon: number; data: Record; }>; searchNearest( lat: number, lon: number, k?: number, maxDistanceKm?: number, ): SpatialPoint[]; } export class FlashSpatialPlugin { static filterNear( docs: Record[], field: string, nearSpec: Record, ): Record[]; } // ============================================================================ // Plugins: FlashTimeSeriesPlugin, FlashTextSearchPlugin, FlashCRDTSync // ============================================================================ export interface TimeSeriesBucket { bucketStart: number; count: number; min: number; max: number; avg: number; sum: number; } export class FlashTimeSeriesPlugin { static bucket( docs: Record[], timeField: string, interval: number, aggregations: Record, ): TimeSeriesBucket[]; } export class FlashTimeSeriesRollup { static rollup( dataPoints?: Array<{ timestamp: number; value: number }>, windowSizeMs?: number, ): TimeSeriesBucket[]; } export class FlashTextSearchPlugin { indexDocument(docId: string, text: string): void; search(query: string, limit?: number): SearchHit[]; } export class FlashCRDTSync { merge( local: Record, remote: Record, ): Record; } // ============================================================================ // Scaling: FlashConnectionPool, FlashRateLimiter, FlashDistributedLock, FlashCDC, FlashFederation // ============================================================================ export class FlashConnectionPool { constructor( serverEndpoints?: string[], options?: { maxConnectionsPerHost?: number }, ); acquire(): string; release(endpoint: string): void; setHealthy(endpoint: string, isHealthy: boolean): void; } export class FlashRateLimiter { constructor(options?: { capacity?: number; refillRatePerSec?: number }); consume( clientId: string, cost?: number, ): { allowed: boolean; remainingTokens: number; retryAfterMs: number }; reset(clientId: string): void; } export interface LockResult { acquired: boolean; leaseToken?: string; expiresAt?: number; } export class FlashDistributedLock { acquire(resourceKey: string, ownerId: string, ttlMs?: number): LockResult; release(resourceKey: string, leaseToken: string): boolean; } export interface CDCEvent { id: string; collection: string; op: "INSERT" | "UPDATE" | "DELETE"; docId: string; payload: Record; timestamp: number; } export class FlashCDC { recordChange( collection: string, op: "INSERT" | "UPDATE" | "DELETE", docId: string, payload?: Record, ): CDCEvent; pollPending(batchSize?: number): CDCEvent[]; ackEvents(eventIds: string[]): void; subscribe(callback: (event: CDCEvent) => void): () => void; } export class FlashFederation { registerMember(name: string, dbInstance: FlashDatabase): void; federatedFind( collectionName: string, queryEnvelope?: QueryEnvelope, options?: QueryOptions, ): Promise>>; } // ============================================================================ // Cost Optimizer // ============================================================================ export interface QueryPlan { plan: string; field?: string; estimatedCost: number; } export class FlashCostOptimizer { static planQuery( query?: Record, availableIndexes?: Set, totalDocuments?: number, ): QueryPlan; } // ============================================================================ // Time Travel // ============================================================================ export class FlashTimeTravel { constructor(mvccInstance: FlashMVCC); recordCommit(commitTs: number, timestamp?: number): void; queryAsOf(docId: string, asOf: number | Date): Record | null; } // ============================================================================ // SQL // ============================================================================ export class FlashSQL { static execute( db: FlashDatabase, sqlQuery: string, ): Promise>>; static parse(sql: string): Record; } // ============================================================================ // Real-Time: FlashWebSocket & FlashWebSocketServer // ============================================================================ export interface WebSocketOptions { path?: string; heartbeatInterval?: number; maxPayload?: number; } export class FlashWebSocket { readonly id: string; readonly rooms: Set; readonly connected: boolean; send(data: string | Record): void; sendBinary(data: Buffer): void; join(room: string): this; leave(room: string): this; ping(): void; close(code?: number, reason?: string): void; onmessage?: (data: Record) => void; onclose?: () => void; } export class FlashWebSocketServer { readonly size: number; constructor( httpServer: import("node:http").Server, options?: WebSocketOptions, ); on(event: "connection", listener: (ws: FlashWebSocket) => void): this; on(event: "disconnect", listener: (ws: FlashWebSocket) => void): this; on( event: "message", listener: (ws: FlashWebSocket, data: Record) => void, ): this; on(event: "join", listener: (ws: FlashWebSocket, room: string) => void): this; on( event: "leave", listener: (ws: FlashWebSocket, room: string) => void, ): this; joinRoom(ws: FlashWebSocket, room: string): void; leaveRoom(ws: FlashWebSocket, room: string): void; to( room: string, data: string | Record, exclude?: FlashWebSocket, ): void; broadcast( data: string | Record, exclude?: FlashWebSocket, ): void; getRoomMembers(room: string): Set; close(): void; } // ============================================================================ // Real-Time: FlashPresence // ============================================================================ export interface PresenceOptions { heartbeatTimeout?: number; cleanupInterval?: number; } export interface PresenceInfo { userId: string; status: string; lastSeen: number; connections: number; meta: Record; } export class FlashPresence { constructor(options?: PresenceOptions); on( event: "online", listener: (userId: string, info: PresenceInfo) => void, ): this; on( event: "offline", listener: (userId: string, info: PresenceInfo) => void, ): this; on( event: "status", listener: (userId: string, status: string, info: PresenceInfo) => void, ): this; track(userId: string, meta?: Record): PresenceInfo; heartbeat(userId: string): void; disconnect(userId: string): void; setStatus(userId: string, status: string): void; isOnline(userId: string): boolean; getStatus(userId: string): string; getOnlineUsers(): PresenceInfo[]; getOnlineCount(): number; get(userId: string): PresenceInfo | null; getAll(): PresenceInfo[]; destroy(): void; } // ============================================================================ // Cache: FlashLRUCache // ============================================================================ export interface LRUCacheOptions { maxSize?: number; defaultTTL?: number; cleanupInterval?: number; } export interface LRUCacheStats { hits: number; misses: number; evictions: number; sets: number; deletes: number; size: number; maxSize: number; } export class FlashLRUCache { constructor(options?: LRUCacheOptions); set(key: string, value: unknown, ttl?: number): void; get(key: string): unknown; has(key: string): boolean; delete(key: string): boolean; peek(key: string): unknown; keys(): string[]; values(): unknown[]; entries(): Array<[string, unknown]>; clear(): void; readonly size: number; readonly stats: LRUCacheStats; destroy(): void; } // ============================================================================ // Real-Time: FlashEnhancedPubSub // ============================================================================ export interface EnhancedPubSubOptions { maxHistory?: number; maxRetries?: number; } export interface PubSubMessage { id: string; topic: string; payload: unknown; timestamp: number; ttl: number; retryCount: number; status: string; } export type AckFn = (ack: boolean) => void; export class FlashEnhancedPubSub { constructor(options?: EnhancedPubSubOptions); on(event: "publish", listener: (msg: PubSubMessage) => void): this; on(event: "dead-letter", listener: (msg: PubSubMessage) => void): this; publish( topic: string, payload: unknown, options?: { id?: string; ttl?: number }, ): string; subscribe( topic: string, subscriberId: string, callback: (msg: PubSubMessage, ack: AckFn) => void, ): this; subscribeWildcard( pattern: string, subscriberId: string, callback: (msg: PubSubMessage, ack: AckFn) => void, ): this; unsubscribe(topic: string, subscriberId: string): this; unsubscribeAll(subscriberId: string): void; getHistory(topic: string, limit?: number): PubSubMessage[]; getDeadLetter(): PubSubMessage[]; retryDeadLetter(msgId: string): boolean; clearHistory(topic?: string): void; getTopics(): string[]; getSubscriberCount(topic: string): number; destroy(): void; } // ============================================================================ // Performance profiles & compact storage (v1.3.2+) // ============================================================================ export const TURBO_MEMTABLE_THRESHOLD: number; export function resolveEngineOptions( userOptions?: FlashEngineOptions, ): FlashEngineOptions; export class FlashStorageCompact { static flattenRecord(record: EncryptedDocument): Record; static expandRecord(flat: Record): EncryptedDocument; } export class MemoryArc { open(): Promise; sync(): Promise; append(opCode: number, key: string, data: Buffer): Promise; appendBatch( operations: Array<{ opCode: number; key: string; data: Buffer }>, ): Promise; truncate(): Promise; close(): Promise; } export class MemoryOplog { open(): Promise; append(): Promise; appendBatch(entries?: unknown[]): Promise; close(): Promise; } export class MemorySSTable { readonly level: number; readonly filePath: string; readonly indexMap: Map; static fromEntries(entries: MemTableEntry[], level?: number): MemorySSTable; load(): Promise; close(): Promise; get(key: string): Promise; }