@dikolab/kbdb 0.4.0 → 0.4.1
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.
- package/README.md +13 -5
- package/dist/{chunk-BJPSPNGX.mjs → chunk-BJXEVALU.mjs} +115 -1
- package/dist/chunk-BJXEVALU.mjs.map +7 -0
- package/dist/cli.cjs +462 -79
- package/dist/cli.cjs.map +4 -4
- package/dist/cli.mjs +356 -79
- package/dist/cli.mjs.map +4 -4
- package/dist/kbdb-worker.cjs +413 -53
- package/dist/kbdb-worker.cjs.map +4 -4
- package/dist/mod.cjs +230 -54
- package/dist/mod.cjs.map +4 -4
- package/dist/mod.mjs +229 -53
- package/dist/mod.mjs.map +4 -4
- package/dist/src/shared/cli/typings/cli-options.interface.d.ts +5 -0
- package/dist/src/shared/embedding/classes/tfidf-embedding-provider.class.d.ts +28 -0
- package/dist/src/shared/embedding/constants/tfidf-defaults.constant.d.ts +4 -0
- package/dist/src/shared/embedding/functions/create-embedding-provider.function.d.ts +5 -2
- package/dist/src/shared/embedding/index.d.ts +2 -0
- package/dist/src/shared/log/constants/log-colors.constant.d.ts +5 -0
- package/dist/src/shared/log/constants/log-defaults.constant.d.ts +3 -0
- package/dist/src/shared/log/constants/log-icons.constant.d.ts +3 -0
- package/dist/src/shared/log/functions/configure-log.function.d.ts +12 -0
- package/dist/src/shared/log/functions/log.function.d.ts +28 -0
- package/dist/src/shared/log/functions/parse-log-level.function.d.ts +10 -0
- package/dist/src/shared/log/functions/resolve-log-level.function.d.ts +12 -0
- package/dist/src/shared/log/functions/write-stderr.function.d.ts +10 -0
- package/dist/src/shared/log/index.d.ts +10 -0
- package/dist/src/shared/log/typings/log-config.interface.d.ts +7 -0
- package/dist/src/shared/log/typings/log-level.type.d.ts +7 -0
- package/dist/src/shared/log/typings/log-output.interface.d.ts +4 -0
- package/dist/src/shared/version/constants/version.constant.d.ts +1 -1
- package/dist/src/shared/worker-client/classes/worker-client.class.d.ts +7 -0
- package/dist/src/shared/worker-client/functions/retry-on-timeout.function.d.ts +1 -0
- package/dist/src/shared/worker-daemon/classes/worker-daemon.class.d.ts +1 -0
- package/dist/src/shared/worker-daemon/functions/run-worker.function.d.ts +6 -1
- package/dist/src/shared/worker-daemon/typings/wasm-modules.interface.d.ts +5 -0
- package/dist/wasm/default-embedding/kbdb_default_embedding.d.ts +55 -0
- package/dist/wasm/default-embedding/kbdb_default_embedding.js +156 -0
- package/dist/wasm/default-embedding/kbdb_default_embedding_bg.wasm +0 -0
- package/dist/wasm/default-embedding/kbdb_default_embedding_bg.wasm.d.ts +12 -0
- package/dist/wasm/default-embedding/package.json +13 -0
- package/dist/wasm/fs-database/kbdb_fs_database_bg.wasm +0 -0
- package/dist/wasm/fs-migration/kbdb_fs_migration.d.ts +38 -0
- package/dist/wasm/fs-migration/kbdb_fs_migration.js +130 -0
- package/dist/wasm/fs-migration/kbdb_fs_migration_bg.wasm +0 -0
- package/dist/wasm/fs-migration/kbdb_fs_migration_bg.wasm.d.ts +9 -0
- package/dist/wasm/fs-migration/package.json +13 -0
- package/dist/wasm/kb-worker/kbdb_worker_bg.wasm +0 -0
- package/dist/wasm/query-parser/kbdb_query_parser_bg.wasm +0 -0
- package/dist/worker.mjs +306 -54
- package/dist/worker.mjs.map +4 -4
- package/docs/details/agent-tooling.md +10 -0
- package/docs/details/cli.md +29 -13
- package/docs/details/knowledge-base.md +15 -8
- package/docs/details/mcp-server.md +16 -1
- package/docs/details/search-and-ranking.md +6 -2
- package/docs/goals/cli.md +33 -4
- package/docs/goals/content-parser.md +1 -1
- package/docs/goals/hybrid-search.md +71 -42
- package/docs/goals/mcp.md +3 -1
- package/docs/goals/overview.md +1 -1
- package/docs/goals/query-parser.md +1 -1
- package/docs/goals/semantic-dedup.md +7 -3
- package/docs/goals/worker-daemon.md +31 -20
- package/docs/modules/overview.md +43 -22
- package/docs/modules/rust/embedding/module.md +91 -0
- package/docs/modules/rust/overview.md +56 -21
- package/docs/modules/rust/query-parser/functions/module.md +7 -5
- package/docs/modules/rust/query-parser/functions/pipeline.md +6 -138
- package/docs/modules/rust/query-parser/module.md +16 -22
- package/docs/modules/rust/query-parser/types/module.md +5 -4
- package/docs/modules/rust/query-parser/types/token.md +5 -1
- package/docs/modules/rust/shared/content-parser/functions.md +1 -1
- package/docs/modules/rust/shared/memory/module.md +1 -1
- package/docs/modules/rust/shared/module.md +33 -5
- package/docs/modules/rust/shared/pipeline/functions.md +141 -0
- package/docs/modules/rust/shared/pipeline/module.md +62 -0
- package/docs/modules/rust/shared/pipeline/types.md +43 -0
- package/docs/modules/rust/shared/section/module.md +1 -1
- package/docs/modules/rust/shared/section/types.md +1 -1
- package/docs/modules/typescript/cli.md +4 -2
- package/docs/modules/typescript/kbdb-worker.md +20 -5
- package/docs/modules/typescript/overview.md +28 -6
- package/docs/modules/typescript/shared/cli/functions.md +15 -4
- package/docs/modules/typescript/shared/cli/typings.md +21 -0
- package/docs/modules/typescript/shared/embedding/functions.md +30 -3
- package/docs/modules/typescript/shared/embedding/module.md +10 -4
- package/docs/modules/typescript/shared/embedding/typings.md +7 -5
- package/docs/modules/typescript/shared/log/constants.md +82 -0
- package/docs/modules/typescript/shared/log/functions.md +131 -0
- package/docs/modules/typescript/shared/log/module.md +153 -0
- package/docs/modules/typescript/shared/log/typings.md +82 -0
- package/docs/modules/typescript/shared/module.md +22 -6
- package/docs/modules/typescript/shared/worker-daemon/functions.md +19 -6
- package/docs/modules/typescript/shared/worker-daemon/module.md +5 -2
- package/docs/modules/typescript/shared/worker-daemon/typings.md +13 -7
- package/docs/release-notes/0.4.1.md +149 -0
- package/package.json +2 -2
- package/dist/chunk-BJPSPNGX.mjs.map +0 -7
package/dist/mod.cjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../mod.ts", "../src/shared/version/constants/version.constant.ts", "../src/shared/worker-client/classes/worker-client.class.ts", "../src/shared/worker-client/functions/
|
|
4
|
-
"sourcesContent": ["/**\n * @module\n *\n * File-based knowledge base database for AI agents.\n * Provides a programmatic API for indexing documents,\n * searching with ranked results, and recalling section\n * context at progressive depths.\n *\n * @example\n * ```ts\n * import { createWorkerClient } from '@dikolab/kbdb';\n *\n * const client = await createWorkerClient({\n * contextPath: '/path/to/.kbdb',\n * });\n *\n * const results = await client.search({\n * query: 'authentication',\n * limit: 10,\n * });\n *\n * console.log(results.items);\n * client.disconnect();\n * ```\n */\n\n/** Semantic version string matching `package.json`. */\nexport { version } from './src/shared/mod.ts';\n\n/** Creates a connected worker client for the given database. */\nexport { createWorkerClient } from './src/shared/worker-client/index.ts';\n\n/** Persistent client wrapping JSON-RPC calls to the daemon. */\nexport { WorkerClient } from './src/shared/worker-client/index.ts';\n\n/** Resolves a parent directory to the `.kbdb` path inside it. */\nexport { resolveDbPath } from './src/shared/worker-client/index.ts';\n\n/** Derives the 16-char hex context ID from an absolute path. */\nexport { computeContextId } from './src/shared/worker-client/index.ts';\n\n/** Returns a cached client or creates a new one for the given path. */\nexport { getOrCreateClient } from './src/shared/worker-client/index.ts';\n\n/** Options accepted by {@linkcode createWorkerClient}. */\nexport type { WorkerClientOptions } from './src/shared/worker-client/index.ts';\n\n/** Parameters for a search query. */\nexport type { SearchParams } from './src/shared/worker-client/index.ts';\n\n/** A single ranked result returned by search. */\nexport type { SearchResult } from './src/shared/worker-client/index.ts';\n\n/** Raw section record stored on disk. */\nexport type { Section } from './src/shared/worker-client/index.ts';\n\n/** Parameters for adding a new section. */\nexport type { AddSectionParams } from './src/shared/worker-client/index.ts';\n\n/** Database status snapshot returned by `client.status()`. */\nexport type { StatusResult } from './src/shared/worker-client/index.ts';\n", "/** Current package version, kept in sync with package.json. */\nexport const VERSION = '0.4.0';\n", "import { connect } from 'node:net';\nimport type { Socket } from 'node:net';\nimport type { SearchParams } from '../typings/search-params.model.ts';\nimport type { PagedSearchResult } from '../typings/search-result.model.ts';\nimport type {\n AddSectionParams,\n Section,\n} from '../typings/section.model.ts';\nimport type { StatusResult } from '../typings/status-result.model.ts';\nimport type { AddSectionResult } from '../typings/add-section-result.model.ts';\nimport type { RemoveSectionResult } from '../typings/remove-section-result.model.ts';\nimport type { ContentResult } from '../typings/content-result.model.ts';\nimport type { IntegrityCheckResult } from '../typings/integrity-check-result.model.ts';\nimport type { GcResult } from '../typings/gc-result.model.ts';\nimport type { RebuildResult } from '../typings/rebuild-result.model.ts';\nimport type { MigrateResult } from '../typings/migrate-result.model.ts';\nimport type { VersionStatus } from '../typings/version-status.model.ts';\nimport type { SectionRecord } from '../../wasm-codec/functions/decode-section-records.function.ts';\nimport type { DocumentManifest } from '../../wasm-codec/functions/decode-document-manifest.function.ts';\nimport type {\n RecallParams,\n RecallResult,\n} from '../typings/recall-result.model.ts';\nimport type { ExportResult } from '../typings/export-result.model.ts';\nimport type { ImportResult } from '../typings/import-result.model.ts';\n\n/** Pending JSON-RPC call awaiting a response from the daemon. */\ninterface PendingCall {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer?: ReturnType<typeof setTimeout>;\n}\n\n/** Shape of a JSON-RPC 2.0 error object from the daemon. */\ninterface JsonRpcError {\n readonly code: number;\n readonly message: string;\n}\n\n/** Shape of a JSON-RPC 2.0 response from the daemon. */\ninterface JsonRpcResponse {\n readonly id: number;\n readonly result?: unknown;\n readonly error?: JsonRpcError;\n}\n\n/**\n * IPC client that communicates with the worker daemon over a Unix\n * domain socket (or Windows named pipe) using JSON-RPC 2.0 with\n * newline-delimited message framing.\n *\n * Call `connect()` before any other method and `disconnect()` when\n * done to release the underlying socket.\n */\nexport class WorkerClient {\n /** Underlying socket; `null` when not connected. */\n private socket: Socket | null = null;\n\n /** Monotonically increasing request ID counter. */\n private nextId = 1;\n\n /** Map of outstanding request IDs to their resolve/reject pairs. */\n private readonly pending = new Map<number, PendingCall>();\n\n /** Partial line buffer for split TCP/IPC frames. */\n private buffer = '';\n\n /**\n * @param socketPath - absolute path to the daemon's IPC socket\n * (or Windows named pipe path)\n * @param contextId - 16-character context identifier sent as\n * `ctx` in every JSON-RPC request\n * @param requestTimeoutMs - per-request timeout in ms\n * (0 or undefined disables the timeout)\n */\n constructor(\n private readonly socketPath: string,\n private readonly contextId: string,\n private readonly requestTimeoutMs?: number,\n ) {}\n\n /** Whether the underlying socket is connected. */\n get isConnected(): boolean {\n return this.socket !== null;\n }\n\n /**\n * Establishes the IPC connection to the worker daemon.\n *\n * Retries up to 5 times with exponential backoff on\n * transient errors (`ENOENT`, `ECONNREFUSED`).\n *\n * @throws {Error} if the connection cannot be established\n */\n async connect(): Promise<void> {\n const maxRetries = 5;\n let delay = 50;\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n await this.tryConnect();\n return;\n } catch (err: unknown) {\n const code = (err as NodeJS.ErrnoException).code;\n const retriable =\n code === 'ENOENT' || code === 'ECONNREFUSED';\n if (!retriable || attempt === maxRetries) {\n throw err;\n }\n await new Promise<void>((r) => setTimeout(r, delay));\n delay = Math.min(delay * 2, 1000);\n }\n }\n }\n\n /** Destroys the IPC socket and clears the connection state. */\n disconnect(): void {\n if (this.socket) {\n this.socket.destroy();\n this.socket = null;\n }\n }\n\n /**\n * Single connection attempt with keepalive and\n * post-connect failure handlers.\n */\n private async tryConnect(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const sock = connect(this.socketPath, () => {\n sock.removeListener('error', reject);\n sock.setKeepAlive(true, 30_000);\n sock.on('error', (err: Error) => {\n this.handleSocketFailure(err);\n });\n sock.on('close', () => {\n if (this.pending.size > 0) {\n this.handleSocketFailure(\n new Error('connection closed'),\n );\n }\n this.socket = null;\n });\n this.socket = sock;\n resolve();\n });\n sock.on('error', reject);\n sock.on('data', (chunk: Buffer) => {\n this.handleData(chunk.toString());\n });\n });\n }\n\n /**\n * Rejects all pending calls and marks the client as\n * disconnected.\n */\n private handleSocketFailure(err: Error): void {\n const sock = this.socket;\n this.socket = null;\n for (const [id, call] of this.pending) {\n this.pending.delete(id);\n if (call.timer) clearTimeout(call.timer);\n call.reject(err);\n }\n if (sock) sock.destroy();\n }\n\n /**\n * Searches the knowledge base.\n *\n * @param params - query parameters including the search string\n * @returns paginated search results with metadata\n */\n async search(params: SearchParams): Promise<PagedSearchResult> {\n return this.call('search', {\n ...params,\n algo: params.algo,\n }) as Promise<PagedSearchResult>;\n }\n\n /**\n * Retrieves full content and context for one or more sections by\n * their knowledge-base identifiers.\n *\n * @param params - section identifier(s) and optional expansion depth\n * @returns a single `RecallResult` when `kbid` is provided without\n * `kbids`, or a `RecallResult[]` when `kbids` is provided\n */\n async recall(\n params: RecallParams,\n ): Promise<RecallResult | RecallResult[]> {\n return this.call('recall', params) as Promise<\n RecallResult | RecallResult[]\n >;\n }\n\n /**\n * Adds a new section to the knowledge base.\n *\n * @param params - section content and metadata\n * @returns the result including the assigned knowledge-base\n * identifier and indexing statistics\n */\n async addSection(\n params: AddSectionParams,\n ): Promise<AddSectionResult> {\n return this.call(\n 'addSection',\n params,\n ) as Promise<AddSectionResult>;\n }\n\n /**\n * Replaces an existing section's content and metadata.\n *\n * @param kbid - identifier of the section to update\n * @param params - new content and metadata\n * @returns the knowledge-base identifier of the updated section\n */\n async updateSection(\n kbid: string,\n params: AddSectionParams,\n ): Promise<string> {\n return this.call('updateSection', {\n kbid,\n ...params,\n }) as Promise<string>;\n }\n\n /**\n * Removes a section from the knowledge base.\n *\n * @param kbid - identifier of the section to remove\n * @returns removal result with `removed` flag and elapsed time\n */\n async removeSection(kbid: string): Promise<RemoveSectionResult> {\n return this.call('removeSection', {\n kbid,\n }) as Promise<RemoveSectionResult>;\n }\n\n /**\n * Retrieves multiple sections by their identifiers.\n *\n * @param kbids - list of knowledge-base identifiers to fetch\n * @returns sections in the order their IDs were requested\n */\n async readSections(kbids: string[]): Promise<Section[]> {\n return this.call('readSections', {\n kbids,\n }) as Promise<Section[]>;\n }\n\n /**\n * Groups a set of sections under a named document.\n *\n * @param title - human-readable document title\n * @param kbids - identifiers of the sections to group\n * @param docType - application-level document type tag; omit or\n * pass an empty string for untagged documents\n * @returns the assigned document identifier\n */\n async groupSections(\n title: string,\n kbids: string[],\n docType?: string,\n ): Promise<string> {\n const result = (await this.call('groupSections', {\n title,\n kbids,\n docType: docType ?? '',\n })) as { docid: string } | string;\n return typeof result === 'string' ? result : result.docid;\n }\n\n /**\n * Removes the document grouping for the given document.\n *\n * The sections themselves are not deleted; only the grouping\n * record is removed.\n *\n * @param docid - identifier of the document grouping to remove\n */\n async removeGrouping(docid: string): Promise<void> {\n await this.call('removeGrouping', { docid });\n }\n\n /**\n * Retrieves a full document record including its sections.\n *\n * @param docid - identifier of the document to retrieve\n * @returns the document record as returned by the daemon\n */\n async retrieveDocument(docid: string): Promise<unknown> {\n return this.call('retrieveDocument', { docid });\n }\n\n /**\n * Composes a rendered Markdown document from one or more kbid\n * or docid identifiers.\n *\n * @param ids - list of kbid or docid identifiers (may be mixed)\n * @returns composed Markdown result with character count\n */\n async content(ids: string[]): Promise<ContentResult> {\n return this.call('content', { ids }) as Promise<ContentResult>;\n }\n\n /**\n * Runs an integrity check on the knowledge-base database.\n *\n * @returns a report of all issues found; `ok` is `true` when\n * no errors were detected\n */\n async integrityCheck(): Promise<IntegrityCheckResult> {\n return this.call(\n 'integrityCheck',\n {},\n ) as Promise<IntegrityCheckResult>;\n }\n\n /**\n * Removes unreferenced sections from the database.\n *\n * @returns a report of sections removed and bytes freed\n */\n async gc(): Promise<GcResult> {\n return this.call('gc', {}) as Promise<GcResult>;\n }\n\n /**\n * Reconstructs all index files from section files and document\n * manifests on disk. Text and code sections are re-tokenized;\n * image sections are skipped.\n *\n * @returns a report of sections and terms re-indexed\n */\n async rebuildIndexes(): Promise<RebuildResult> {\n return this.call('rebuildIndexes', {}) as Promise<RebuildResult>;\n }\n\n /**\n * Invalidates the in-memory cache entry for a single section.\n *\n * @param kbid - identifier of the section to evict from cache\n */\n async invalidate(kbid: string): Promise<void> {\n await this.call('invalidate', { kbid });\n }\n\n /** Clears all entries from the daemon's in-memory cache. */\n async invalidateAll(): Promise<void> {\n await this.call('invalidateAll', {});\n }\n\n /**\n * Retrieves diagnostic status information from the daemon.\n *\n * @returns current initialization state and cache statistics\n */\n async status(): Promise<StatusResult> {\n return this.call('status', {}) as Promise<StatusResult>;\n }\n\n /**\n * Returns database metadata and status from the daemon,\n * including document count, section count, index size, and\n * cache statistics.\n *\n * @returns database metadata from the daemon's cached state\n */\n async dbStatus(): Promise<StatusResult> {\n return this.call('dbStatus', {}) as Promise<StatusResult>;\n }\n\n /**\n * Initialises a new `.kbdb` database directory at the given path\n * by sending an init request to the worker daemon.\n *\n * The daemon creates all required subdirectories and seed files via\n * the `worker_init_directory` WASM export.\n *\n * @param targetPath - absolute path to the directory that will\n * contain the new `.kbdb` database\n * @throws {Error} if the `.kbdb` directory already exists or the\n * daemon cannot create the layout\n */\n async initDirectory(targetPath: string): Promise<void> {\n await this.call('initDirectory', { targetPath });\n }\n\n /**\n * Runs all pending database migrations for the `.kbdb` directory\n * at the given path.\n *\n * Delegates to the `worker_migrate` WASM export on the daemon.\n * Each migration step updates `catalog.toml` on success, so\n * retrying after a partial failure is safe.\n *\n * @param targetPath - absolute path to the `.kbdb` database root\n * @returns migration report with old version, new version, and\n * number of migration steps applied\n */\n async migrateDatabase(targetPath: string): Promise<MigrateResult> {\n return this.call('migrateDatabase', {\n targetPath,\n }) as Promise<MigrateResult>;\n }\n\n /**\n * Checks the format version of the `.kbdb` database at the given\n * path against the version required by the current WASM engine.\n *\n * This is a read-only operation: it reads `catalog.toml` and\n * returns the compatibility status without making any changes.\n *\n * @param targetPath - absolute path to the `.kbdb` database root\n * @returns version compatibility report\n */\n async checkVersion(targetPath: string): Promise<VersionStatus> {\n return this.call('checkVersion', {\n targetPath,\n }) as Promise<VersionStatus>;\n }\n\n /**\n * Retrieves all sections whose type name matches the given string.\n *\n * @param sectionType - the application-level type name to filter by\n * @returns all section records with a matching type name\n */\n async listByType(sectionType: string): Promise<SectionRecord[]> {\n return this.call('listByType', {\n sectionType,\n }) as Promise<SectionRecord[]>;\n }\n\n /**\n * Retrieves all documents whose type name matches the given string.\n *\n * @param docType - the application-level document type to filter by\n * @returns all document manifests with a matching type name\n */\n async listDocumentsByType(\n docType: string,\n ): Promise<DocumentManifest[]> {\n return this.call('listDocumentsByType', {\n docType,\n }) as Promise<DocumentManifest[]>;\n }\n\n /**\n * Exports the database to a target directory on disk.\n *\n * Copies section files, document manifests, and `catalog.toml`\n * to `params.path`. Index files are not exported because they\n * are derivable from the section and document data.\n *\n * @param params - optional export parameters\n * @param params.path - target directory path; defaults to\n * `./kbdb-export/` when not provided\n * @returns export report with the resolved path and file counts\n */\n async export(params?: {\n path?: string;\n format?: string;\n }): Promise<ExportResult> {\n return this.call('export', {\n targetPath: params?.path || undefined,\n format: params?.format,\n }) as Promise<ExportResult>;\n }\n\n /**\n * Imports an exported database from the given path.\n *\n * @param params - source path and dry-run flag\n * @returns import report with counts and timing\n */\n async import(params: {\n from: string;\n dryRun: boolean;\n }): Promise<ImportResult> {\n return this.call('importDb', {\n sourcePath: params.from,\n dryRun: params.dryRun,\n }) as Promise<ImportResult>;\n }\n\n /**\n * Sends a JSON-RPC 2.0 request and awaits the response.\n *\n * @param method - the RPC method name\n * @param params - parameters to include in the request\n * @throws {Error} if not connected\n * @throws {Error} when the daemon returns an error response\n */\n private async call(\n method: string,\n params: unknown,\n ): Promise<unknown> {\n const socket = this.socket;\n if (!socket) {\n throw new Error('not connected');\n }\n\n const id = this.nextId++;\n const request = {\n jsonrpc: '2.0',\n id,\n method,\n params: { ctx: this.contextId, ...(params as object) },\n };\n\n const timeoutMs = this.requestTimeoutMs;\n return new Promise<unknown>((resolve, reject) => {\n const call: PendingCall = { resolve, reject };\n if (timeoutMs) {\n call.timer = setTimeout(() => {\n if (!this.pending.has(id)) return;\n this.pending.delete(id);\n const err = new Error(\n `request timeout after ${String(timeoutMs)}ms`,\n );\n (err as unknown as Record<string, unknown>).code =\n 'REQUEST_TIMEOUT';\n reject(err);\n }, timeoutMs);\n }\n this.pending.set(id, call);\n socket.write(JSON.stringify(request) + '\\n');\n });\n }\n\n /**\n * Processes incoming data from the socket, splitting on newlines\n * and dispatching complete JSON-RPC response objects.\n *\n * @param data - raw string chunk received from the socket\n */\n private handleData(data: string): void {\n this.buffer += data;\n const lines = this.buffer.split('\\n');\n this.buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n const response = JSON.parse(line) as JsonRpcResponse;\n const pending = this.pending.get(response.id);\n if (pending) {\n this.pending.delete(response.id);\n if (pending.timer) clearTimeout(pending.timer);\n if (response.error) {\n const err = new Error(response.error.message);\n (err as unknown as Record<string, unknown>).code =\n response.error.code;\n pending.reject(err);\n } else {\n pending.resolve(response.result);\n }\n }\n } catch {\n // Ignore unparseable lines\n }\n }\n }\n}\n", "import { existsSync, readFileSync, unlinkSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { WorkerClient } from '../classes/worker-client.class.ts';\nimport { resolveDbPath } from './resolve-db-path.function.ts';\nimport { computeContextId } from './compute-context-id.function.ts';\nimport { discoverDaemon } from './discover-daemon.function.ts';\nimport { spawnDaemon } from './spawn-daemon.function.ts';\nimport { waitForDaemon } from './wait-for-daemon.function.ts';\nimport { detectRuntime } from '../../runtime/functions/detect-runtime.ts';\nimport { getIpcPath } from '../../platform/functions/get-ipc-path.function.ts';\nimport type { WorkerClientOptions } from '../typings/worker-client-options.interface.ts';\n\n/**\n * Creates and connects a `WorkerClient` to the worker daemon.\n *\n * Resolves the context path, derives a stable context identifier,\n * and checks whether a daemon is already running. If no daemon is\n * found and `autoSpawn` is not `false`, a new daemon process is\n * spawned and the factory waits for its PID file to appear before\n * connecting.\n *\n * @param options - optional configuration for path resolution,\n * auto-spawn behaviour, and connection timeout\n * @returns a connected `WorkerClient` ready to send requests\n * @throws {Error} if the `.kbdb` directory cannot be found\n * @throws {Error} if the socket connection cannot be established\n */\nexport async function createWorkerClient(\n options?: WorkerClientOptions,\n): Promise<WorkerClient> {\n const dbPath =\n options?.contextPath ?? resolveDbPath(options?.dbPath);\n const contextId = await computeContextId(dbPath);\n const socketPath = getIpcPath(contextId);\n\n let daemon = discoverDaemon(contextId);\n\n if (!daemon && options?.autoSpawn !== false) {\n const runtime = detectRuntime();\n spawnDaemon(dbPath, runtime, options?.workerScript);\n await waitForDaemon(contextId, options?.connectTimeoutMs);\n daemon = discoverDaemon(contextId);\n }\n\n if (!daemon) {\n throw new Error(\n `kbdb worker daemon did not start: ${readCrashReason(contextId)}`,\n );\n }\n\n const client = new WorkerClient(\n socketPath,\n contextId,\n options?.requestTimeoutMs,\n );\n await client.connect();\n return client;\n}\n\nfunction readCrashReason(contextId: string): string {\n const crashPath = join(tmpdir(), `kbdb-${contextId}.crash`);\n if (!existsSync(crashPath)) {\n return 'daemon failed to start (no details available)';\n }\n try {\n const raw = readFileSync(crashPath, 'utf-8');\n const crash = JSON.parse(raw) as { error?: string };\n unlinkSync(crashPath);\n return crash.error ?? 'unknown error (crash log empty)';\n } catch {\n return 'daemon failed to start (crash log unreadable)';\n }\n}\n", "import { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\n/**\n * Resolves the absolute path to the `.kbdb` database directory.\n *\n * Searches for a `.kbdb` sub-directory inside `targetDir`. When\n * `targetDir` is omitted, `process.cwd()` is used as the base.\n *\n * @param targetDir - directory to search in; defaults to cwd\n * @throws {Error} if no `.kbdb` directory exists at the resolved\n * path\n */\nexport function resolveDbPath(targetDir?: string): string {\n const base = targetDir ? resolve(targetDir) : process.cwd();\n const dbPath = join(base, '.kbdb');\n if (!existsSync(dbPath)) {\n throw new Error(`database not found: ${dbPath}`);\n }\n return dbPath;\n}\n", "/**\n * Computes the SHA-256 hash of a UTF-8 string.\n *\n * Uses the Web Crypto API (`crypto.subtle`), which is available\n * in both Deno and Node.js >= 20 without additional imports.\n *\n * @param input - the string to hash\n * @returns lowercase hex-encoded SHA-256 digest (64 characters)\n */\nexport async function computeSha256(input: string): Promise<string> {\n const data = new TextEncoder().encode(input);\n const hash = await crypto.subtle.digest('SHA-256', data);\n const bytes = new Uint8Array(hash);\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n", "import { computeSha256 } from '../../hash/functions/compute-sha256.ts';\n\n/**\n * Computes a short context identifier for an absolute path.\n *\n * Hashes the path with SHA-256 and returns the first 16 hex\n * characters. The result is stable for the same input and unique\n * enough to avoid accidental collisions across typical path sets.\n *\n * @param absolutePath - the absolute filesystem path to identify\n * @returns a 16-character lowercase hex string\n */\nexport async function computeContextId(\n absolutePath: string,\n): Promise<string> {\n const hash = await computeSha256(absolutePath);\n return hash.slice(0, 16);\n}\n", "import { existsSync, readFileSync, unlinkSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { isProcessAlive } from '../../platform/functions/is-process-alive.function.ts';\nimport type { DaemonInfo } from '../typings/daemon-info.model.ts';\n\nexport type { DaemonInfo };\n\n/**\n * Discovers a running worker daemon for the given context.\n *\n * Reads the PID file at `<tmpdir>/kbdb-<contextId>.pid`. If the\n * file exists and the process is alive, returns its PID and the\n * expected socket path. If the file is stale (process dead or PID\n * unparseable), removes the PID file and returns `null`.\n *\n * @param contextId - the 16-character context identifier\n * @returns daemon location info, or `null` if no live daemon found\n */\nexport function discoverDaemon(contextId: string): DaemonInfo | null {\n const pidPath = join(tmpdir(), `kbdb-${contextId}.pid`);\n\n if (!existsSync(pidPath)) return null;\n\n const pidStr = readFileSync(pidPath, 'utf-8').trim();\n const pid = parseInt(pidStr, 10);\n\n if (isNaN(pid) || !isProcessAlive(pid)) {\n try {\n unlinkSync(pidPath);\n } catch {\n // Stale PID file removal is best-effort\n }\n return null;\n }\n\n const socketPath = join(tmpdir(), `kbdb-${contextId}.sock`);\n\n const crashPath = join(tmpdir(), `kbdb-${contextId}.crash`);\n try {\n unlinkSync(crashPath);\n } catch {\n // stale crash file removal is best-effort\n }\n\n return { pid, socketPath };\n}\n", "/**\n * Checks whether a process with the given PID is alive.\n *\n * Sends signal `0` to the process, which performs a permission\n * check without sending an actual signal. Returns `true` if the\n * process exists and is reachable, `false` otherwise.\n *\n * @param pid - the process identifier to probe\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n", "import { spawn } from 'node:child_process';\nimport type { Runtime } from '../../runtime/typings/runtime.ts';\n\n/**\n * Spawns a detached worker daemon process for the given context.\n *\n * @param contextPath - absolute path to the context directory the\n * daemon should serve\n * @param runtime - the current JavaScript runtime environment\n * @param workerScript - absolute path to the worker daemon script,\n * resolved at the entry point by `resolveWorkerScript`\n */\nexport function spawnDaemon(\n contextPath: string,\n runtime: Runtime,\n workerScript?: string,\n): void {\n if (!workerScript) {\n throw new Error(\n 'workerScript must be provided' + ' (resolve at entry point)',\n );\n }\n const execPath = runtime === 'deno' ? 'deno' : process.execPath;\n\n const args =\n runtime === 'deno'\n ? ['run', '--allow-all', workerScript, contextPath]\n : [workerScript, contextPath];\n\n const child = spawn(execPath, args, {\n detached: true,\n stdio: 'ignore',\n });\n child.unref();\n}\n", "import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\n\n/** Default maximum wait time for the daemon PID file to appear. */\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/** Polling interval in milliseconds between existence checks. */\nconst POLL_INTERVAL_MS = 100;\n\n/**\n * Waits for the worker daemon's PID file to appear on disk.\n *\n * Polls every 100 ms until the PID file at\n * `<tmpdir>/kbdb-<contextId>.pid` exists or the timeout elapses.\n *\n * @param contextId - the 16-character context identifier\n * @param timeoutMs - maximum wait time in milliseconds; defaults\n * to 10 000 ms\n * @returns `true` if the PID file appeared before the timeout,\n * `false` otherwise\n */\nexport async function waitForDaemon(\n contextId: string,\n timeoutMs: number = DEFAULT_TIMEOUT_MS,\n): Promise<boolean> {\n const pidPath = join(tmpdir(), `kbdb-${contextId}.pid`);\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n if (existsSync(pidPath)) return true;\n await new Promise<void>((r) => setTimeout(r, POLL_INTERVAL_MS));\n }\n return false;\n}\n", "import type { Runtime } from '../typings/runtime.ts';\n\n/**\n * Detects the current JavaScript runtime environment.\n *\n * Returns `'deno'` when the global `Deno` object is present,\n * otherwise returns `'node'`.\n */\nexport function detectRuntime(): Runtime {\n if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {\n return 'deno';\n }\n return 'node';\n}\n", "import { join } from 'node:path';\nimport { getTmpdir } from './get-tmpdir.function.ts';\n\n/**\n * Returns the platform-appropriate IPC socket path for a given\n * context identifier.\n *\n * On Windows, returns a named pipe path (`\\\\.\\pipe\\kbdb-<ctx>`).\n * On POSIX systems, returns a Unix domain socket path under the\n * system temp directory (`<tmpdir>/kbdb-<ctx>.sock`).\n *\n * @param ctx - unique context identifier embedded in the path\n */\nexport function getIpcPath(ctx: string): string {\n if (process.platform === 'win32') {\n return `\\\\\\\\.\\\\pipe\\\\kbdb-${ctx}`;\n }\n return join(getTmpdir(), `kbdb-${ctx}.sock`);\n}\n", "import { tmpdir } from 'node:os';\n\n/**\n * Returns the operating system's default temporary directory path.\n */\nexport function getTmpdir(): string {\n return tmpdir();\n}\n", "import { createWorkerClient } from './create-worker-client.function.ts';\nimport type { WorkerClient } from '../classes/worker-client.class.ts';\nimport type { WorkerClientOptions } from '../typings/worker-client-options.interface.ts';\nimport { resolveDbPath } from './resolve-db-path.function.ts';\n\n/** Cache of connected clients keyed by database path. */\nconst cache = new Map<string, WorkerClient>();\n\n/**\n * Returns a cached `WorkerClient` for the given context\n * path, or creates and caches a new one if the cached\n * client is disconnected or absent.\n *\n * Intended for library consumers and the MCP server. CLI\n * one-shots should use `createWorkerClient()` directly.\n *\n * @param options - optional configuration forwarded to\n * `createWorkerClient`\n * @returns a connected `WorkerClient`\n */\nexport async function getOrCreateClient(\n options?: WorkerClientOptions,\n): Promise<WorkerClient> {\n const dbPath =\n options?.contextPath ?? resolveDbPath(options?.dbPath);\n const cached = cache.get(dbPath);\n if (cached?.isConnected) return cached;\n cache.delete(dbPath);\n const client = await createWorkerClient(options);\n cache.set(dbPath, client);\n return client;\n}\n\n/**\n * Clears the internal client cache. Intended for tests\n * that need isolation between runs.\n */\nexport function clearClientCache(): void {\n for (const [key, client] of cache) {\n client.disconnect();\n cache.delete(key);\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,UAAU;;;ACDvB,sBAAwB;AAsDjB,IAAM,eAAN,MAAmB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqBvB,YACoB,YACA,WACA,kBAClB;AAHkB;AACA;AACA;AAAA,EACjB;AAAA;AAAA,EAvBK,SAAwB;AAAA;AAAA,EAGxB,SAAS;AAAA;AAAA,EAGA,UAAU,oBAAI,IAAyB;AAAA;AAAA,EAGhD,SAAS;AAAA;AAAA,EAiBjB,IAAI,cAAuB;AACxB,WAAO,KAAK,WAAW;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,UAAyB;AAC5B,UAAM,aAAa;AACnB,QAAI,QAAQ;AACZ,aAAS,UAAU,GAAG,WAAW,YAAY,WAAW;AACrD,UAAI;AACD,cAAM,KAAK,WAAW;AACtB;AAAA,MACH,SAAS,KAAc;AACpB,cAAM,OAAQ,IAA8B;AAC5C,cAAM,YACH,SAAS,YAAY,SAAS;AACjC,YAAI,CAAC,aAAa,YAAY,YAAY;AACvC,gBAAM;AAAA,QACT;AACA,cAAM,IAAI,QAAc,CAAC,MAAM,WAAW,GAAG,KAAK,CAAC;AACnD,gBAAQ,KAAK,IAAI,QAAQ,GAAG,GAAI;AAAA,MACnC;AAAA,IACH;AAAA,EACH;AAAA;AAAA,EAGA,aAAmB;AAChB,QAAI,KAAK,QAAQ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AAmB,OAAO;AAC/C,QAAM,IAAI,QAAQ,MAAM;AACxB,SAAO;AACV;",
|
|
6
|
-
"names": ["resolve", "import_node_fs", "import_node_path", "import_node_os", "import_node_fs", "import_node_path", "import_node_fs", "import_node_path", "import_node_os", "import_node_path", "import_node_os"]
|
|
3
|
+
"sources": ["../mod.ts", "../src/shared/version/constants/version.constant.ts", "../src/shared/worker-client/classes/worker-client.class.ts", "../src/shared/worker-client/functions/discover-daemon.function.ts", "../src/shared/platform/functions/is-process-alive.function.ts", "../src/shared/log/typings/log-level.type.ts", "../src/shared/log/constants/log-colors.constant.ts", "../src/shared/log/constants/log-icons.constant.ts", "../src/shared/log/constants/log-defaults.constant.ts", "../src/shared/log/functions/write-stderr.function.ts", "../src/shared/log/functions/log.function.ts", "../src/shared/worker-client/functions/create-worker-client.function.ts", "../src/shared/worker-client/functions/resolve-db-path.function.ts", "../src/shared/hash/functions/compute-sha256.ts", "../src/shared/worker-client/functions/compute-context-id.function.ts", "../src/shared/worker-client/functions/spawn-daemon.function.ts", "../src/shared/worker-client/functions/wait-for-daemon.function.ts", "../src/shared/runtime/functions/detect-runtime.ts", "../src/shared/platform/functions/get-ipc-path.function.ts", "../src/shared/platform/functions/get-tmpdir.function.ts", "../src/shared/worker-client/functions/get-or-create-client.function.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * @module\n *\n * File-based knowledge base database for AI agents.\n * Provides a programmatic API for indexing documents,\n * searching with ranked results, and recalling section\n * context at progressive depths.\n *\n * @example\n * ```ts\n * import { createWorkerClient } from '@dikolab/kbdb';\n *\n * const client = await createWorkerClient({\n * contextPath: '/path/to/.kbdb',\n * });\n *\n * const results = await client.search({\n * query: 'authentication',\n * limit: 10,\n * });\n *\n * console.log(results.items);\n * client.disconnect();\n * ```\n */\n\n/** Semantic version string matching `package.json`. */\nexport { version } from './src/shared/mod.ts';\n\n/** Creates a connected worker client for the given database. */\nexport { createWorkerClient } from './src/shared/worker-client/index.ts';\n\n/** Persistent client wrapping JSON-RPC calls to the daemon. */\nexport { WorkerClient } from './src/shared/worker-client/index.ts';\n\n/** Resolves a parent directory to the `.kbdb` path inside it. */\nexport { resolveDbPath } from './src/shared/worker-client/index.ts';\n\n/** Derives the 16-char hex context ID from an absolute path. */\nexport { computeContextId } from './src/shared/worker-client/index.ts';\n\n/** Returns a cached client or creates a new one for the given path. */\nexport { getOrCreateClient } from './src/shared/worker-client/index.ts';\n\n/** Options accepted by {@linkcode createWorkerClient}. */\nexport type { WorkerClientOptions } from './src/shared/worker-client/index.ts';\n\n/** Parameters for a search query. */\nexport type { SearchParams } from './src/shared/worker-client/index.ts';\n\n/** A single ranked result returned by search. */\nexport type { SearchResult } from './src/shared/worker-client/index.ts';\n\n/** Raw section record stored on disk. */\nexport type { Section } from './src/shared/worker-client/index.ts';\n\n/** Parameters for adding a new section. */\nexport type { AddSectionParams } from './src/shared/worker-client/index.ts';\n\n/** Database status snapshot returned by `client.status()`. */\nexport type { StatusResult } from './src/shared/worker-client/index.ts';\n", "/** Current package version, kept in sync with package.json. */\nexport const VERSION = '0.4.1';\n", "import { connect } from 'node:net';\nimport type { Socket } from 'node:net';\nimport { discoverDaemon } from '../functions/discover-daemon.function.ts';\nimport { log } from '../../log/functions/log.function.ts';\nimport { LogLevel } from '../../log/typings/log-level.type.ts';\nimport type { SearchParams } from '../typings/search-params.model.ts';\nimport type { PagedSearchResult } from '../typings/search-result.model.ts';\nimport type {\n AddSectionParams,\n Section,\n} from '../typings/section.model.ts';\nimport type { StatusResult } from '../typings/status-result.model.ts';\nimport type { AddSectionResult } from '../typings/add-section-result.model.ts';\nimport type { RemoveSectionResult } from '../typings/remove-section-result.model.ts';\nimport type { ContentResult } from '../typings/content-result.model.ts';\nimport type { IntegrityCheckResult } from '../typings/integrity-check-result.model.ts';\nimport type { GcResult } from '../typings/gc-result.model.ts';\nimport type { RebuildResult } from '../typings/rebuild-result.model.ts';\nimport type { MigrateResult } from '../typings/migrate-result.model.ts';\nimport type { VersionStatus } from '../typings/version-status.model.ts';\nimport type { SectionRecord } from '../../wasm-codec/functions/decode-section-records.function.ts';\nimport type { DocumentManifest } from '../../wasm-codec/functions/decode-document-manifest.function.ts';\nimport type {\n RecallParams,\n RecallResult,\n} from '../typings/recall-result.model.ts';\nimport type { ExportResult } from '../typings/export-result.model.ts';\nimport type { ImportResult } from '../typings/import-result.model.ts';\n\n/** Pending JSON-RPC call awaiting a response from the daemon. */\ninterface PendingCall {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer?: ReturnType<typeof setTimeout>;\n}\n\n/** Shape of a JSON-RPC 2.0 error object from the daemon. */\ninterface JsonRpcError {\n readonly code: number;\n readonly message: string;\n}\n\n/** Shape of a JSON-RPC 2.0 response from the daemon. */\ninterface JsonRpcResponse {\n readonly id: number;\n readonly result?: unknown;\n readonly error?: JsonRpcError;\n}\n\n/**\n * IPC client that communicates with the worker daemon over a Unix\n * domain socket (or Windows named pipe) using JSON-RPC 2.0 with\n * newline-delimited message framing.\n *\n * Call `connect()` before any other method and `disconnect()` when\n * done to release the underlying socket.\n */\nexport class WorkerClient {\n /** Underlying socket; `null` when not connected. */\n private socket: Socket | null = null;\n\n /** Monotonically increasing request ID counter. */\n private nextId = 1;\n\n /** Map of outstanding request IDs to their resolve/reject pairs. */\n private readonly pending = new Map<number, PendingCall>();\n\n /** Partial line buffer for split TCP/IPC frames. */\n private buffer = '';\n\n /**\n * @param socketPath - absolute path to the daemon's IPC socket\n * (or Windows named pipe path)\n * @param contextId - 16-character context identifier sent as\n * `ctx` in every JSON-RPC request\n * @param requestTimeoutMs - per-request timeout in ms\n * (0 or undefined disables the timeout)\n */\n constructor(\n private readonly socketPath: string,\n private readonly contextId: string,\n private readonly requestTimeoutMs?: number,\n ) {}\n\n /** Whether the underlying socket is connected. */\n get isConnected(): boolean {\n return this.socket !== null;\n }\n\n /**\n * Establishes the IPC connection to the worker daemon.\n *\n * Retries up to 5 times with exponential backoff on\n * transient errors (`ENOENT`, `ECONNREFUSED`).\n *\n * @throws {Error} if the connection cannot be established\n */\n async connect(): Promise<void> {\n log('connecting to ' + this.socketPath, LogLevel.DEBUG);\n const maxRetries = 5;\n let delay = 50;\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n await this.tryConnect();\n log('connected', LogLevel.DEBUG);\n return;\n } catch (err: unknown) {\n const code = (err as NodeJS.ErrnoException).code;\n const retriable =\n code === 'ENOENT' || code === 'ECONNREFUSED';\n if (!retriable || attempt === maxRetries) {\n throw err;\n }\n log(\n 'connect retry: attempt=' +\n attempt.toString() +\n ' code=' +\n code +\n ' delay=' +\n delay.toString() +\n 'ms',\n LogLevel.DEBUG,\n );\n await new Promise<void>((r) => setTimeout(r, delay));\n delay = Math.min(delay * 2, 1000);\n }\n }\n }\n\n /** Destroys the IPC socket and clears the connection state. */\n disconnect(): void {\n log('disconnecting client', LogLevel.DEBUG);\n if (this.socket) {\n this.socket.destroy();\n this.socket = null;\n }\n }\n\n /**\n * Kills the daemon process and disconnects the client.\n *\n * Discovers the daemon via PID file and sends `SIGTERM`.\n * Always disconnects the socket regardless of kill outcome.\n */\n killDaemon(): void {\n const info = discoverDaemon(this.contextId);\n log(\n 'killing daemon: pid=' +\n (info ? info.pid.toString() : 'unknown'),\n LogLevel.DEBUG,\n );\n if (info) {\n try {\n process.kill(info.pid, 'SIGTERM');\n } catch {\n // already dead\n }\n }\n this.disconnect();\n }\n\n /**\n * Single connection attempt with keepalive and\n * post-connect failure handlers.\n */\n private async tryConnect(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const sock = connect(this.socketPath, () => {\n sock.removeListener('error', reject);\n sock.setKeepAlive(true, 30_000);\n sock.on('error', (err: Error) => {\n log(\n 'socket error: code=' +\n ((err as NodeJS.ErrnoException).code ??\n err.message),\n LogLevel.DEBUG,\n );\n this.handleSocketFailure(err);\n });\n sock.on('close', () => {\n log('socket closed', LogLevel.DEBUG);\n if (this.pending.size > 0) {\n this.handleSocketFailure(\n new Error('connection closed'),\n );\n }\n this.socket = null;\n });\n this.socket = sock;\n resolve();\n });\n sock.on('error', reject);\n sock.on('data', (chunk: Buffer) => {\n this.handleData(chunk.toString());\n });\n });\n }\n\n /**\n * Rejects all pending calls and marks the client as\n * disconnected.\n */\n private handleSocketFailure(err: Error): void {\n log(\n 'socket failure: pending=' +\n this.pending.size.toString() +\n ' err=' +\n err.message,\n LogLevel.DEBUG,\n );\n const sock = this.socket;\n this.socket = null;\n for (const [id, call] of this.pending) {\n this.pending.delete(id);\n if (call.timer) clearTimeout(call.timer);\n call.reject(err);\n }\n if (sock) sock.destroy();\n }\n\n /**\n * Searches the knowledge base.\n *\n * @param params - query parameters including the search string\n * @returns paginated search results with metadata\n */\n async search(params: SearchParams): Promise<PagedSearchResult> {\n return this.call('search', {\n ...params,\n algo: params.algo,\n }) as Promise<PagedSearchResult>;\n }\n\n /**\n * Retrieves full content and context for one or more sections by\n * their knowledge-base identifiers.\n *\n * @param params - section identifier(s) and optional expansion depth\n * @returns a single `RecallResult` when `kbid` is provided without\n * `kbids`, or a `RecallResult[]` when `kbids` is provided\n */\n async recall(\n params: RecallParams,\n ): Promise<RecallResult | RecallResult[]> {\n return this.call('recall', params) as Promise<\n RecallResult | RecallResult[]\n >;\n }\n\n /**\n * Adds a new section to the knowledge base.\n *\n * @param params - section content and metadata\n * @returns the result including the assigned knowledge-base\n * identifier and indexing statistics\n */\n async addSection(\n params: AddSectionParams,\n ): Promise<AddSectionResult> {\n return this.call(\n 'addSection',\n params,\n ) as Promise<AddSectionResult>;\n }\n\n /**\n * Replaces an existing section's content and metadata.\n *\n * @param kbid - identifier of the section to update\n * @param params - new content and metadata\n * @returns the knowledge-base identifier of the updated section\n */\n async updateSection(\n kbid: string,\n params: AddSectionParams,\n ): Promise<string> {\n return this.call('updateSection', {\n kbid,\n ...params,\n }) as Promise<string>;\n }\n\n /**\n * Removes a section from the knowledge base.\n *\n * @param kbid - identifier of the section to remove\n * @returns removal result with `removed` flag and elapsed time\n */\n async removeSection(kbid: string): Promise<RemoveSectionResult> {\n return this.call('removeSection', {\n kbid,\n }) as Promise<RemoveSectionResult>;\n }\n\n /**\n * Retrieves multiple sections by their identifiers.\n *\n * @param kbids - list of knowledge-base identifiers to fetch\n * @returns sections in the order their IDs were requested\n */\n async readSections(kbids: string[]): Promise<Section[]> {\n return this.call('readSections', {\n kbids,\n }) as Promise<Section[]>;\n }\n\n /**\n * Groups a set of sections under a named document.\n *\n * @param title - human-readable document title\n * @param kbids - identifiers of the sections to group\n * @param docType - application-level document type tag; omit or\n * pass an empty string for untagged documents\n * @returns the assigned document identifier\n */\n async groupSections(\n title: string,\n kbids: string[],\n docType?: string,\n ): Promise<string> {\n const result = (await this.call('groupSections', {\n title,\n kbids,\n docType: docType ?? '',\n })) as { docid: string } | string;\n return typeof result === 'string' ? result : result.docid;\n }\n\n /**\n * Removes the document grouping for the given document.\n *\n * The sections themselves are not deleted; only the grouping\n * record is removed.\n *\n * @param docid - identifier of the document grouping to remove\n */\n async removeGrouping(docid: string): Promise<void> {\n await this.call('removeGrouping', { docid });\n }\n\n /**\n * Retrieves a full document record including its sections.\n *\n * @param docid - identifier of the document to retrieve\n * @returns the document record as returned by the daemon\n */\n async retrieveDocument(docid: string): Promise<unknown> {\n return this.call('retrieveDocument', { docid });\n }\n\n /**\n * Composes a rendered Markdown document from one or more kbid\n * or docid identifiers.\n *\n * @param ids - list of kbid or docid identifiers (may be mixed)\n * @returns composed Markdown result with character count\n */\n async content(ids: string[]): Promise<ContentResult> {\n return this.call('content', { ids }) as Promise<ContentResult>;\n }\n\n /**\n * Runs an integrity check on the knowledge-base database.\n *\n * @returns a report of all issues found; `ok` is `true` when\n * no errors were detected\n */\n async integrityCheck(): Promise<IntegrityCheckResult> {\n return this.call(\n 'integrityCheck',\n {},\n ) as Promise<IntegrityCheckResult>;\n }\n\n /**\n * Removes unreferenced sections from the database.\n *\n * @returns a report of sections removed and bytes freed\n */\n async gc(): Promise<GcResult> {\n return this.call('gc', {}) as Promise<GcResult>;\n }\n\n /**\n * Reconstructs all index files from section files and document\n * manifests on disk. Text and code sections are re-tokenized;\n * image sections are skipped.\n *\n * @returns a report of sections and terms re-indexed\n */\n async rebuildIndexes(): Promise<RebuildResult> {\n return this.call('rebuildIndexes', {}) as Promise<RebuildResult>;\n }\n\n /**\n * Invalidates the in-memory cache entry for a single section.\n *\n * @param kbid - identifier of the section to evict from cache\n */\n async invalidate(kbid: string): Promise<void> {\n await this.call('invalidate', { kbid });\n }\n\n /** Clears all entries from the daemon's in-memory cache. */\n async invalidateAll(): Promise<void> {\n await this.call('invalidateAll', {});\n }\n\n /**\n * Retrieves diagnostic status information from the daemon.\n *\n * @returns current initialization state and cache statistics\n */\n async status(): Promise<StatusResult> {\n return this.call('status', {}) as Promise<StatusResult>;\n }\n\n /**\n * Returns database metadata and status from the daemon,\n * including document count, section count, index size, and\n * cache statistics.\n *\n * @returns database metadata from the daemon's cached state\n */\n async dbStatus(): Promise<StatusResult> {\n return this.call('dbStatus', {}) as Promise<StatusResult>;\n }\n\n /**\n * Initialises a new `.kbdb` database directory at the given path\n * by sending an init request to the worker daemon.\n *\n * The daemon creates all required subdirectories and seed files via\n * the `worker_init_directory` WASM export.\n *\n * @param targetPath - absolute path to the directory that will\n * contain the new `.kbdb` database\n * @throws {Error} if the `.kbdb` directory already exists or the\n * daemon cannot create the layout\n */\n async initDirectory(targetPath: string): Promise<void> {\n await this.call('initDirectory', { targetPath });\n }\n\n /**\n * Runs all pending database migrations for the `.kbdb` directory\n * at the given path.\n *\n * Delegates to the `worker_migrate` WASM export on the daemon.\n * Each migration step updates `catalog.toml` on success, so\n * retrying after a partial failure is safe.\n *\n * @param targetPath - absolute path to the `.kbdb` database root\n * @returns migration report with old version, new version, and\n * number of migration steps applied\n */\n async migrateDatabase(targetPath: string): Promise<MigrateResult> {\n return this.call('migrateDatabase', {\n targetPath,\n }) as Promise<MigrateResult>;\n }\n\n /**\n * Checks the format version of the `.kbdb` database at the given\n * path against the version required by the current WASM engine.\n *\n * This is a read-only operation: it reads `catalog.toml` and\n * returns the compatibility status without making any changes.\n *\n * @param targetPath - absolute path to the `.kbdb` database root\n * @returns version compatibility report\n */\n async checkVersion(targetPath: string): Promise<VersionStatus> {\n return this.call('checkVersion', {\n targetPath,\n }) as Promise<VersionStatus>;\n }\n\n /**\n * Retrieves all sections whose type name matches the given string.\n *\n * @param sectionType - the application-level type name to filter by\n * @returns all section records with a matching type name\n */\n async listByType(sectionType: string): Promise<SectionRecord[]> {\n return this.call('listByType', {\n sectionType,\n }) as Promise<SectionRecord[]>;\n }\n\n /**\n * Retrieves all documents whose type name matches the given string.\n *\n * @param docType - the application-level document type to filter by\n * @returns all document manifests with a matching type name\n */\n async listDocumentsByType(\n docType: string,\n ): Promise<DocumentManifest[]> {\n return this.call('listDocumentsByType', {\n docType,\n }) as Promise<DocumentManifest[]>;\n }\n\n /**\n * Exports the database to a target directory on disk.\n *\n * Copies section files, document manifests, and `catalog.toml`\n * to `params.path`. Index files are not exported because they\n * are derivable from the section and document data.\n *\n * @param params - optional export parameters\n * @param params.path - target directory path; defaults to\n * `./kbdb-export/` when not provided\n * @returns export report with the resolved path and file counts\n */\n async export(params?: {\n path?: string;\n format?: string;\n }): Promise<ExportResult> {\n return this.call('export', {\n targetPath: params?.path || undefined,\n format: params?.format,\n }) as Promise<ExportResult>;\n }\n\n /**\n * Imports an exported database from the given path.\n *\n * @param params - source path and dry-run flag\n * @returns import report with counts and timing\n */\n async import(params: {\n from: string;\n dryRun: boolean;\n }): Promise<ImportResult> {\n return this.call('importDb', {\n sourcePath: params.from,\n dryRun: params.dryRun,\n }) as Promise<ImportResult>;\n }\n\n /**\n * Sends a JSON-RPC 2.0 request and awaits the response.\n *\n * @param method - the RPC method name\n * @param params - parameters to include in the request\n * @throws {Error} if not connected\n * @throws {Error} when the daemon returns an error response\n */\n private async call(\n method: string,\n params: unknown,\n ): Promise<unknown> {\n const socket = this.socket;\n if (!socket) {\n throw new Error('not connected');\n }\n\n const id = this.nextId++;\n log(\n 'call: method=' + method + ' id=' + id.toString(),\n LogLevel.DEBUG,\n );\n const request = {\n jsonrpc: '2.0',\n id,\n method,\n params: { ctx: this.contextId, ...(params as object) },\n };\n\n const timeoutMs = this.requestTimeoutMs;\n return new Promise<unknown>((resolve, reject) => {\n const call: PendingCall = { resolve, reject };\n if (timeoutMs) {\n call.timer = setTimeout(() => {\n if (!this.pending.has(id)) return;\n this.pending.delete(id);\n log(\n 'request timeout after ' + String(timeoutMs) + 'ms',\n LogLevel.WARNING,\n );\n const err = new Error(\n `request timeout after ${String(timeoutMs)}ms`,\n );\n (err as unknown as Record<string, unknown>).code =\n 'REQUEST_TIMEOUT';\n reject(err);\n }, timeoutMs);\n }\n this.pending.set(id, call);\n socket.write(JSON.stringify(request) + '\\n');\n });\n }\n\n /**\n * Processes incoming data from the socket, splitting on newlines\n * and dispatching complete JSON-RPC response objects.\n *\n * @param data - raw string chunk received from the socket\n */\n private handleData(data: string): void {\n this.buffer += data;\n const lines = this.buffer.split('\\n');\n this.buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n const response = JSON.parse(line) as JsonRpcResponse;\n const pending = this.pending.get(response.id);\n if (pending) {\n this.pending.delete(response.id);\n if (pending.timer) clearTimeout(pending.timer);\n if (response.error) {\n log(\n 'response error: id=' +\n response.id.toString() +\n ' code=' +\n response.error.code.toString(),\n LogLevel.DEBUG,\n );\n const err = new Error(response.error.message);\n (err as unknown as Record<string, unknown>).code =\n response.error.code;\n pending.reject(err);\n } else {\n log(\n 'response ok: id=' + response.id.toString(),\n LogLevel.DEBUG,\n );\n pending.resolve(response.result);\n }\n } else {\n log(\n 'unmatched response id=' + response.id.toString(),\n LogLevel.DEBUG,\n );\n }\n } catch (parseErr: unknown) {\n log(\n 'json parse error: ' + (parseErr as Error).message,\n LogLevel.DEBUG,\n );\n }\n }\n }\n}\n", "import { existsSync, readFileSync, unlinkSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { isProcessAlive } from '../../platform/functions/is-process-alive.function.ts';\nimport type { DaemonInfo } from '../typings/daemon-info.model.ts';\nimport { log } from '../../log/functions/log.function.ts';\nimport { LogLevel } from '../../log/typings/log-level.type.ts';\n\nexport type { DaemonInfo };\n\n/**\n * Discovers a running worker daemon for the given context.\n *\n * Reads the PID file at `<tmpdir>/kbdb-<contextId>.pid`. If the\n * file exists and the process is alive, returns its PID and the\n * expected socket path. If the file is stale (process dead or PID\n * unparseable), removes the PID file and returns `null`.\n *\n * @param contextId - the 16-character context identifier\n * @returns daemon location info, or `null` if no live daemon found\n */\nexport function discoverDaemon(contextId: string): DaemonInfo | null {\n log('discovering daemon for context: ' + contextId, LogLevel.DEBUG);\n const pidPath = join(tmpdir(), `kbdb-${contextId}.pid`);\n\n if (!existsSync(pidPath)) {\n log(\n 'no daemon PID file found for context: ' + contextId,\n LogLevel.DEBUG,\n );\n return null;\n }\n\n const pidStr = readFileSync(pidPath, 'utf-8').trim();\n const pid = parseInt(pidStr, 10);\n\n if (isNaN(pid) || !isProcessAlive(pid)) {\n log(\n 'daemon process not alive for context: ' + contextId,\n LogLevel.DEBUG,\n );\n try {\n unlinkSync(pidPath);\n } catch {\n // Stale PID file removal is best-effort\n }\n return null;\n }\n\n log('daemon found: pid=' + pid.toString(), LogLevel.DEBUG);\n const socketPath = join(tmpdir(), `kbdb-${contextId}.sock`);\n\n const crashPath = join(tmpdir(), `kbdb-${contextId}.crash`);\n try {\n unlinkSync(crashPath);\n } catch {\n // stale crash file removal is best-effort\n }\n\n return { pid, socketPath };\n}\n", "/**\n * Checks whether a process with the given PID is alive.\n *\n * Sends signal `0` to the process, which performs a permission\n * check without sending an actual signal. Returns `true` if the\n * process exists and is reachable, `false` otherwise.\n *\n * @param pid - the process identifier to probe\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n", "/** Verbosity levels, ordered from most to least verbose. */\nexport enum LogLevel {\n DEBUG = 0,\n INFO = 1,\n WARNING = 2,\n ERROR = 3,\n}\n", "import { LogLevel } from '../typings/log-level.type.ts';\n\n/** ANSI escape sequence that resets all text formatting. */\nexport const ANSI_RESET = '\\x1b[0m';\n\n/** ANSI foreground color code applied to each log level's output. */\nexport const LOG_COLORS: Record<LogLevel, string> = {\n [LogLevel.DEBUG]: '\\x1b[37m',\n [LogLevel.INFO]: '\\x1b[36m',\n [LogLevel.WARNING]: '\\x1b[33m',\n [LogLevel.ERROR]: '\\x1b[91m',\n};\n", "import { LogLevel } from '../typings/log-level.type.ts';\n\n/** Single-character icon used as visual prefix for each log level. */\nexport const LOG_ICONS: Record<LogLevel, string> = {\n [LogLevel.DEBUG]: '\u25B8',\n [LogLevel.INFO]: '\u2139',\n [LogLevel.WARNING]: '\u26A0',\n [LogLevel.ERROR]: '\u2716',\n};\n", "import { LogLevel } from '../typings/log-level.type.ts';\n\n/** Default log level used when no CLI flag or env var is set. */\nexport const DEFAULT_LOG_LEVEL = LogLevel.ERROR;\n", "/**\n * Writes a string to the process standard error stream.\n *\n * Works on both Node.js (via `process.stderr.write`) and Deno\n * (via `Deno.stderr.writeSync`). Silently does nothing when\n * neither runtime API is available.\n *\n * @param message - the string to write to stderr\n */\nexport function writeStderr(message: string): void {\n const g = globalThis as Record<string, unknown>;\n const proc = g['process'] as\n | { stderr: { write: (s: string) => void } }\n | undefined;\n if (proc?.stderr) {\n proc.stderr.write(message);\n return;\n }\n const deno = g['Deno'] as\n | { stderr: { writeSync: (b: Uint8Array) => void } }\n | undefined;\n deno?.stderr.writeSync(new TextEncoder().encode(message));\n}\n", "import {\n ANSI_RESET,\n LOG_COLORS,\n} from '../constants/log-colors.constant.ts';\nimport { LOG_ICONS } from '../constants/log-icons.constant.ts';\nimport { DEFAULT_LOG_LEVEL } from '../constants/log-defaults.constant.ts';\nimport { LogLevel } from '../typings/log-level.type.ts';\nimport { writeStderr } from './write-stderr.function.ts';\n\n/** A function that receives a formatted log line. */\ntype OutputFn = (message: string) => void;\n\nlet currentLevel: LogLevel = DEFAULT_LOG_LEVEL;\n\nconst outputs: Record<LogLevel, OutputFn> = {\n [LogLevel.DEBUG]: writeStderr,\n [LogLevel.INFO]: writeStderr,\n [LogLevel.WARNING]: writeStderr,\n [LogLevel.ERROR]: writeStderr,\n};\n\n/**\n * Sets the minimum log level. Messages below this level are\n * suppressed. Used internally by `configureLog`.\n */\nexport function setLogLevel(level: LogLevel): void {\n currentLevel = level;\n}\n\n/**\n * Overrides the output function for a specific log level.\n * Used internally by `configureLog`.\n *\n * @param level - the log level whose output to replace\n * @param output - function that receives the formatted message\n */\nexport function setLogOutput(level: LogLevel, output: OutputFn): void {\n outputs[level] = output;\n}\n\n/**\n * Writes a formatted, colorized log message to the configured\n * output for the given level. Messages below the current level\n * are silently discarded.\n *\n * Format: `\\x1b[COLORm ICON [LEVEL_NAME] message\\x1b[0m\\n`\n *\n * @param message - the text to log\n * @param level - severity level; defaults to `LogLevel.ERROR`\n */\nexport function log(\n message: string,\n level: LogLevel = LogLevel.ERROR,\n): void {\n if (level < currentLevel) {\n return;\n }\n const color = LOG_COLORS[level];\n const icon = LOG_ICONS[level];\n const name = LogLevel[level];\n const line = `${color}${icon} [${name}] ${message}${ANSI_RESET}\\n`;\n outputs[level](line);\n}\n", "import { existsSync, readFileSync, unlinkSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { WorkerClient } from '../classes/worker-client.class.ts';\nimport { resolveDbPath } from './resolve-db-path.function.ts';\nimport { computeContextId } from './compute-context-id.function.ts';\nimport { discoverDaemon } from './discover-daemon.function.ts';\nimport { spawnDaemon } from './spawn-daemon.function.ts';\nimport { waitForDaemon } from './wait-for-daemon.function.ts';\nimport { detectRuntime } from '../../runtime/functions/detect-runtime.ts';\nimport { getIpcPath } from '../../platform/functions/get-ipc-path.function.ts';\nimport type { WorkerClientOptions } from '../typings/worker-client-options.interface.ts';\nimport { log } from '../../log/functions/log.function.ts';\nimport { LogLevel } from '../../log/typings/log-level.type.ts';\n\n/**\n * Creates and connects a `WorkerClient` to the worker daemon.\n *\n * Resolves the context path, derives a stable context identifier,\n * and checks whether a daemon is already running. If no daemon is\n * found and `autoSpawn` is not `false`, a new daemon process is\n * spawned and the factory waits for its PID file to appear before\n * connecting.\n *\n * @param options - optional configuration for path resolution,\n * auto-spawn behaviour, and connection timeout\n * @returns a connected `WorkerClient` ready to send requests\n * @throws {Error} if the `.kbdb` directory cannot be found\n * @throws {Error} if the socket connection cannot be established\n */\nexport async function createWorkerClient(\n options?: WorkerClientOptions,\n): Promise<WorkerClient> {\n const dbPath =\n options?.contextPath ?? resolveDbPath(options?.dbPath);\n const contextId = await computeContextId(dbPath);\n log('create-worker-client: contextId=' + contextId, LogLevel.DEBUG);\n const socketPath = getIpcPath(contextId);\n\n let daemon = discoverDaemon(contextId);\n\n if (daemon) {\n log('daemon found: pid=' + daemon.pid.toString(), LogLevel.DEBUG);\n } else {\n log('no daemon found', LogLevel.DEBUG);\n }\n\n if (!daemon && options?.autoSpawn !== false) {\n const runtime = detectRuntime();\n log('auto-spawning daemon', LogLevel.DEBUG);\n spawnDaemon(dbPath, runtime, options?.workerScript);\n log('waiting for daemon after spawn', LogLevel.DEBUG);\n await waitForDaemon(contextId, options?.connectTimeoutMs);\n daemon = discoverDaemon(contextId);\n }\n\n if (!daemon) {\n const msg = `kbdb worker daemon did not start: ${readCrashReason(contextId)}`;\n log(msg, LogLevel.ERROR);\n throw new Error(msg);\n }\n\n log('connecting to daemon', LogLevel.DEBUG);\n const client = new WorkerClient(\n socketPath,\n contextId,\n options?.requestTimeoutMs,\n );\n await client.connect();\n return client;\n}\n\nfunction readCrashReason(contextId: string): string {\n const crashPath = join(tmpdir(), `kbdb-${contextId}.crash`);\n if (!existsSync(crashPath)) {\n return 'daemon failed to start (no details available)';\n }\n try {\n const raw = readFileSync(crashPath, 'utf-8');\n const crash = JSON.parse(raw) as { error?: string };\n unlinkSync(crashPath);\n return crash.error ?? 'unknown error (crash log empty)';\n } catch {\n return 'daemon failed to start (crash log unreadable)';\n }\n}\n", "import { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { log } from '../../log/functions/log.function.ts';\nimport { LogLevel } from '../../log/typings/log-level.type.ts';\n\n/**\n * Resolves the absolute path to the `.kbdb` database directory.\n *\n * Searches for a `.kbdb` sub-directory inside `targetDir`. When\n * `targetDir` is omitted, `process.cwd()` is used as the base.\n *\n * @param targetDir - directory to search in; defaults to cwd\n * @throws {Error} if no `.kbdb` directory exists at the resolved\n * path\n */\nexport function resolveDbPath(targetDir?: string): string {\n const base = targetDir ? resolve(targetDir) : process.cwd();\n const dbPath = join(base, '.kbdb');\n if (!existsSync(dbPath)) {\n const msg = `database not found: ${dbPath}`;\n log(msg, LogLevel.ERROR);\n throw new Error(msg);\n }\n return dbPath;\n}\n", "/**\n * Computes the SHA-256 hash of a UTF-8 string.\n *\n * Uses the Web Crypto API (`crypto.subtle`), which is available\n * in both Deno and Node.js >= 20 without additional imports.\n *\n * @param input - the string to hash\n * @returns lowercase hex-encoded SHA-256 digest (64 characters)\n */\nexport async function computeSha256(input: string): Promise<string> {\n const data = new TextEncoder().encode(input);\n const hash = await crypto.subtle.digest('SHA-256', data);\n const bytes = new Uint8Array(hash);\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n", "import { computeSha256 } from '../../hash/functions/compute-sha256.ts';\n\n/**\n * Computes a short context identifier for an absolute path.\n *\n * Hashes the path with SHA-256 and returns the first 16 hex\n * characters. The result is stable for the same input and unique\n * enough to avoid accidental collisions across typical path sets.\n *\n * @param absolutePath - the absolute filesystem path to identify\n * @returns a 16-character lowercase hex string\n */\nexport async function computeContextId(\n absolutePath: string,\n): Promise<string> {\n const hash = await computeSha256(absolutePath);\n return hash.slice(0, 16);\n}\n", "import { spawn } from 'node:child_process';\nimport type { Runtime } from '../../runtime/typings/runtime.ts';\nimport { log } from '../../log/functions/log.function.ts';\nimport { LogLevel } from '../../log/typings/log-level.type.ts';\n\n/**\n * Spawns a detached worker daemon process for the given context.\n *\n * @param contextPath - absolute path to the context directory the\n * daemon should serve\n * @param runtime - the current JavaScript runtime environment\n * @param workerScript - absolute path to the worker daemon script,\n * resolved at the entry point by `resolveWorkerScript`\n */\nexport function spawnDaemon(\n contextPath: string,\n runtime: Runtime,\n workerScript?: string,\n): void {\n if (!workerScript) {\n const msg =\n 'workerScript must be provided' + ' (resolve at entry point)';\n log(msg, LogLevel.ERROR);\n throw new Error(msg);\n }\n const execPath = runtime === 'deno' ? 'deno' : process.execPath;\n\n const logLevelEnv = process.env['KBDB_LOG_LEVEL'];\n const logArgs = logLevelEnv ? ['--log-level', logLevelEnv] : [];\n\n const args =\n runtime === 'deno'\n ? ['run', '--allow-all', workerScript, contextPath, ...logArgs]\n : [workerScript, contextPath, ...logArgs];\n\n log(\n 'spawning daemon: ' + execPath + ' ' + args.join(' '),\n LogLevel.DEBUG,\n );\n const child = spawn(execPath, args, {\n detached: true,\n stdio: 'ignore',\n });\n child.unref();\n}\n", "import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { log } from '../../log/functions/log.function.ts';\nimport { LogLevel } from '../../log/typings/log-level.type.ts';\n\n/** Default maximum wait time for the daemon PID file to appear. */\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/** Polling interval in milliseconds between existence checks. */\nconst POLL_INTERVAL_MS = 100;\n\n/**\n * Waits for the worker daemon's PID file to appear on disk.\n *\n * Polls every 100 ms until the PID file at\n * `<tmpdir>/kbdb-<contextId>.pid` exists or the timeout elapses.\n *\n * @param contextId - the 16-character context identifier\n * @param timeoutMs - maximum wait time in milliseconds; defaults\n * to 10 000 ms\n * @returns `true` if the PID file appeared before the timeout,\n * `false` otherwise\n */\nexport async function waitForDaemon(\n contextId: string,\n timeoutMs: number = DEFAULT_TIMEOUT_MS,\n): Promise<boolean> {\n log('waiting for daemon: contextId=' + contextId, LogLevel.DEBUG);\n const pidPath = join(tmpdir(), `kbdb-${contextId}.pid`);\n const start = Date.now();\n let iteration = 0;\n while (Date.now() - start < timeoutMs) {\n if (existsSync(pidPath)) {\n log('daemon PID file appeared', LogLevel.DEBUG);\n return true;\n }\n iteration++;\n if (iteration % 10 === 0) {\n const elapsed = Date.now() - start;\n log(\n 'still waiting for daemon: elapsed=' +\n elapsed.toString() +\n 'ms',\n LogLevel.DEBUG,\n );\n }\n await new Promise<void>((r) => setTimeout(r, POLL_INTERVAL_MS));\n }\n const elapsed = Date.now() - start;\n log(\n 'timed out waiting for daemon: elapsed=' +\n elapsed.toString() +\n 'ms',\n LogLevel.DEBUG,\n );\n return false;\n}\n", "import type { Runtime } from '../typings/runtime.ts';\n\n/**\n * Detects the current JavaScript runtime environment.\n *\n * Returns `'deno'` when the global `Deno` object is present,\n * otherwise returns `'node'`.\n */\nexport function detectRuntime(): Runtime {\n if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {\n return 'deno';\n }\n return 'node';\n}\n", "import { join } from 'node:path';\nimport { getTmpdir } from './get-tmpdir.function.ts';\n\n/**\n * Returns the platform-appropriate IPC socket path for a given\n * context identifier.\n *\n * On Windows, returns a named pipe path (`\\\\.\\pipe\\kbdb-<ctx>`).\n * On POSIX systems, returns a Unix domain socket path under the\n * system temp directory (`<tmpdir>/kbdb-<ctx>.sock`).\n *\n * @param ctx - unique context identifier embedded in the path\n */\nexport function getIpcPath(ctx: string): string {\n if (process.platform === 'win32') {\n return `\\\\\\\\.\\\\pipe\\\\kbdb-${ctx}`;\n }\n return join(getTmpdir(), `kbdb-${ctx}.sock`);\n}\n", "import { tmpdir } from 'node:os';\n\n/**\n * Returns the operating system's default temporary directory path.\n */\nexport function getTmpdir(): string {\n return tmpdir();\n}\n", "import { createWorkerClient } from './create-worker-client.function.ts';\nimport type { WorkerClient } from '../classes/worker-client.class.ts';\nimport type { WorkerClientOptions } from '../typings/worker-client-options.interface.ts';\nimport { resolveDbPath } from './resolve-db-path.function.ts';\nimport { log } from '../../log/functions/log.function.ts';\nimport { LogLevel } from '../../log/typings/log-level.type.ts';\n\n/** Cache of connected clients keyed by database path. */\nconst cache = new Map<string, WorkerClient>();\n\n/**\n * Returns a cached `WorkerClient` for the given context\n * path, or creates and caches a new one if the cached\n * client is disconnected or absent.\n *\n * Intended for library consumers and the MCP server. CLI\n * one-shots should use `createWorkerClient()` directly.\n *\n * @param options - optional configuration forwarded to\n * `createWorkerClient`\n * @returns a connected `WorkerClient`\n */\nexport async function getOrCreateClient(\n options?: WorkerClientOptions,\n): Promise<WorkerClient> {\n log('getOrCreateClient called', LogLevel.DEBUG);\n const dbPath =\n options?.contextPath ?? resolveDbPath(options?.dbPath);\n const cached = cache.get(dbPath);\n if (cached?.isConnected) {\n log('returning cached client for: ' + dbPath, LogLevel.DEBUG);\n return cached;\n }\n cache.delete(dbPath);\n log('creating new client for: ' + dbPath, LogLevel.DEBUG);\n const client = await createWorkerClient(options);\n cache.set(dbPath, client);\n return client;\n}\n\n/**\n * Clears the internal client cache. Intended for tests\n * that need isolation between runs.\n */\nexport function clearClientCache(): void {\n for (const [key, client] of cache) {\n client.disconnect();\n cache.delete(key);\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,UAAU;;;ACDvB,sBAAwB;;;ACAxB,qBAAqD;AACrD,uBAAqB;AACrB,qBAAuB;;;ACOhB,SAAS,eAAe,KAAsB;AAClD,MAAI;AACD,YAAQ,KAAK,KAAK,CAAC;AACnB,WAAO;AAAA,EACV,QAAQ;AACL,WAAO;AAAA,EACV;AACH;;;ACfO,IAAK,WAAL,kBAAKA,cAAL;AACJ,EAAAA,oBAAA,WAAQ,KAAR;AACA,EAAAA,oBAAA,UAAO,KAAP;AACA,EAAAA,oBAAA,aAAU,KAAV;AACA,EAAAA,oBAAA,WAAQ,KAAR;AAJS,SAAAA;AAAA,GAAA;;;ACE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AA,EACV;AACA,QAAM,OAAO,MAAM;AACnB,MAAI,8BAA8B,qBAAsB;AACxD,QAAM,SAAS,MAAM,mBAAmB,OAAO;AAC/C,QAAM,IAAI,QAAQ,MAAM;AACxB,SAAO;AACV;",
|
|
6
|
+
"names": ["LogLevel", "resolve", "import_node_fs", "import_node_path", "import_node_os", "import_node_fs", "import_node_path", "import_node_fs", "import_node_path", "import_node_os", "elapsed", "import_node_path", "import_node_os"]
|
|
7
7
|
}
|