inkdex 0.0.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.
Files changed (55) hide show
  1. package/.claude/settings.local.json +15 -0
  2. package/.github/workflows/ci.yml +73 -0
  3. package/.github/workflows/release.yml +65 -0
  4. package/AGENTS.md +32 -0
  5. package/LICENSE +190 -0
  6. package/README.md +40 -0
  7. package/biome.json +43 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.js +38 -0
  10. package/dist/embedder/embedder.d.ts +9 -0
  11. package/dist/embedder/embedder.js +39 -0
  12. package/dist/ingest/chunker.d.ts +7 -0
  13. package/dist/ingest/chunker.js +114 -0
  14. package/dist/ingest/index-docs.d.ts +2 -0
  15. package/dist/ingest/index-docs.js +78 -0
  16. package/dist/logger.d.ts +6 -0
  17. package/dist/logger.js +28 -0
  18. package/dist/search/search.d.ts +7 -0
  19. package/dist/search/search.js +70 -0
  20. package/dist/server.d.ts +2 -0
  21. package/dist/server.js +66 -0
  22. package/dist/store/db.d.ts +13 -0
  23. package/dist/store/db.js +149 -0
  24. package/dist/types.d.ts +14 -0
  25. package/dist/types.js +1 -0
  26. package/dist/version.d.ts +1 -0
  27. package/dist/version.js +13 -0
  28. package/inkdex-0.0.1.tgz +0 -0
  29. package/package.json +46 -0
  30. package/release.sh +33 -0
  31. package/src/cli.ts +45 -0
  32. package/src/embedder/embedder.ts +52 -0
  33. package/src/ingest/chunker.ts +158 -0
  34. package/src/ingest/index-docs.ts +120 -0
  35. package/src/logger.ts +39 -0
  36. package/src/search/search.ts +93 -0
  37. package/src/server.ts +96 -0
  38. package/src/store/db.ts +217 -0
  39. package/src/types.ts +16 -0
  40. package/src/version.ts +16 -0
  41. package/test/fixtures/docs/api.md +26 -0
  42. package/test/fixtures/docs/getting-started.md +13 -0
  43. package/test/helpers/index.ts +14 -0
  44. package/test/integration/embedder.test.ts +52 -0
  45. package/test/integration/server.test.ts +125 -0
  46. package/test/unit/chunker.test.ts +193 -0
  47. package/test/unit/db.test.ts +190 -0
  48. package/test/unit/index-docs.test.ts +120 -0
  49. package/test/unit/logger.test.ts +11 -0
  50. package/test/unit/search.test.ts +93 -0
  51. package/test/unit/version.test.ts +16 -0
  52. package/test-docs/api-reference.md +76 -0
  53. package/test-docs/deployment.md +55 -0
  54. package/test-docs/getting-started.md +52 -0
  55. package/tsconfig.json +18 -0
