@contextstream/mcp-server 0.4.82 → 1.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.
@@ -1,1023 +0,0 @@
1
- #!/usr/bin/env node
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __commonJS = (cb, mod) => function __require() {
9
- try {
10
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
- } catch (e) {
12
- throw mod = 0, e;
13
- }
14
- };
15
- var __copyProps = (to, from, except, desc) => {
16
- if (from && typeof from === "object" || typeof from === "function") {
17
- for (let key of __getOwnPropNames(from))
18
- if (!__hasOwnProp.call(to, key) && key !== except)
19
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
- }
21
- return to;
22
- };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
- // If the importer is in node compatibility mode or this is not an ESM
25
- // file that has been converted to a CommonJS file using a Babel-
26
- // compatible transform (i.e. "__esModule" has not been set), then set
27
- // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
- mod
30
- ));
31
-
32
- // node_modules/ignore/index.js
33
- var require_ignore = __commonJS({
34
- "node_modules/ignore/index.js"(exports, module) {
35
- function makeArray(subject) {
36
- return Array.isArray(subject) ? subject : [subject];
37
- }
38
- var UNDEFINED = void 0;
39
- var EMPTY = "";
40
- var SPACE = " ";
41
- var ESCAPE = "\\";
42
- var REGEX_TEST_BLANK_LINE = /^\s+$/;
43
- var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
44
- var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
45
- var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
46
- var REGEX_SPLITALL_CRLF = /\r?\n/g;
47
- var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
48
- var REGEX_TEST_TRAILING_SLASH = /\/$/;
49
- var SLASH = "/";
50
- var TMP_KEY_IGNORE = "node-ignore";
51
- if (typeof Symbol !== "undefined") {
52
- TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
53
- }
54
- var KEY_IGNORE = TMP_KEY_IGNORE;
55
- var define = (object, key, value) => {
56
- Object.defineProperty(object, key, { value });
57
- return value;
58
- };
59
- var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
60
- var RETURN_FALSE = () => false;
61
- var sanitizeRange = (range) => range.replace(
62
- REGEX_REGEXP_RANGE,
63
- (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match : EMPTY
64
- );
65
- var cleanRangeBackSlash = (slashes) => {
66
- const { length } = slashes;
67
- return slashes.slice(0, length - length % 2);
68
- };
69
- var REPLACERS = [
70
- [
71
- // Remove BOM
72
- // TODO:
73
- // Other similar zero-width characters?
74
- /^\uFEFF/,
75
- () => EMPTY
76
- ],
77
- // > Trailing spaces are ignored unless they are quoted with backslash ("\")
78
- [
79
- // (a\ ) -> (a )
80
- // (a ) -> (a)
81
- // (a ) -> (a)
82
- // (a \ ) -> (a )
83
- /((?:\\\\)*?)(\\?\s+)$/,
84
- (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE : EMPTY)
85
- ],
86
- // Replace (\ ) with ' '
87
- // (\ ) -> ' '
88
- // (\\ ) -> '\\ '
89
- // (\\\ ) -> '\\ '
90
- [
91
- /(\\+?)\s/g,
92
- (_, m1) => {
93
- const { length } = m1;
94
- return m1.slice(0, length - length % 2) + SPACE;
95
- }
96
- ],
97
- // Escape metacharacters
98
- // which is written down by users but means special for regular expressions.
99
- // > There are 12 characters with special meanings:
100
- // > - the backslash \,
101
- // > - the caret ^,
102
- // > - the dollar sign $,
103
- // > - the period or dot .,
104
- // > - the vertical bar or pipe symbol |,
105
- // > - the question mark ?,
106
- // > - the asterisk or star *,
107
- // > - the plus sign +,
108
- // > - the opening parenthesis (,
109
- // > - the closing parenthesis ),
110
- // > - and the opening square bracket [,
111
- // > - the opening curly brace {,
112
- // > These special characters are often called "metacharacters".
113
- [
114
- /[\\$.|*+(){^]/g,
115
- (match) => `\\${match}`
116
- ],
117
- [
118
- // > a question mark (?) matches a single character
119
- /(?!\\)\?/g,
120
- () => "[^/]"
121
- ],
122
- // leading slash
123
- [
124
- // > A leading slash matches the beginning of the pathname.
125
- // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
126
- // A leading slash matches the beginning of the pathname
127
- /^\//,
128
- () => "^"
129
- ],
130
- // replace special metacharacter slash after the leading slash
131
- [
132
- /\//g,
133
- () => "\\/"
134
- ],
135
- [
136
- // > A leading "**" followed by a slash means match in all directories.
137
- // > For example, "**/foo" matches file or directory "foo" anywhere,
138
- // > the same as pattern "foo".
139
- // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
140
- // > under directory "foo".
141
- // Notice that the '*'s have been replaced as '\\*'
142
- /^\^*\\\*\\\*\\\//,
143
- // '**/foo' <-> 'foo'
144
- () => "^(?:.*\\/)?"
145
- ],
146
- // starting
147
- [
148
- // there will be no leading '/'
149
- // (which has been replaced by section "leading slash")
150
- // If starts with '**', adding a '^' to the regular expression also works
151
- /^(?=[^^])/,
152
- function startingReplacer() {
153
- return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^";
154
- }
155
- ],
156
- // two globstars
157
- [
158
- // Use lookahead assertions so that we could match more than one `'/**'`
159
- /\\\/\\\*\\\*(?=\\\/|$)/g,
160
- // Zero, one or several directories
161
- // should not use '*', or it will be replaced by the next replacer
162
- // Check if it is not the last `'/**'`
163
- (_, index, str) => index + 6 < str.length ? "(?:\\/[^\\/]+)*" : "\\/.+"
164
- ],
165
- // normal intermediate wildcards
166
- [
167
- // Never replace escaped '*'
168
- // ignore rule '\*' will match the path '*'
169
- // 'abc.*/' -> go
170
- // 'abc.*' -> skip this rule,
171
- // coz trailing single wildcard will be handed by [trailing wildcard]
172
- /(^|[^\\]+)(\\\*)+(?=.+)/g,
173
- // '*.js' matches '.js'
174
- // '*.js' doesn't match 'abc'
175
- (_, p1, p2) => {
176
- const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
177
- return p1 + unescaped;
178
- }
179
- ],
180
- [
181
- // unescape, revert step 3 except for back slash
182
- // For example, if a user escape a '\\*',
183
- // after step 3, the result will be '\\\\\\*'
184
- /\\\\\\(?=[$.|*+(){^])/g,
185
- () => ESCAPE
186
- ],
187
- [
188
- // '\\\\' -> '\\'
189
- /\\\\/g,
190
- () => ESCAPE
191
- ],
192
- [
193
- // > The range notation, e.g. [a-zA-Z],
194
- // > can be used to match one of the characters in a range.
195
- // `\` is escaped by step 3
196
- /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
197
- (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]"
198
- ],
199
- // ending
200
- [
201
- // 'js' will not match 'js.'
202
- // 'ab' will not match 'abc'
203
- /(?:[^*])$/,
204
- // WTF!
205
- // https://git-scm.com/docs/gitignore
206
- // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
207
- // which re-fixes #24, #38
208
- // > If there is a separator at the end of the pattern then the pattern
209
- // > will only match directories, otherwise the pattern can match both
210
- // > files and directories.
211
- // 'js*' will not match 'a.js'
212
- // 'js/' will not match 'a.js'
213
- // 'js' will match 'a.js' and 'a.js/'
214
- (match) => /\/$/.test(match) ? `${match}$` : `${match}(?=$|\\/$)`
215
- ]
216
- ];
217
- var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\\\*$/;
218
- var MODE_IGNORE = "regex";
219
- var MODE_CHECK_IGNORE = "checkRegex";
220
- var UNDERSCORE = "_";
221
- var TRAILING_WILD_CARD_REPLACERS = {
222
- [MODE_IGNORE](_, p1) {
223
- const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
224
- return `${prefix}(?=$|\\/$)`;
225
- },
226
- [MODE_CHECK_IGNORE](_, p1) {
227
- const prefix = p1 ? `${p1}[^/]*` : "[^/]*";
228
- return `${prefix}(?=$|\\/$)`;
229
- }
230
- };
231
- var makeRegexPrefix = (pattern) => REPLACERS.reduce(
232
- (prev, [matcher, replacer]) => prev.replace(matcher, replacer.bind(pattern)),
233
- pattern
234
- );
235
- var isString = (subject) => typeof subject === "string";
236
- var checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
237
- var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean);
238
- var IgnoreRule = class {
239
- constructor(pattern, mark, body, ignoreCase, negative, prefix) {
240
- this.pattern = pattern;
241
- this.mark = mark;
242
- this.negative = negative;
243
- define(this, "body", body);
244
- define(this, "ignoreCase", ignoreCase);
245
- define(this, "regexPrefix", prefix);
246
- }
247
- get regex() {
248
- const key = UNDERSCORE + MODE_IGNORE;
249
- if (this[key]) {
250
- return this[key];
251
- }
252
- return this._make(MODE_IGNORE, key);
253
- }
254
- get checkRegex() {
255
- const key = UNDERSCORE + MODE_CHECK_IGNORE;
256
- if (this[key]) {
257
- return this[key];
258
- }
259
- return this._make(MODE_CHECK_IGNORE, key);
260
- }
261
- _make(mode, key) {
262
- const str = this.regexPrefix.replace(
263
- REGEX_REPLACE_TRAILING_WILDCARD,
264
- // It does not need to bind pattern
265
- TRAILING_WILD_CARD_REPLACERS[mode]
266
- );
267
- const regex = this.ignoreCase ? new RegExp(str, "i") : new RegExp(str);
268
- return define(this, key, regex);
269
- }
270
- };
271
- var createRule = ({
272
- pattern,
273
- mark
274
- }, ignoreCase) => {
275
- let negative = false;
276
- let body = pattern;
277
- if (body.indexOf("!") === 0) {
278
- negative = true;
279
- body = body.substr(1);
280
- }
281
- body = body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
282
- const regexPrefix = makeRegexPrefix(body);
283
- return new IgnoreRule(
284
- pattern,
285
- mark,
286
- body,
287
- ignoreCase,
288
- negative,
289
- regexPrefix
290
- );
291
- };
292
- var RuleManager = class {
293
- constructor(ignoreCase) {
294
- this._ignoreCase = ignoreCase;
295
- this._rules = [];
296
- }
297
- _add(pattern) {
298
- if (pattern && pattern[KEY_IGNORE]) {
299
- this._rules = this._rules.concat(pattern._rules._rules);
300
- this._added = true;
301
- return;
302
- }
303
- if (isString(pattern)) {
304
- pattern = {
305
- pattern
306
- };
307
- }
308
- if (checkPattern(pattern.pattern)) {
309
- const rule = createRule(pattern, this._ignoreCase);
310
- this._added = true;
311
- this._rules.push(rule);
312
- }
313
- }
314
- // @param {Array<string> | string | Ignore} pattern
315
- add(pattern) {
316
- this._added = false;
317
- makeArray(
318
- isString(pattern) ? splitPattern(pattern) : pattern
319
- ).forEach(this._add, this);
320
- return this._added;
321
- }
322
- // Test one single path without recursively checking parent directories
323
- //
324
- // - checkUnignored `boolean` whether should check if the path is unignored,
325
- // setting `checkUnignored` to `false` could reduce additional
326
- // path matching.
327
- // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
328
- // @returns {TestResult} true if a file is ignored
329
- test(path3, checkUnignored, mode) {
330
- let ignored = false;
331
- let unignored = false;
332
- let matchedRule;
333
- this._rules.forEach((rule) => {
334
- const { negative } = rule;
335
- if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
336
- return;
337
- }
338
- const matched = rule[mode].test(path3);
339
- if (!matched) {
340
- return;
341
- }
342
- ignored = !negative;
343
- unignored = negative;
344
- matchedRule = negative ? UNDEFINED : rule;
345
- });
346
- const ret = {
347
- ignored,
348
- unignored
349
- };
350
- if (matchedRule) {
351
- ret.rule = matchedRule;
352
- }
353
- return ret;
354
- }
355
- };
356
- var throwError = (message, Ctor) => {
357
- throw new Ctor(message);
358
- };
359
- var checkPath = (path3, originalPath, doThrow) => {
360
- if (!isString(path3)) {
361
- return doThrow(
362
- `path must be a string, but got \`${originalPath}\``,
363
- TypeError
364
- );
365
- }
366
- if (!path3) {
367
- return doThrow(`path must not be empty`, TypeError);
368
- }
369
- if (checkPath.isNotRelative(path3)) {
370
- const r = "`path.relative()`d";
371
- return doThrow(
372
- `path should be a ${r} string, but got "${originalPath}"`,
373
- RangeError
374
- );
375
- }
376
- return true;
377
- };
378
- var isNotRelative = (path3) => REGEX_TEST_INVALID_PATH.test(path3);
379
- checkPath.isNotRelative = isNotRelative;
380
- checkPath.convert = (p) => p;
381
- var Ignore2 = class {
382
- constructor({
383
- ignorecase = true,
384
- ignoreCase = ignorecase,
385
- allowRelativePaths = false
386
- } = {}) {
387
- define(this, KEY_IGNORE, true);
388
- this._rules = new RuleManager(ignoreCase);
389
- this._strictPathCheck = !allowRelativePaths;
390
- this._initCache();
391
- }
392
- _initCache() {
393
- this._ignoreCache = /* @__PURE__ */ Object.create(null);
394
- this._testCache = /* @__PURE__ */ Object.create(null);
395
- }
396
- add(pattern) {
397
- if (this._rules.add(pattern)) {
398
- this._initCache();
399
- }
400
- return this;
401
- }
402
- // legacy
403
- addPattern(pattern) {
404
- return this.add(pattern);
405
- }
406
- // @returns {TestResult}
407
- _test(originalPath, cache, checkUnignored, slices) {
408
- const path3 = originalPath && checkPath.convert(originalPath);
409
- checkPath(
410
- path3,
411
- originalPath,
412
- this._strictPathCheck ? throwError : RETURN_FALSE
413
- );
414
- return this._t(path3, cache, checkUnignored, slices);
415
- }
416
- checkIgnore(path3) {
417
- if (!REGEX_TEST_TRAILING_SLASH.test(path3)) {
418
- return this.test(path3);
419
- }
420
- const slices = path3.split(SLASH).filter(Boolean);
421
- slices.pop();
422
- if (slices.length) {
423
- const parent = this._t(
424
- slices.join(SLASH) + SLASH,
425
- this._testCache,
426
- true,
427
- slices
428
- );
429
- if (parent.ignored) {
430
- return parent;
431
- }
432
- }
433
- return this._rules.test(path3, false, MODE_CHECK_IGNORE);
434
- }
435
- _t(path3, cache, checkUnignored, slices) {
436
- if (path3 in cache) {
437
- return cache[path3];
438
- }
439
- if (!slices) {
440
- slices = path3.split(SLASH).filter(Boolean);
441
- }
442
- slices.pop();
443
- if (!slices.length) {
444
- return cache[path3] = this._rules.test(path3, checkUnignored, MODE_IGNORE);
445
- }
446
- const parent = this._t(
447
- slices.join(SLASH) + SLASH,
448
- cache,
449
- checkUnignored,
450
- slices
451
- );
452
- return cache[path3] = parent.ignored ? parent : this._rules.test(path3, checkUnignored, MODE_IGNORE);
453
- }
454
- ignores(path3) {
455
- return this._test(path3, this._ignoreCache, false).ignored;
456
- }
457
- createFilter() {
458
- return (path3) => !this.ignores(path3);
459
- }
460
- filter(paths) {
461
- return makeArray(paths).filter(this.createFilter());
462
- }
463
- // @returns {TestResult}
464
- test(path3) {
465
- return this._test(path3, this._testCache, true);
466
- }
467
- };
468
- var factory = (options) => new Ignore2(options);
469
- var isPathValid = (path3) => checkPath(path3 && checkPath.convert(path3), path3, RETURN_FALSE);
470
- var setupWindows = () => {
471
- const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
472
- checkPath.convert = makePosix;
473
- const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
474
- checkPath.isNotRelative = (path3) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path3) || isNotRelative(path3);
475
- };
476
- if (
477
- // Detect `process` so that it can run in browsers.
478
- typeof process !== "undefined" && process.platform === "win32"
479
- ) {
480
- setupWindows();
481
- }
482
- module.exports = factory;
483
- factory.default = factory;
484
- module.exports.isPathValid = isPathValid;
485
- define(module.exports, /* @__PURE__ */ Symbol.for("setupWindows"), setupWindows);
486
- }
487
- });
488
-
489
- // src/hooks/post-write.ts
490
- import * as fs2 from "node:fs";
491
- import * as path2 from "node:path";
492
- import { homedir } from "node:os";
493
- import { execFileSync } from "node:child_process";
494
-
495
- // src/ignore.ts
496
- var import_ignore = __toESM(require_ignore(), 1);
497
- import * as fs from "fs";
498
- import * as path from "path";
499
- var IGNORE_FILENAMES = [".gitignore", ".contextignore", ".contextstream/ignore"];
500
- var INVARIANT_IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
501
- ".contextstream",
502
- ".claude",
503
- ".codex",
504
- ".cursor",
505
- ".windsurf",
506
- ".roo",
507
- ".kilocode",
508
- ".ssh",
509
- ".aws",
510
- ".gnupg",
511
- ".kube",
512
- ".docker"
513
- ]);
514
- var INVARIANT_SECRET_FILENAMES = /* @__PURE__ */ new Set([
515
- ".npmrc",
516
- ".pypirc",
517
- ".netrc",
518
- ".pgpass",
519
- ".git-credentials",
520
- "id_rsa",
521
- "id_ed25519",
522
- "id_ecdsa",
523
- "known_hosts",
524
- "credentials.json",
525
- "serviceaccountkey.json",
526
- "auth.json"
527
- ]);
528
- var INVARIANT_SECRET_SUFFIXES = [".pem", ".key", ".p12", ".pfx", ".jks"];
529
- var ENV_TEMPLATE_ALLOWLIST = /* @__PURE__ */ new Set([
530
- ".env.example",
531
- ".env.sample",
532
- ".env.template",
533
- ".env.dist",
534
- ".env.defaults"
535
- ]);
536
- function isInvariantIgnoredPath(pathname) {
537
- const normalized = pathname.replace(/\\/g, "/").replace(/^\.\//, "");
538
- const segments = normalized.split("/").filter(Boolean);
539
- if (segments.some((segment) => INVARIANT_IGNORED_DIRECTORIES.has(segment.toLowerCase()))) {
540
- return true;
541
- }
542
- const basename2 = (segments.at(-1) || "").toLowerCase();
543
- if (INVARIANT_SECRET_FILENAMES.has(basename2)) return true;
544
- if (INVARIANT_SECRET_SUFFIXES.some((suffix) => basename2.endsWith(suffix))) return true;
545
- return (basename2 === ".env" || basename2.startsWith(".env.")) && !ENV_TEMPLATE_ALLOWLIST.has(basename2);
546
- }
547
- var DEFAULT_IGNORE_PATTERNS = [
548
- // Version control
549
- ".git/",
550
- ".svn/",
551
- ".hg/",
552
- // ContextStream and AI editor/agent state. These directories can contain
553
- // credentials, generated rules, caches, and nested worktrees.
554
- ".contextstream/",
555
- ".claude/",
556
- ".codex/",
557
- ".cursor/",
558
- ".windsurf/",
559
- ".roo/",
560
- ".kilocode/",
561
- // Package managers / dependencies
562
- "node_modules/",
563
- "vendor/",
564
- ".pnpm/",
565
- // Build outputs
566
- "target/",
567
- "dist/",
568
- "build/",
569
- "out/",
570
- ".next/",
571
- ".nuxt/",
572
- ".svelte-kit/",
573
- ".parcel-cache/",
574
- ".turbo/",
575
- ".gradle/",
576
- ".cache/",
577
- "bin/",
578
- "obj/",
579
- // Python
580
- "__pycache__/",
581
- ".pytest_cache/",
582
- ".mypy_cache/",
583
- "venv/",
584
- ".venv/",
585
- "env/",
586
- ".env/",
587
- // IDE
588
- ".idea/",
589
- ".vscode/",
590
- ".vs/",
591
- // Credential stores
592
- ".ssh/",
593
- ".aws/",
594
- ".gnupg/",
595
- ".kube/",
596
- ".docker/",
597
- // Coverage
598
- "coverage/",
599
- ".coverage/",
600
- // Lock files
601
- "package-lock.json",
602
- "yarn.lock",
603
- "pnpm-lock.yaml",
604
- "Cargo.lock",
605
- "poetry.lock",
606
- "Gemfile.lock",
607
- "composer.lock",
608
- "*.min.js",
609
- "*.min.css",
610
- "*.pem",
611
- "*.key",
612
- "*.p12",
613
- "*.pfx",
614
- "*.jks",
615
- ".npmrc",
616
- ".pypirc",
617
- ".netrc",
618
- ".pgpass",
619
- ".git-credentials",
620
- "id_rsa",
621
- "id_ed25519",
622
- "id_ecdsa",
623
- "credentials.json",
624
- "serviceAccountKey.json",
625
- "auth.json",
626
- // OS files
627
- ".DS_Store",
628
- "Thumbs.db"
629
- ];
630
- function loadIgnorePatternsSync(projectRoot) {
631
- const ig = (0, import_ignore.default)();
632
- const patterns = [...DEFAULT_IGNORE_PATTERNS];
633
- ig.add(DEFAULT_IGNORE_PATTERNS);
634
- let hasUserPatterns = false;
635
- for (const filename of IGNORE_FILENAMES) {
636
- try {
637
- const content = fs.readFileSync(path.join(projectRoot, filename), "utf-8");
638
- const userPatterns = content.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
639
- if (userPatterns.length > 0) {
640
- ig.add(userPatterns);
641
- patterns.push(...userPatterns);
642
- hasUserPatterns = true;
643
- }
644
- } catch {
645
- }
646
- }
647
- return {
648
- ignores: (pathname) => isInvariantIgnoredPath(pathname) || ig.ignores(pathname),
649
- patterns,
650
- hasUserPatterns
651
- };
652
- }
653
-
654
- // src/hooks/post-write.ts
655
- var API_URL = process.env.CONTEXTSTREAM_API_URL || "https://api.contextstream.io";
656
- var API_KEY = process.env.CONTEXTSTREAM_API_KEY || "";
657
- var ENABLED = process.env.CONTEXTSTREAM_POSTWRITE_ENABLED !== "false";
658
- var INDEXABLE_EXTENSIONS = /* @__PURE__ */ new Set([
659
- ".ts",
660
- ".tsx",
661
- ".js",
662
- ".jsx",
663
- ".mjs",
664
- ".cjs",
665
- ".py",
666
- ".pyw",
667
- ".rs",
668
- ".go",
669
- ".java",
670
- ".kt",
671
- ".scala",
672
- ".c",
673
- ".cpp",
674
- ".cc",
675
- ".cxx",
676
- ".h",
677
- ".hpp",
678
- ".cs",
679
- ".fs",
680
- ".vb",
681
- ".rb",
682
- ".php",
683
- ".pl",
684
- ".pm",
685
- ".swift",
686
- ".m",
687
- ".mm",
688
- ".lua",
689
- ".r",
690
- ".jl",
691
- ".sh",
692
- ".bash",
693
- ".zsh",
694
- ".fish",
695
- ".sql",
696
- ".graphql",
697
- ".gql",
698
- ".html",
699
- ".htm",
700
- ".css",
701
- ".scss",
702
- ".sass",
703
- ".less",
704
- ".json",
705
- ".yaml",
706
- ".yml",
707
- ".toml",
708
- ".xml",
709
- ".ini",
710
- ".cfg",
711
- ".md",
712
- ".mdx",
713
- ".txt",
714
- ".rst",
715
- ".vue",
716
- ".svelte",
717
- ".astro",
718
- ".tf",
719
- ".hcl",
720
- ".dockerfile",
721
- ".containerfile",
722
- ".prisma",
723
- ".proto"
724
- ]);
725
- var MAX_FILE_SIZE = 5 * 1024 * 1024;
726
- function extractFilePath(input) {
727
- if (input.tool_input) {
728
- const filePath = input.tool_input.file_path || input.tool_input.notebook_path || input.tool_input.path;
729
- if (filePath) return filePath;
730
- }
731
- if (input.parameters) {
732
- const filePath = input.parameters.path || input.parameters.file_path;
733
- if (filePath) return filePath;
734
- }
735
- if (input.toolParameters?.path) {
736
- return input.toolParameters.path;
737
- }
738
- if (input.file_path) {
739
- return input.file_path;
740
- }
741
- return null;
742
- }
743
- function extractCwd(input) {
744
- if (input.cwd) return input.cwd;
745
- if (input.workspace_roots?.length) return input.workspace_roots[0];
746
- if (input.workspaceRoots?.length) return input.workspaceRoots[0];
747
- return process.cwd();
748
- }
749
- function findLocalConfig(startDir) {
750
- let currentDir = path2.resolve(startDir);
751
- for (let i = 0; i < 10; i++) {
752
- const configPath = path2.join(currentDir, ".contextstream", "config.json");
753
- if (fs2.existsSync(configPath)) {
754
- try {
755
- const content = fs2.readFileSync(configPath, "utf-8");
756
- return JSON.parse(content);
757
- } catch {
758
- }
759
- }
760
- const parentDir = path2.dirname(currentDir);
761
- if (parentDir === currentDir) break;
762
- currentDir = parentDir;
763
- }
764
- return null;
765
- }
766
- function loadApiConfig(startDir) {
767
- let apiUrl = API_URL;
768
- let apiKey = API_KEY;
769
- if (apiKey) {
770
- return { apiUrl, apiKey };
771
- }
772
- let currentDir = path2.resolve(startDir);
773
- for (let i = 0; i < 10; i++) {
774
- const mcpPath = path2.join(currentDir, ".mcp.json");
775
- if (fs2.existsSync(mcpPath)) {
776
- try {
777
- const content = fs2.readFileSync(mcpPath, "utf-8");
778
- const config = JSON.parse(content);
779
- const csEnv = config.mcpServers?.contextstream?.env;
780
- if (csEnv?.CONTEXTSTREAM_API_KEY) {
781
- apiKey = csEnv.CONTEXTSTREAM_API_KEY;
782
- }
783
- if (csEnv?.CONTEXTSTREAM_API_URL) {
784
- apiUrl = csEnv.CONTEXTSTREAM_API_URL;
785
- }
786
- if (apiKey) break;
787
- } catch {
788
- }
789
- }
790
- const parentDir = path2.dirname(currentDir);
791
- if (parentDir === currentDir) break;
792
- currentDir = parentDir;
793
- }
794
- if (!apiKey) {
795
- const homeMcpPath = path2.join(homedir(), ".mcp.json");
796
- if (fs2.existsSync(homeMcpPath)) {
797
- try {
798
- const content = fs2.readFileSync(homeMcpPath, "utf-8");
799
- const config = JSON.parse(content);
800
- const csEnv = config.mcpServers?.contextstream?.env;
801
- if (csEnv?.CONTEXTSTREAM_API_KEY) {
802
- apiKey = csEnv.CONTEXTSTREAM_API_KEY;
803
- }
804
- if (csEnv?.CONTEXTSTREAM_API_URL) {
805
- apiUrl = csEnv.CONTEXTSTREAM_API_URL;
806
- }
807
- } catch {
808
- }
809
- }
810
- }
811
- return { apiUrl, apiKey };
812
- }
813
- function shouldIndexFile(filePath) {
814
- const ext = path2.extname(filePath).toLowerCase();
815
- if (!INDEXABLE_EXTENSIONS.has(ext)) {
816
- const basename2 = path2.basename(filePath).toLowerCase();
817
- if (!["dockerfile", "makefile", "rakefile", "gemfile", "procfile"].includes(basename2)) {
818
- return false;
819
- }
820
- }
821
- try {
822
- const stats = fs2.statSync(filePath);
823
- if (stats.size > MAX_FILE_SIZE) {
824
- return false;
825
- }
826
- } catch {
827
- return false;
828
- }
829
- return true;
830
- }
831
- function shouldIgnoreHookPath(projectRoot, filePath) {
832
- const root = path2.resolve(projectRoot);
833
- const absolutePath = path2.resolve(filePath);
834
- if (isInvariantIgnoredPath(absolutePath)) {
835
- return true;
836
- }
837
- const relativePath = path2.relative(root, absolutePath).replace(/\\/g, "/");
838
- if (!relativePath || relativePath === ".." || relativePath.startsWith("../")) {
839
- return true;
840
- }
841
- if (loadIgnorePatternsSync(root).ignores(relativePath)) {
842
- return true;
843
- }
844
- try {
845
- execFileSync("git", ["-C", root, "check-ignore", "-q", "--", relativePath], {
846
- stdio: "ignore",
847
- timeout: 2e3
848
- });
849
- return true;
850
- } catch {
851
- return false;
852
- }
853
- }
854
- function detectLanguage(filePath) {
855
- const ext = path2.extname(filePath).toLowerCase();
856
- const langMap = {
857
- ".ts": "typescript",
858
- ".tsx": "typescript",
859
- ".js": "javascript",
860
- ".jsx": "javascript",
861
- ".mjs": "javascript",
862
- ".cjs": "javascript",
863
- ".py": "python",
864
- ".pyw": "python",
865
- ".rs": "rust",
866
- ".go": "go",
867
- ".java": "java",
868
- ".kt": "kotlin",
869
- ".scala": "scala",
870
- ".c": "c",
871
- ".cpp": "cpp",
872
- ".cc": "cpp",
873
- ".cxx": "cpp",
874
- ".h": "c",
875
- ".hpp": "cpp",
876
- ".cs": "csharp",
877
- ".fs": "fsharp",
878
- ".vb": "vb",
879
- ".rb": "ruby",
880
- ".php": "php",
881
- ".pl": "perl",
882
- ".pm": "perl",
883
- ".swift": "swift",
884
- ".m": "objective-c",
885
- ".mm": "objective-cpp",
886
- ".lua": "lua",
887
- ".r": "r",
888
- ".jl": "julia",
889
- ".sh": "shell",
890
- ".bash": "shell",
891
- ".zsh": "shell",
892
- ".fish": "shell",
893
- ".sql": "sql",
894
- ".graphql": "graphql",
895
- ".gql": "graphql",
896
- ".html": "html",
897
- ".htm": "html",
898
- ".css": "css",
899
- ".scss": "scss",
900
- ".sass": "sass",
901
- ".less": "less",
902
- ".json": "json",
903
- ".yaml": "yaml",
904
- ".yml": "yaml",
905
- ".toml": "toml",
906
- ".xml": "xml",
907
- ".ini": "ini",
908
- ".cfg": "ini",
909
- ".md": "markdown",
910
- ".mdx": "mdx",
911
- ".txt": "text",
912
- ".rst": "rst",
913
- ".vue": "vue",
914
- ".svelte": "svelte",
915
- ".astro": "astro",
916
- ".tf": "terraform",
917
- ".hcl": "hcl",
918
- ".prisma": "prisma",
919
- ".proto": "protobuf"
920
- };
921
- return langMap[ext] || "text";
922
- }
923
- async function indexFile(filePath, projectId, apiUrl, apiKey, projectRoot) {
924
- const content = fs2.readFileSync(filePath, "utf-8");
925
- const relativePath = path2.relative(projectRoot, filePath);
926
- const payload = {
927
- files: [
928
- {
929
- path: relativePath,
930
- content,
931
- language: detectLanguage(filePath)
932
- }
933
- ]
934
- };
935
- const response = await fetch(`${apiUrl}/api/v1/projects/${projectId}/files/ingest`, {
936
- method: "POST",
937
- headers: {
938
- "Content-Type": "application/json",
939
- "X-API-Key": apiKey
940
- },
941
- body: JSON.stringify(payload),
942
- signal: AbortSignal.timeout(1e4)
943
- // 10 second timeout
944
- });
945
- if (!response.ok) {
946
- throw new Error(`API error: ${response.status} ${response.statusText}`);
947
- }
948
- try {
949
- const body = await response.json();
950
- if (body?.data?.status === "cooldown" || body?.data?.status === "daily_limit_exceeded") {
951
- return;
952
- }
953
- } catch {
954
- }
955
- }
956
- function findProjectRoot(filePath) {
957
- let currentDir = path2.dirname(path2.resolve(filePath));
958
- for (let i = 0; i < 10; i++) {
959
- const configPath = path2.join(currentDir, ".contextstream", "config.json");
960
- if (fs2.existsSync(configPath)) {
961
- return currentDir;
962
- }
963
- const parentDir = path2.dirname(currentDir);
964
- if (parentDir === currentDir) break;
965
- currentDir = parentDir;
966
- }
967
- return null;
968
- }
969
- async function runPostWriteHook() {
970
- if (!ENABLED) {
971
- process.exit(0);
972
- }
973
- let inputData = "";
974
- for await (const chunk of process.stdin) {
975
- inputData += chunk;
976
- }
977
- if (!inputData.trim()) {
978
- process.exit(0);
979
- }
980
- let input;
981
- try {
982
- input = JSON.parse(inputData);
983
- } catch {
984
- process.exit(0);
985
- }
986
- const filePath = extractFilePath(input);
987
- if (!filePath) {
988
- process.exit(0);
989
- }
990
- const cwd = extractCwd(input);
991
- const absolutePath = path2.isAbsolute(filePath) ? filePath : path2.resolve(cwd, filePath);
992
- if (!fs2.existsSync(absolutePath) || !shouldIndexFile(absolutePath)) {
993
- process.exit(0);
994
- }
995
- const projectRoot = findProjectRoot(absolutePath);
996
- if (!projectRoot) {
997
- process.exit(0);
998
- }
999
- if (shouldIgnoreHookPath(projectRoot, absolutePath)) {
1000
- process.exit(0);
1001
- }
1002
- const localConfig = findLocalConfig(projectRoot);
1003
- if (!localConfig?.project_id) {
1004
- process.exit(0);
1005
- }
1006
- const { apiUrl, apiKey } = loadApiConfig(projectRoot);
1007
- if (!apiKey) {
1008
- process.exit(0);
1009
- }
1010
- try {
1011
- await indexFile(absolutePath, localConfig.project_id, apiUrl, apiKey, projectRoot);
1012
- } catch {
1013
- }
1014
- process.exit(0);
1015
- }
1016
- var isDirectRun = process.argv[1]?.includes("post-write") || process.argv[2] === "post-write";
1017
- if (isDirectRun) {
1018
- runPostWriteHook().catch(() => process.exit(0));
1019
- }
1020
- export {
1021
- runPostWriteHook,
1022
- shouldIgnoreHookPath
1023
- };