@gitsense/gsc-utils 0.1.0

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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/dist/gitsense-chat-utils.cjs.js +10977 -0
  3. package/dist/gitsense-chat-utils.esm.js +10975 -0
  4. package/dist/gsc-utils.cjs.js +11043 -0
  5. package/dist/gsc-utils.esm.js +11041 -0
  6. package/package.json +37 -0
  7. package/src/AnalysisBlockUtils.js +151 -0
  8. package/src/ChatUtils.js +126 -0
  9. package/src/CodeBlockUtils/blockExtractor.js +277 -0
  10. package/src/CodeBlockUtils/blockProcessor.js +559 -0
  11. package/src/CodeBlockUtils/blockProcessor.js.rej +8 -0
  12. package/src/CodeBlockUtils/constants.js +62 -0
  13. package/src/CodeBlockUtils/continuationUtils.js +191 -0
  14. package/src/CodeBlockUtils/headerParser.js +175 -0
  15. package/src/CodeBlockUtils/headerUtils.js +236 -0
  16. package/src/CodeBlockUtils/index.js +83 -0
  17. package/src/CodeBlockUtils/lineNumberFormatter.js +117 -0
  18. package/src/CodeBlockUtils/markerRemover.js +89 -0
  19. package/src/CodeBlockUtils/patchIntegration.js +38 -0
  20. package/src/CodeBlockUtils/relationshipUtils.js +159 -0
  21. package/src/CodeBlockUtils/updateCodeBlock.js +372 -0
  22. package/src/CodeBlockUtils/uuidUtils.js +48 -0
  23. package/src/ContextUtils.js +180 -0
  24. package/src/GSToolBlockUtils.js +108 -0
  25. package/src/GitSenseChatUtils.js +386 -0
  26. package/src/JsonUtils.js +101 -0
  27. package/src/LLMUtils.js +31 -0
  28. package/src/MessageUtils.js +460 -0
  29. package/src/PatchUtils/constants.js +72 -0
  30. package/src/PatchUtils/diagnosticReporter.js +213 -0
  31. package/src/PatchUtils/enhancedPatchProcessor.js +390 -0
  32. package/src/PatchUtils/fuzzyMatcher.js +252 -0
  33. package/src/PatchUtils/hunkCorrector.js +204 -0
  34. package/src/PatchUtils/hunkValidator.js +305 -0
  35. package/src/PatchUtils/index.js +135 -0
  36. package/src/PatchUtils/patchExtractor.js +175 -0
  37. package/src/PatchUtils/patchHeaderFormatter.js +143 -0
  38. package/src/PatchUtils/patchParser.js +289 -0
  39. package/src/PatchUtils/patchProcessor.js +389 -0
  40. package/src/PatchUtils/patchVerifier/constants.js +23 -0
  41. package/src/PatchUtils/patchVerifier/detectAndFixOverlappingHunks.js +281 -0
  42. package/src/PatchUtils/patchVerifier/detectAndFixRedundantChanges.js +404 -0
  43. package/src/PatchUtils/patchVerifier/formatAndAddLineNumbers.js +165 -0
  44. package/src/PatchUtils/patchVerifier/index.js +25 -0
  45. package/src/PatchUtils/patchVerifier/verifyAndCorrectHunkHeaders.js +202 -0
  46. package/src/PatchUtils/patchVerifier/verifyAndCorrectLineNumbers.js +254 -0
  47. package/src/SharedUtils/timestampUtils.js +41 -0
  48. package/src/SharedUtils/versionUtils.js +58 -0
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Component: GitSense Tool Block Utilities
3
+ * Block-UUID: 72db6a5f-3b09-49e8-8f39-d4e3d37b510a
4
+ * Parent-UUID: N/A
5
+ * Version: 1.0.0
6
+ * Description: Provides utility functions for identifying and parsing GitSense Chat Tool Blocks.
7
+ * Language: JavaScript
8
+ * Created-at: 2025-04-27T01:29:53.576Z
9
+ * Authors: Gemini 2.5 Pro (v1.0.0)
10
+ */
11
+
12
+
13
+ /**
14
+ * Checks if a given code block content represents a GitSense Chat Tool Block.
15
+ * It verifies if the first non-empty line starts with "# GitSense Chat Tool".
16
+ *
17
+ * @param {string} content - The raw content of the code block (within the fences).
18
+ * @returns {boolean} True if it's a GitSense Chat Tool Block, false otherwise.
19
+ */
20
+ function isToolBlock(content) {
21
+ if (!content || typeof content !== 'string') {
22
+ return false;
23
+ }
24
+
25
+ if (content.match(/^\s*# GitSense Chat Tool\n\s*{/))
26
+ return true;
27
+
28
+ return false;
29
+ }
30
+
31
+ /**
32
+ * Parses the content of a GitSense Chat Tool Block to extract the JSON payload.
33
+ * It strips the marker line and any subsequent lines starting with '#' (comments)
34
+ * or empty lines before attempting to parse the remaining content as JSON.
35
+ *
36
+ * @param {string} content - The raw content of the code block, verified by isToolBlock.
37
+ * @returns {{ tool: string, config: object, data: object } | null} The parsed JSON object { tool, config, data } or null if parsing fails or format is invalid.
38
+ * @throws {Error} If JSON parsing fails.
39
+ */
40
+ function parseToolBlock(content) {
41
+ if (!isToolBlock(content)) {
42
+ return null; // Should already be verified, but double-check
43
+ }
44
+
45
+ const lines = content.split('\n');
46
+ const jsonLines = [];
47
+ let markerFound = false;
48
+
49
+ for (const line of lines) {
50
+ const trimmedLine = line.trim();
51
+
52
+ if (!markerFound) {
53
+ if (trimmedLine.startsWith('# GitSense Chat Tool')) {
54
+ markerFound = true; // Skip the marker line itself
55
+ }
56
+ continue; // Skip lines before the marker (shouldn't be any non-empty ones based on isToolBlock)
57
+ }
58
+
59
+ // After the marker, skip empty lines and comment lines
60
+ if (trimmedLine.length === 0 || /^\s*#/.test(line)) {
61
+ continue;
62
+ }
63
+
64
+ // Keep lines that are part of the JSON
65
+ jsonLines.push(line);
66
+ }
67
+
68
+ const jsonString = jsonLines.join('\n');
69
+
70
+ if (!jsonString) {
71
+ // No JSON content found after stripping comments/marker
72
+ throw new Error("No JSON content found in the tool block after stripping marker and comments.");
73
+ }
74
+
75
+ try {
76
+ const parsed = JSON.parse(jsonString);
77
+
78
+ // Basic validation of the parsed structure
79
+ // The properties tool and config are required. Tool cannot be null or undefined but
80
+ // config can't. The reason for requiring config to be declared is to reserve the
81
+ // property name.
82
+ if (typeof parsed !== 'object' || parsed === null) {
83
+ throw new Error("Parsed content is not a valid JSON object.");
84
+ }
85
+ if (typeof parsed.tool !== 'string' || !parsed.tool) {
86
+ throw new Error("Parsed JSON object is missing the required 'tool' string property.");
87
+ }
88
+
89
+ if (typeof parsed.config === 'undefined') {
90
+ throw new Error("Parsed JSON object is missing the required 'config' property.");
91
+ }
92
+
93
+ return parsed;
94
+ } catch (error) {
95
+ // Re-throw JSON parsing errors with more context
96
+ throw new Error(`Failed to parse tool block JSON: ${error.message}\nContent after stripping comments:\n${jsonString}`);
97
+ }
98
+ }
99
+
100
+ function formatToolBlock(toolData) {
101
+ return `# GitSense Chat Tool\n\n${JSON.stringify(toolData, null, 2)}`;
102
+ }
103
+
104
+ module.exports = {
105
+ isToolBlock,
106
+ parseToolBlock,
107
+ formatToolBlock
108
+ }
@@ -0,0 +1,386 @@
1
+ /**
2
+ * Component: GitSenseChatUtils
3
+ * Block-UUID: 5e8d1a9c-0b3f-4e1a-8c7d-9f0b2e1d3a4b
4
+ * Parent-UUID: 7a9b1c8e-f1a4-4b2d-9e8f-6f7a0b1c2d3f
5
+ * Version: 2.1.1
6
+ * Description: Interface class for GitSense Chat utilities providing a unified API for code block parsing (markdown), extraction, and patch operations. Integrates functionalities from CodeBlockUtils and PatchUtils modules.
7
+ * Language: JavaScript
8
+ * Created-at: 2025-04-15T16:04:26.780Z
9
+ * Authors: Claude 3.7 Sonnet (v1.0.0), Gemini 2.5 Pro (v2.0.0), Gemini 2.5 Pro (v2.1.0), Gemini 2.5 Pro (v2.1.1)
10
+ */
11
+
12
+
13
+ const ChatUtils = require('./ChatUtils');
14
+ const CodeBlockUtils = require('./CodeBlockUtils');
15
+ const ContextUtils = require('./ContextUtils');
16
+ const MessageUtils = require('./MessageUtils');
17
+ const AnalysisBlockUtils = require('./AnalysisBlockUtils');
18
+ const PatchUtils = require('./PatchUtils');
19
+ const GSToolBlockUtils = require('./GSToolBlockUtils');
20
+ const LLMUtils = require('./LLMUtils');
21
+ const JsonUtils = require('./JsonUtils');
22
+
23
+ const {
24
+ estimateTokens
25
+ } = LLMUtils;
26
+
27
+ const {
28
+ detectJsonComments
29
+ } = JsonUtils;
30
+
31
+ const {
32
+ isOverviewBuilderChat,
33
+ getChatMessages,
34
+ } = ChatUtils;
35
+
36
+ const {
37
+ getChatTemplateMessages,
38
+ getMessagesBeforeId,
39
+ getMessageById,
40
+ getLastMessage,
41
+ findMessages,
42
+ deleteMessagesByIds,
43
+ getMessageContentType,
44
+ isContextMessage,
45
+ isContextItemsOverviewMessage
46
+ } = MessageUtils;
47
+
48
+ const {
49
+ isOverviewBlock,
50
+ getOverviewType,
51
+ parseOverviewMetadata,
52
+ validateOverviewMetadata,
53
+ } = AnalysisBlockUtils;
54
+
55
+ const {
56
+ COMMENT_STYLES,
57
+ generateUUID,
58
+ validateUUID,
59
+ isValidISOTimestamp,
60
+ parseHeader,
61
+ findAllCodeFences,
62
+ matchFencesAndExtractBlocks,
63
+ processCodeBlocks,
64
+ extractCodeBlocks,
65
+ fixTextCodeBlocks,
66
+ containsPatch,
67
+ detectCodeBlockRelationships,
68
+ detectIncompleteCodeBlock,
69
+ extractFilePaths,
70
+ extractContinuationInfo,
71
+ formatWithLineNumbers,
72
+ formatBlocksWithLineNumbers,
73
+ formatBlockWithLineNumbers,
74
+ removeLineNumbers,
75
+ generateContinuationPrompt,
76
+ parseCommentDelimitedBlocks,
77
+ removeCodeBlockMarkers,
78
+ updateCodeBlockByIndex,
79
+ deleteCodeBlockByIndex,
80
+ } = CodeBlockUtils;
81
+
82
+ const {
83
+ isPatchBlock,
84
+ determinePatchFormat,
85
+ extractPatchMetadata,
86
+ validatePatchMetadata,
87
+ extractPatchContent,
88
+ extractContextPatches,
89
+ convertContextPatchToDiff,
90
+ convertDiffToContextPatch,
91
+ verifyAndCorrectLineNumbers,
92
+ } = PatchUtils;
93
+
94
+ const {
95
+ isToolBlock,
96
+ parseToolBlock
97
+ } = GSToolBlockUtils;
98
+
99
+ /**
100
+ * GitSenseChatUtils class provides a unified interface to code block and patch utilities.
101
+ * Focuses on markdown code block extraction and processing.
102
+ */
103
+ class GitSenseChatUtils {
104
+ /**
105
+ * Create a new GitSenseChatUtils instance
106
+ * @param {Object} options - Configuration options
107
+ * @param {boolean} [options.silent=false] - Whether to suppress console warning messages
108
+ */
109
+ constructor(options = {}) {
110
+ this.options = {
111
+ silent: false,
112
+ ...options
113
+ };
114
+
115
+ // Make comment styles available as a property via CodeBlockUtils
116
+ this.commentStyles = CodeBlockUtils.COMMENT_STYLES;
117
+ }
118
+
119
+ /**
120
+ * Parse markdown code blocks from input text using the primary extractor.
121
+ * @param {string} input - The input text containing markdown code blocks.
122
+ * @param {Object} [options] - Options for extraction (overrides instance options).
123
+ * @returns {Object} Object containing extracted blocks and warnings { blocks: Array, warnings: Array }.
124
+ */
125
+ parseCodeBlocks(input, options) {
126
+ // Wraps the primary markdown block extractor for consistency
127
+ return CodeBlockUtils.extractCodeBlocks(input, options || this.options);
128
+ }
129
+
130
+ /**
131
+ * Remove custom code block start/complete markers from markdown text.
132
+ * @param {string} markdownText - The markdown text containing code blocks with markers.
133
+ * @returns {string} The markdown text with code block markers removed.
134
+ */
135
+ removeCodeBlockMarkers(markdownText) {
136
+ // Uses function from CodeBlockUtils
137
+ return CodeBlockUtils.removeCodeBlockMarkers(markdownText);
138
+ }
139
+
140
+ /**
141
+ * Extract markdown code blocks from text (simple API).
142
+ * @param {string} text - The input text containing markdown code blocks.
143
+ * @param {Object} [options] - Options for extraction (overrides instance options).
144
+ * @returns {Object} Object containing extracted blocks and warnings { blocks: Array, warnings: Array }.
145
+ */
146
+ extractCodeBlocks(text, options) {
147
+ // Uses function from CodeBlockUtils
148
+ return CodeBlockUtils.extractCodeBlocks(text, options || this.options);
149
+ }
150
+
151
+ /**
152
+ * Process text with markdown code blocks, returning detailed information including incomplete status.
153
+ * @param {string} text - The input text containing markdown code blocks.
154
+ * @param {Object} [options] - Options for processing (overrides instance options).
155
+ * @returns {Object} Processed blocks, warnings, and incomplete status info.
156
+ */
157
+ processCodeBlocks(text, options) {
158
+ // Uses function from CodeBlockUtils
159
+ return CodeBlockUtils.processCodeBlocks(text, options || this.options);
160
+ }
161
+
162
+ /**
163
+ * Extract only patch blocks from text.
164
+ * @param {string} text - The input text potentially containing patch blocks.
165
+ * @param {Object} [options] - Options for processing (overrides instance options).
166
+ * @returns {Object} Object containing extracted patch blocks and warnings { blocks: Array, warnings: Array }.
167
+ */
168
+ extractPatchBlocks(text, options) {
169
+ const { blocks, warnings } = CodeBlockUtils.processCodeBlocks(text, options || this.options);
170
+ const patchBlocks = blocks.filter(block => block.type === 'patch');
171
+ // Filter warnings? For now, return all warnings encountered during processing.
172
+ return { blocks: patchBlocks, warnings: warnings };
173
+ }
174
+
175
+ /**
176
+ * Fix invalid UUIDs in code blocks (markdown headers or patch metadata) within text.
177
+ * @param {string} text - The input text containing code blocks.
178
+ * @returns {Object} Object containing fixed text and whether changes were made { text: string, modified: boolean }.
179
+ */
180
+ fixTextCodeBlocks(text) {
181
+ // Uses function from CodeBlockUtils
182
+ return CodeBlockUtils.fixTextCodeBlocks(text);
183
+ }
184
+
185
+ /**
186
+ * Determines if a code block's content represents a patch.
187
+ * @param {string} codeBlockContent - The content of the code block (between the fences).
188
+ * @returns {boolean} True if the code block is a patch.
189
+ */
190
+ isPatchBlock(codeBlockContent) {
191
+ // Uses function from PatchUtils
192
+ return PatchUtils.isPatchBlock(codeBlockContent);
193
+ }
194
+
195
+ /**
196
+ * Determines the type of patch format used (e.g., 'context', 'diff').
197
+ * @param {string} patchText - The patch text content.
198
+ * @returns {string} 'context', 'diff', or 'unknown'.
199
+ */
200
+ determinePatchFormat(patchText) {
201
+ // Uses function from PatchUtils
202
+ return PatchUtils.determinePatchFormat(patchText);
203
+ }
204
+
205
+ /**
206
+ * Extracts metadata from a patch block.
207
+ * @param {string} patchText - The patch text including metadata.
208
+ * @returns {Object} Extracted metadata object.
209
+ */
210
+ extractPatchMetadata(patchText) {
211
+ // Uses function from PatchUtils
212
+ return PatchUtils.extractPatchMetadata(patchText);
213
+ }
214
+
215
+ /**
216
+ * Validates patch metadata for required fields and format.
217
+ * @param {Object} metadata - The patch metadata object.
218
+ * @returns {Object} Validation result { valid: boolean, errors: Array }.
219
+ */
220
+ validatePatchMetadata(metadata) {
221
+ // Uses function from PatchUtils
222
+ return PatchUtils.validatePatchMetadata(metadata);
223
+ }
224
+
225
+ /**
226
+ * Extracts context-based patch sections (@@ ... @@) from patch text.
227
+ * @param {string} patchText - The full patch text content.
228
+ * @returns {Array|null} Array of context patch objects or null if invalid format.
229
+ */
230
+ extractContextPatches(patchText) {
231
+ // Uses function from PatchUtils
232
+ return PatchUtils.extractContextPatches(patchText);
233
+ }
234
+
235
+ /**
236
+ * Extracts the diff content (lines after metadata) from a patch block.
237
+ * @param {string} patchText - The full patch text content.
238
+ * @returns {string} The diff content only.
239
+ */
240
+ extractDiffContent(patchText) {
241
+ // Uses function from PatchUtils (assuming it's named extractPatchContent or similar)
242
+ // If PatchUtils.extractDiffContent exists, use it. Otherwise, use extractPatchContent.
243
+ return PatchUtils.extractDiffContent
244
+ ? PatchUtils.extractDiffContent(patchText)
245
+ : PatchUtils.extractPatchContent(patchText);
246
+ }
247
+
248
+ /**
249
+ * Converts a context-based patch representation to a traditional diff patch string.
250
+ * (Requires external 'diff' library functionality, likely within PatchUtils).
251
+ * @param {Array} contextPatches - Array of context patch objects.
252
+ * @param {string} sourceCode - The source code to patch.
253
+ * @returns {string} Traditional diff patch content.
254
+ */
255
+ convertContextPatchToDiff(contextPatches, sourceCode) {
256
+ // Uses function from PatchUtils
257
+ return PatchUtils.convertContextPatchToDiff(contextPatches, sourceCode);
258
+ }
259
+
260
+ /**
261
+ * Converts a traditional diff patch string to a context-based patch representation.
262
+ * (Requires external 'diff' library functionality, likely within PatchUtils).
263
+ * @param {string} diffContent - Traditional diff content.
264
+ * @param {string} sourceCode - The source code the diff applies to.
265
+ * @returns {Array} Array of context patch objects.
266
+ */
267
+ convertDiffToContextPatch(diffContent, sourceCode) {
268
+ // Uses function from PatchUtils
269
+ return PatchUtils.convertDiffToContextPatch(diffContent, sourceCode);
270
+ }
271
+
272
+ /**
273
+ * Generates a valid RFC 4122 UUID v4.
274
+ * @returns {string} A valid UUID v4.
275
+ */
276
+ generateUUID() {
277
+ // Uses function from CodeBlockUtils
278
+ return CodeBlockUtils.generateUUID();
279
+ }
280
+
281
+ /**
282
+ * Validates a UUID string.
283
+ * @param {string} uuid - The UUID string to validate.
284
+ * @returns {Object} Object containing validation results.
285
+ */
286
+ validateUUID(uuid) {
287
+ // Uses function from CodeBlockUtils
288
+ return CodeBlockUtils.validateUUID(uuid);
289
+ }
290
+
291
+ /**
292
+ * Validates if a string is a valid ISO 8601 timestamp.
293
+ * @param {string} timestamp - The timestamp to validate.
294
+ * @returns {boolean} - True if valid, false otherwise.
295
+ */
296
+ isValidISOTimestamp(timestamp) {
297
+ // Uses function from CodeBlockUtils
298
+ return CodeBlockUtils.isValidISOTimestamp(timestamp);
299
+ }
300
+ }
301
+
302
+ // Export the main class, the aggregated CodeBlockUtils, PatchUtils,
303
+ // and individual functions for backward compatibility or direct use.
304
+ module.exports = {
305
+ // Main class
306
+ GitSenseChatUtils,
307
+
308
+ // Aggregated Modules
309
+ CodeBlockUtils,
310
+ ContextUtils,
311
+ MessageUtils,
312
+ PatchUtils,
313
+ LLMUtils,
314
+ AnalysisBlockUtils,
315
+ ChatUtils,
316
+ GSToolBlockUtils,
317
+ JsonUtils,
318
+
319
+ // --- Individual Function Exports (sourced correctly) ---
320
+
321
+ // Code Block Processing (from CodeBlockUtils)
322
+ COMMENT_STYLES,
323
+ extractCodeBlocks,
324
+ processCodeBlocks,
325
+ fixTextCodeBlocks,
326
+ parseHeader,
327
+
328
+ // UUID (from CodeBlockUtils)
329
+ generateUUID,
330
+ validateUUID,
331
+
332
+ // Timestamp (from CodeBlockUtils)
333
+ isValidISOTimestamp,
334
+
335
+ // Patch Detection/Integration (from CodeBlockUtils)
336
+ containsPatch,
337
+
338
+ // Relationships / Incomplete Blocks (from CodeBlockUtils)
339
+ detectCodeBlockRelationships,
340
+ detectIncompleteCodeBlock,
341
+ extractFilePaths,
342
+ extractContinuationInfo,
343
+ generateContinuationPrompt,
344
+
345
+ // Line formatter (from CodeBlockUtils)
346
+ formatWithLineNumbers,
347
+ formatBlockWithLineNumbers,
348
+ formatBlocksWithLineNumbers,
349
+ removeLineNumbers,
350
+
351
+ // Other Utilities (from CodeBlockUtils)
352
+ removeCodeBlockMarkers,
353
+ parseCommentDelimitedBlocks,
354
+ updateCodeBlockByIndex,
355
+ deleteCodeBlockByIndex,
356
+
357
+ // Analysis Block Utilities
358
+ isOverviewBlock,
359
+ getOverviewType,
360
+ parseOverviewMetadata,
361
+ validateOverviewMetadata,
362
+
363
+ // ChatUtils
364
+ getChatMessages,
365
+
366
+ // Message Utils
367
+ getChatTemplateMessages,
368
+ getMessagesBeforeId,
369
+ getMessageById,
370
+ getLastMessage,
371
+ findMessages,
372
+ deleteMessagesByIds,
373
+ getMessageContentType,
374
+ isContextMessage,
375
+ isContextItemsOverviewMessage,
376
+
377
+ // LLM Utils
378
+ estimateTokens,
379
+
380
+ // GS Tool Block
381
+ isToolBlock,
382
+ parseToolBlock,
383
+
384
+ // Note: Internal helpers like findAllCodeFences, matchFencesAndExtractBlocks are
385
+ // typically not exported directly from the facade but are available via CodeBlockUtils object.
386
+ };
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Component: JSON Utils
3
+ * Block-UUID: 751cb03b-731d-4fa1-9dc0-5d4142275f20
4
+ * Parent-UUID: N/A
5
+ * Version: 1.0.0
6
+ * Description: JSON Utilities
7
+ * Language: javascript
8
+ * Created-at: 2025-05-24T01:15:44.320Z
9
+ * Authors: Gemini 2.5 Flash Thinking (v1.0.0)
10
+ */
11
+
12
+
13
+ /**
14
+ * Detects C-style block (/* ... *\/) and single-line (// ...) comments
15
+ * within a string, correctly ignoring comments that appear inside
16
+ * JSON string literals.
17
+ *
18
+ * @param {string} jsonString The string potentially containing JSON and comments.
19
+ * @returns {string[]} An array of detected comment strings (including their markers).
20
+ */
21
+ function detectJsonComments(jsonString) {
22
+ const comments = [];
23
+ let inString = false;
24
+ let inBlockComment = false;
25
+ let inLineComment = false;
26
+ let commentStartIndex = -1;
27
+
28
+ for (let i = 0; i < jsonString.length; i++) {
29
+ const char = jsonString[i];
30
+ const nextChar = jsonString[i + 1];
31
+
32
+ // Handle escape sequences within strings
33
+ if (inString && char === '\\') {
34
+ i++; // Skip the next character as it's escaped
35
+ continue;
36
+ }
37
+
38
+ // Handle entering/exiting strings
39
+ if (char === '"' && !inBlockComment && !inLineComment) {
40
+ inString = !inString;
41
+ continue; // Move to the next character
42
+ }
43
+
44
+ // If currently in a block comment
45
+ if (inBlockComment) {
46
+ if (char === '*' && nextChar === '/') {
47
+ // End of block comment found
48
+ comments.push(jsonString.substring(commentStartIndex, i + 2));
49
+ inBlockComment = false;
50
+ commentStartIndex = -1;
51
+ i++; // Skip the '/' character
52
+ continue;
53
+ }
54
+ // Continue consuming characters within the comment
55
+ continue;
56
+ }
57
+
58
+ // If currently in a line comment
59
+ if (inLineComment) {
60
+ if (char === '\n' || i === jsonString.length - 1) {
61
+ // End of line comment found (newline or end of string)
62
+ comments.push(jsonString.substring(commentStartIndex, i + (char === '\n' ? 0 : 1)));
63
+ inLineComment = false;
64
+ commentStartIndex = -1;
65
+ // Do not continue, let the loop handle the newline or end of string
66
+ }
67
+ // Continue consuming characters within the comment
68
+ continue;
69
+ }
70
+
71
+ // If not in a string or comment, check for comment starts
72
+ if (!inString) {
73
+ // Check for block comment start
74
+ if (char === '/' && nextChar === '*') {
75
+ inBlockComment = true;
76
+ commentStartIndex = i;
77
+ i++; // Skip the '*' character
78
+ continue;
79
+ }
80
+
81
+ // Check for single-line comment start
82
+ if (char === '/' && nextChar === '/') {
83
+ inLineComment = true;
84
+ commentStartIndex = i;
85
+ i++; // Skip the '/' character
86
+ continue;
87
+ }
88
+ }
89
+ }
90
+
91
+ // Handle case where a line comment is the very last thing in the string
92
+ if (inLineComment && commentStartIndex !== -1) {
93
+ comments.push(jsonString.substring(commentStartIndex));
94
+ }
95
+
96
+ return comments;
97
+ }
98
+
99
+ module.exports = {
100
+ detectJsonComments
101
+ };
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Component: LLMUtils
3
+ * Block-UUID: a3106054-42f1-474f-96f3-182d66eb19a0
4
+ * Parent-UUID: N/A
5
+ * Version: 1.0.0
6
+ * Description: Provides utility functions related to Large Language Model interactions, such as token estimation.
7
+ * Language: JavaScript
8
+ * Created-at: 2025-04-22T17:16:00.590Z
9
+ * Authors: Gemini 2.5 Pro (v1.0.0)
10
+ */
11
+
12
+
13
+ /**
14
+ * Estimates the number of tokens in a given text string.
15
+ * This is a basic estimation using the common heuristic of ~4 characters per token.
16
+ * Actual token count can vary significantly based on the specific tokenizer used by an LLM.
17
+ *
18
+ * @param {string} text - The text to estimate tokens for.
19
+ * @returns {number} An estimated token count. Returns 0 if input is not a non-empty string.
20
+ */
21
+ function estimateTokens(text) {
22
+ if (typeof text !== 'string' || text.length === 0) {
23
+ return 0;
24
+ }
25
+ // Basic heuristic: average token length is around 4 characters
26
+ return Math.ceil(text.length / 4);
27
+ }
28
+
29
+ module.exports = {
30
+ estimateTokens,
31
+ };