@@ -0,0 +1,15 @@
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "WebFetch(domain:github.com)",
5
+ "mcp__acp__Bash",
6
+ "mcp__acp__Write",
7
+ "mcp__acp__Edit",
8
+ "WebFetch(domain:raw.githubusercontent.com)",
9
+ "WebFetch(domain:api.github.com)",
10
+ "WebFetch(domain:www.firecrawl.dev)",
11
+ "WebFetch(domain:unstructured.io)",
12
+ "WebFetch(domain:www.npmjs.com)"
13
+ ]
14
+ }
15
+ }
@@ -0,0 +1,73 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ paths:
7
+ - "src/**"
8
+ - "test/**"
9
+ - "package.json"
10
+ - "package-lock.json"
11
+ - "tsconfig.json"
12
+ - ".github/workflows/**"
13
+ pull_request:
14
+ branches: [main]
15
+ paths:
16
+ - "src/**"
17
+ - "test/**"
18
+ - "package.json"
19
+ - "package-lock.json"
20
+ - "tsconfig.json"
21
+ - ".github/workflows/**"
22
+
23
+ jobs:
24
+ audit:
25
+ name: Security Audit
26
+ runs-on: ubuntu-latest
27
+ steps:
28
+ - uses: actions/checkout@v5
29
+
30
+ - uses: actions/setup-node@v6
31
+ with:
32
+ node-version: "22"
33
+
34
+ - run: npm audit --audit-level=critical
35
+
36
+ check:
37
+ name: Lint & Format
38
+ runs-on: ubuntu-latest
39
+ steps:
40
+ - uses: actions/checkout@v5
41
+
42
+ - uses: actions/setup-node@v6
43
+ with:
44
+ node-version: "22"
45
+
46
+ - run: npm ci
47
+ - run: npm run check
48
+
49
+ test-unit:
50
+ name: Unit Tests
51
+ runs-on: ubuntu-latest
52
+ steps:
53
+ - uses: actions/checkout@v5
54
+
55
+ - uses: actions/setup-node@v6
56
+ with:
57
+ node-version: "22"
58
+
59
+ - run: npm ci
60
+ - run: npm run test:unit
61
+
62
+ test-integration:
63
+ name: Integration Tests
64
+ runs-on: ubuntu-latest
65
+ steps:
66
+ - uses: actions/checkout@v5
67
+
68
+ - uses: actions/setup-node@v6
69
+ with:
70
+ node-version: "22"
71
+
72
+ - run: npm ci
73
+ - run: npm run test:integration
@@ -0,0 +1,65 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "v*"
7
+
8
+ permissions:
9
+ contents: write
10
+ id-token: write
11
+
12
+ jobs:
13
+ check:
14
+ name: Check
15
+ runs-on: ubuntu-latest
16
+ steps:
17
+ - uses: actions/checkout@v5
18
+
19
+ - uses: actions/setup-node@v6
20
+ with:
21
+ node-version: "22"
22
+
23
+ - run: npm ci
24
+ - run: npm run check
25
+
26
+ test:
27
+ name: Test
28
+ runs-on: ubuntu-latest
29
+ steps:
30
+ - uses: actions/checkout@v5
31
+
32
+ - uses: actions/setup-node@v6
33
+ with:
34
+ node-version: "22"
35
+
36
+ - run: npm ci
37
+ - run: npm run test
38
+
39
+ npm:
40
+ name: npm
41
+ needs: [check, test]
42
+ runs-on: ubuntu-latest
43
+ steps:
44
+ - uses: actions/checkout@v5
45
+
46
+ - uses: actions/setup-node@v6
47
+ with:
48
+ node-version: "22"
49
+ registry-url: "https://registry.npmjs.org"
50
+
51
+ - run: npm install -g npm@latest
52
+ - run: npm ci
53
+ - run: npm run build
54
+ - run: npm publish --access public --provenance
55
+
56
+ release:
57
+ name: Release
58
+ needs: [npm]
59
+ runs-on: ubuntu-latest
60
+ steps:
61
+ - uses: actions/checkout@v5
62
+
63
+ - uses: softprops/action-gh-release@v2
64
+ with:
65
+ generate_release_notes: true
package/AGENTS.md ADDED
@@ -0,0 +1,32 @@
1
+ # AGENTS.md
2
+
3
+ - Use [Conventional Commits](https://www.conventionalcommits.org/) (`feat:`, `fix:`, `chore:`, `docs:`)
4
+
5
+ ## General Coding Guidelines
6
+
7
+ - Maintain consistency with existing patterns and style in the codebase
8
+ - Use TypeScript strictly: enable `strict: true`, prefer `unknown` over `any`, avoid type assertions unless necessary
9
+ - Write comments that explain *why*, not *what*—update or remove stale comments when modifying code
10
+ - Prefer renaming over commenting: if code needs a comment to explain what it does, rename instead
11
+ - Use JSDoc (`/** */`) only for exported functions/types; use `//` for implementation notes
12
+ - Use `@package` on exports internal to their feature package
13
+ - Include `@example` in JSDoc when input/output isn't obvious from the signature
14
+ - No commented-out code, no TODO/FIXME without a linked issue
15
+ - Naming: camelCase functions/variables, PascalCase types/classes, UPPER_SNAKE_CASE constants; prefix booleans with `is`/`has`/`should`
16
+ - Keep functions focused and single-responsibility; favor immutable patterns (`readonly`, no mutation)
17
+ - Handle errors consistently: prefer typed errors or Result patterns, handle promise rejections explicitly
18
+ - Use modern syntax: optional chaining (`?.`), nullish coalescing (`??`), `satisfies`, ES modules
19
+ - After refactoring, run `npm run test` to verify tests pass and coverage requirements are met
20
+ - Write tests covering happy path, edge cases, and error conditions with descriptive names
21
+ - Test should validate observable behavior not implementation details
22
+
23
+ ## Development
24
+
25
+ ```bash
26
+ npm install
27
+ npm run build # TypeScript compilation
28
+ npm run dev # Run via tsx
29
+ npm run check # Biome lint
30
+ npm run format # Biome format
31
+ npm test # Unit + integration
32
+ ```
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Anton Lundén
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,40 @@
1
+ # Inkdex
2
+
3
+ Inkdex is a MCP server that makes your markdown docs searchable for AI. Point it at your docs directory, get hybrid search (text + vector) powered by local AI embeddings.
4
+
5
+ ## Tools
6
+
7
+ | Tool | Description |
8
+ |------|-------------|
9
+ | `search_docs` | Search indexed documentation. Returns matching chunks ranked by relevance. |
10
+
11
+ ## Usage
12
+
13
+ Add to your MCP client configuration:
14
+
15
+ ```json
16
+ {
17
+ "mcpServers": {
18
+ "inkdex": {
19
+ "command": "npx",
20
+ "args": [
21
+ "-y",
22
+ "inkdex"
23
+ ],
24
+ "env": {
25
+ "DOCS_PATH": "/path/to/your/docs"
26
+ }
27
+ }
28
+ }
29
+ }
30
+ ```
31
+
32
+ | Variable | Required | Description |
33
+ |----------|----------|-------------|
34
+ | `DOCS_PATH` | Yes | Path to the directory containing markdown files to index |
35
+
36
+ To expose docs remotely, use a MCP gateway like [MCPBox](https://github.com/kandobyte/mcpbox).
37
+
38
+ ## How it works
39
+
40
+ Documents are split along heading boundaries with overlap to preserve context. Chunks are embedded locally and stored in SQLite for hybrid retrieval. Indexing runs on startup and is incremental — only changed files are re-processed.
package/biome.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "$schema": "https://biomejs.dev/schemas/2.3.14/schema.json",
3
+ "vcs": {
4
+ "enabled": true,
5
+ "clientKind": "git",
6
+ "useIgnoreFile": true
7
+ },
8
+ "assist": { "actions": { "source": { "organizeImports": "on" } } },
9
+ "formatter": {
10
+ "indentStyle": "space",
11
+ "indentWidth": 2
12
+ },
13
+ "linter": {
14
+ "enabled": true,
15
+ "rules": {
16
+ "recommended": true,
17
+ "suspicious": {
18
+ "noExplicitAny": "error"
19
+ },
20
+ "performance": {
21
+ "noDelete": "off"
22
+ },
23
+ "correctness": {
24
+ "noPrivateImports": "error"
25
+ }
26
+ }
27
+ },
28
+ "overrides": [
29
+ {
30
+ "includes": ["test/**"],
31
+ "linter": {
32
+ "rules": {
33
+ "correctness": {
34
+ "noPrivateImports": "off"
35
+ }
36
+ }
37
+ }
38
+ }
39
+ ],
40
+ "files": {
41
+ "includes": ["**", "!**/dist", "!**/node_modules"]
42
+ }
43
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ import { stat } from "node:fs/promises";
3
+ import { resolve } from "node:path";
4
+ import { Embedder } from "./embedder/embedder.js";
5
+ import { indexDocs } from "./ingest/index-docs.js";
6
+ import { logger } from "./logger.js";
7
+ import { startServer } from "./server.js";
8
+ import { closeDb, openDb } from "./store/db.js";
9
+ process.on("uncaughtException", (error) => {
10
+ logger.error({ error }, "Uncaught exception");
11
+ process.exit(1);
12
+ });
13
+ process.on("unhandledRejection", (reason) => {
14
+ logger.error({ reason }, "Unhandled rejection");
15
+ process.exit(1);
16
+ });
17
+ async function main() {
18
+ const docsPath = process.env.DOCS_PATH;
19
+ if (!docsPath) {
20
+ logger.error("DOCS_PATH environment variable is required");
21
+ process.exit(1);
22
+ }
23
+ const resolved = resolve(docsPath);
24
+ const info = await stat(resolved).catch(() => null);
25
+ if (!info?.isDirectory()) {
26
+ logger.error({ path: resolved }, "DOCS_PATH is not a directory");
27
+ process.exit(1);
28
+ }
29
+ const embedder = await Embedder.load();
30
+ openDb(resolved);
31
+ await indexDocs(embedder, resolved);
32
+ await startServer(embedder);
33
+ }
34
+ main().catch((error) => {
35
+ closeDb();
36
+ logger.error({ error }, "Failed to start server");
37
+ process.exit(1);
38
+ });
@@ -0,0 +1,9 @@
1
+ export declare class Embedder {
2
+ readonly maxTokens: number;
3
+ private readonly pipeline;
4
+ private constructor();
5
+ static load(): Promise<Embedder>;
6
+ tokenize(text: string): number[];
7
+ embed(text: string): Promise<number[]>;
8
+ embedBatch(texts: string[]): Promise<number[][]>;
9
+ }
@@ -0,0 +1,39 @@
1
+ import { pipeline } from "@huggingface/transformers";
2
+ const MODEL = "Xenova/all-MiniLM-L6-v2";
3
+ const BATCH_SIZE = 32;
4
+ export class Embedder {
5
+ maxTokens;
6
+ pipeline;
7
+ constructor(pipe) {
8
+ this.pipeline = pipe;
9
+ this.maxTokens = pipe.tokenizer.model_max_length ?? 256;
10
+ }
11
+ static async load() {
12
+ const pipe = await pipeline("feature-extraction", MODEL);
13
+ return new Embedder(pipe);
14
+ }
15
+ tokenize(text) {
16
+ return this.pipeline.tokenizer.encode(text);
17
+ }
18
+ async embed(text) {
19
+ const result = await this.pipeline(text, {
20
+ pooling: "mean",
21
+ normalize: true,
22
+ });
23
+ return result.tolist()[0];
24
+ }
25
+ async embedBatch(texts) {
26
+ if (texts.length === 0)
27
+ return [];
28
+ const results = [];
29
+ for (let i = 0; i < texts.length; i += BATCH_SIZE) {
30
+ const batch = texts.slice(i, i + BATCH_SIZE);
31
+ const result = await this.pipeline(batch, {
32
+ pooling: "mean",
33
+ normalize: true,
34
+ });
35
+ results.push(...result.tolist());
36
+ }
37
+ return results;
38
+ }
39
+ }
@@ -0,0 +1,7 @@
1
+ import type { BaseChunk } from "../types.js";
2
+ export interface ChunkOptions {
3
+ readonly maxTokens: number;
4
+ readonly countTokens: (text: string) => number;
5
+ }
6
+ /** @package */
7
+ export declare function chunkMarkdown(content: string, path: string, options: ChunkOptions): BaseChunk[];
@@ -0,0 +1,114 @@
1
+ import { basename } from "node:path";
2
+ import matter from "gray-matter";
3
+ const OVERLAP_RATIO = 0.1;
4
+ const SUB_SEPARATORS = [/^### /m, /\n\n/, /\. /];
5
+ function extractH1(body) {
6
+ const match = body.match(/^# (.+)$/m);
7
+ return match ? match[1].trim() : null;
8
+ }
9
+ function clean(text) {
10
+ return text
11
+ .replace(/<!--.*?-->/gs, "")
12
+ .replace(/\n{3,}/g, "\n\n")
13
+ .trim();
14
+ }
15
+ function splitWithOverlap(text, separators, maxTokens, overlap, countTokens) {
16
+ if (countTokens(text) <= maxTokens)
17
+ return [text];
18
+ const separator = separators[0];
19
+ const remaining = separators.slice(1);
20
+ const parts = text.split(separator).filter((p) => p.trim());
21
+ if (parts.length <= 1) {
22
+ // Separator didn't help — try the next one
23
+ if (remaining.length > 0) {
24
+ return splitWithOverlap(text, remaining, maxTokens, overlap, countTokens);
25
+ }
26
+ // Last resort: hard split
27
+ return hardSplit(text, maxTokens, overlap, countTokens);
28
+ }
29
+ const chunks = [];
30
+ let current = "";
31
+ for (const part of parts) {
32
+ const combined = current ? `${current}\n\n${part}` : part;
33
+ if (current && countTokens(combined) > maxTokens) {
34
+ chunks.push(current.trim());
35
+ // Start next chunk with overlap from the end of the previous
36
+ const overlapText = current.slice(-overlap);
37
+ current = overlapText + part;
38
+ }
39
+ else {
40
+ current = combined;
41
+ }
42
+ }
43
+ if (current.trim())
44
+ chunks.push(current.trim());
45
+ // Recursively split any chunks that are still too large
46
+ return chunks.flatMap((chunk) => {
47
+ if (countTokens(chunk) <= maxTokens)
48
+ return [chunk];
49
+ if (remaining.length > 0) {
50
+ return splitWithOverlap(chunk, remaining, maxTokens, overlap, countTokens);
51
+ }
52
+ return hardSplit(chunk, maxTokens, overlap, countTokens);
53
+ });
54
+ }
55
+ function hardSplit(text, maxTokens, overlap, countTokens) {
56
+ const chunks = [];
57
+ const words = text.split(/\s+/);
58
+ let current = "";
59
+ for (const word of words) {
60
+ const next = current ? `${current} ${word}` : word;
61
+ if (countTokens(next) > maxTokens && current) {
62
+ chunks.push(current.trim());
63
+ // Keep overlap from end of current chunk
64
+ const overlapText = current.slice(-overlap);
65
+ current = overlapText + word;
66
+ }
67
+ else {
68
+ current = next;
69
+ }
70
+ }
71
+ if (current.trim())
72
+ chunks.push(current.trim());
73
+ return chunks;
74
+ }
75
+ /** @package */
76
+ export function chunkMarkdown(content, path, options) {
77
+ const { maxTokens, countTokens } = options;
78
+ const overlap = Math.floor(maxTokens * OVERLAP_RATIO);
79
+ const { data: metadata, content: body } = matter(content);
80
+ const fileHeading = extractH1(body) || basename(path, ".md");
81
+ const sections = body.split(/^## /m);
82
+ const chunks = [];
83
+ for (let i = 0; i < sections.length; i++) {
84
+ const section = sections[i];
85
+ if (!section.trim())
86
+ continue;
87
+ let heading;
88
+ let text;
89
+ if (i === 0) {
90
+ // Content before the first ## — strip the H1 line and use fileHeading
91
+ heading = fileHeading;
92
+ const withoutH1 = section.replace(/^# .+$/m, "");
93
+ text = clean(withoutH1);
94
+ }
95
+ else {
96
+ const [headingLine, ...rest] = section.split("\n");
97
+ heading = headingLine.trim();
98
+ text = clean(rest.join("\n"));
99
+ }
100
+ if (!text)
101
+ continue;
102
+ const subChunks = splitWithOverlap(text, SUB_SEPARATORS, maxTokens, overlap, countTokens);
103
+ for (const sub of subChunks) {
104
+ chunks.push({
105
+ path,
106
+ fileHeading,
107
+ heading,
108
+ text: sub,
109
+ metadata,
110
+ });
111
+ }
112
+ }
113
+ return chunks;
114
+ }
@@ -0,0 +1,2 @@
1
+ import type { Embedder } from "../embedder/embedder.js";
2
+ export declare function indexDocs(embedder: Embedder, docsPath: string): Promise<void>;