@critical-path/core 0.20.2 → 0.22.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 (85) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +45 -0
  3. package/dist/domain/ddd.test.js +12 -0
  4. package/dist/domain/ddd.test.js.map +1 -1
  5. package/dist/domain/entities.d.ts.map +1 -1
  6. package/dist/domain/entities.js +3 -2
  7. package/dist/domain/entities.js.map +1 -1
  8. package/dist/domain/errors.d.ts +13 -0
  9. package/dist/domain/errors.d.ts.map +1 -0
  10. package/dist/domain/errors.js +19 -0
  11. package/dist/domain/errors.js.map +1 -0
  12. package/dist/domain/events.d.ts +9 -1
  13. package/dist/domain/events.d.ts.map +1 -1
  14. package/dist/domain/events.js.map +1 -1
  15. package/dist/domain/index.d.ts +1 -0
  16. package/dist/domain/index.d.ts.map +1 -1
  17. package/dist/domain/index.js +1 -0
  18. package/dist/domain/index.js.map +1 -1
  19. package/dist/domain/task-duration.test.js +32 -0
  20. package/dist/domain/task-duration.test.js.map +1 -1
  21. package/dist/engine/index.d.ts +11 -0
  22. package/dist/engine/index.d.ts.map +1 -1
  23. package/dist/engine/index.js +112 -19
  24. package/dist/engine/index.js.map +1 -1
  25. package/dist/index.test.js +20 -0
  26. package/dist/index.test.js.map +1 -1
  27. package/dist/status.test.js +97 -1
  28. package/dist/status.test.js.map +1 -1
  29. package/dist/store/sqlite.d.ts.map +1 -1
  30. package/dist/store/sqlite.js +19 -6
  31. package/dist/store/sqlite.js.map +1 -1
  32. package/dist/store/sqlite.test.js +20 -0
  33. package/dist/store/sqlite.test.js.map +1 -1
  34. package/dist/types/index.d.ts +2 -1
  35. package/dist/types/index.d.ts.map +1 -1
  36. package/dist/utils/fractional-index.d.ts +50 -0
  37. package/dist/utils/fractional-index.d.ts.map +1 -0
  38. package/dist/utils/fractional-index.js +226 -0
  39. package/dist/utils/fractional-index.js.map +1 -0
  40. package/dist/utils/fractional-index.test.d.ts +2 -0
  41. package/dist/utils/fractional-index.test.d.ts.map +1 -0
  42. package/dist/utils/fractional-index.test.js +182 -0
  43. package/dist/utils/fractional-index.test.js.map +1 -0
  44. package/dist/utils/index.d.ts +1 -0
  45. package/dist/utils/index.d.ts.map +1 -1
  46. package/dist/utils/index.js +1 -0
  47. package/dist/utils/index.js.map +1 -1
  48. package/dist/utils/key.d.ts +5 -0
  49. package/dist/utils/key.d.ts.map +1 -1
  50. package/dist/utils/key.js +10 -0
  51. package/dist/utils/key.js.map +1 -1
  52. package/dist/utils/key.test.js +18 -1
  53. package/dist/utils/key.test.js.map +1 -1
  54. package/dist/utils/mentions.d.ts +13 -5
  55. package/dist/utils/mentions.d.ts.map +1 -1
  56. package/dist/utils/mentions.js +52 -16
  57. package/dist/utils/mentions.js.map +1 -1
  58. package/dist/utils/mentions.test.js +32 -1
  59. package/dist/utils/mentions.test.js.map +1 -1
  60. package/dist/utils/status.d.ts +80 -1
  61. package/dist/utils/status.d.ts.map +1 -1
  62. package/dist/utils/status.js +194 -0
  63. package/dist/utils/status.js.map +1 -1
  64. package/package.json +1 -5
  65. package/src/domain/ddd.test.ts +22 -0
  66. package/src/domain/entities.ts +3 -2
  67. package/src/domain/errors.ts +19 -0
  68. package/src/domain/events.ts +6 -0
  69. package/src/domain/index.ts +1 -0
  70. package/src/domain/task-duration.test.ts +36 -0
  71. package/src/engine/index.ts +118 -20
  72. package/src/index.test.ts +24 -0
  73. package/src/status.test.ts +130 -2
  74. package/src/store/sqlite.test.ts +22 -0
  75. package/src/store/sqlite.ts +21 -4
  76. package/src/types/index.ts +2 -0
  77. package/src/utils/fractional-index.test.ts +228 -0
  78. package/src/utils/fractional-index.ts +254 -0
  79. package/src/utils/index.ts +2 -0
  80. package/src/utils/key.test.ts +22 -1
  81. package/src/utils/key.ts +11 -0
  82. package/src/utils/mentions.test.ts +37 -1
  83. package/src/utils/mentions.ts +58 -16
  84. package/src/utils/status.ts +247 -0
  85. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,254 @@
1
+ /**
2
+ * Fractional Lexical Indexing Utility
3
+ *
4
+ * Deterministic Base-62 fractional indexing for ordered lists and swimlane task sequences.
5
+ * Produces lexicographically sortable strings (`orderIndex`) that allow infinite insertion
6
+ * between any two items without floating-point precision loss.
7
+ */
8
+
9
+ export const BASE_62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
10
+
11
+ /**
12
+ * Encodes a non-negative integer into Base-62.
13
+ */
14
+ function toBase62(n: number): string {
15
+ if (n === 0) return '0';
16
+ let s = '';
17
+ let curr = n;
18
+ while (curr > 0) {
19
+ s = BASE_62[curr % 62] + s;
20
+ curr = Math.floor(curr / 62);
21
+ }
22
+ return s;
23
+ }
24
+
25
+ /**
26
+ * Decodes a Base-62 string into a non-negative integer.
27
+ */
28
+ function fromBase62(s: string): number {
29
+ let n = 0;
30
+ for (let i = 0; i < s.length; i++) {
31
+ const idx = BASE_62.indexOf(s[i]);
32
+ if (idx === -1) return 0;
33
+ n = n * 62 + idx;
34
+ }
35
+ return n;
36
+ }
37
+
38
+ /**
39
+ * Encodes an integer into a prefix-encoded string such that standard
40
+ * string comparison strictly matches integer comparison.
41
+ *
42
+ * Non-negative integers (0, 1, 2, ...):
43
+ * Prefix 'a'-'z' specifies the digit count (1 to 26 digits).
44
+ * 0 -> "a0", 1 -> "a1", 61 -> "az", 62 -> "b10", ...
45
+ *
46
+ * Negative integers (-1, -2, ...):
47
+ * Prefix 'Z'-'A' specifies inverted digit count with inverted digits.
48
+ * -1 -> "Zz", -2 -> "Zy", ...
49
+ */
50
+ export function encodeInteger(n: number): string {
51
+ if (n >= 0) {
52
+ const digits = toBase62(n);
53
+ const prefixCode = 97 + digits.length - 1; // 97 is 'a'
54
+ const prefix = String.fromCharCode(Math.min(prefixCode, 122)); // clamp to 'z'
55
+ return prefix + digits;
56
+ } else {
57
+ const pos = -n - 1;
58
+ const digits = toBase62(pos);
59
+ let inverted = '';
60
+ for (let i = 0; i < digits.length; i++) {
61
+ const idx = BASE_62.indexOf(digits[i]);
62
+ inverted += BASE_62[61 - idx];
63
+ }
64
+ const prefixCode = 90 - (digits.length - 1); // 90 is 'Z'
65
+ const prefix = String.fromCharCode(Math.max(prefixCode, 65)); // clamp to 'A'
66
+ return prefix + inverted;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Decodes a prefix-encoded integer string back into a number.
72
+ */
73
+ export function decodeInteger(s: string): number {
74
+ if (!s || s.length < 2) return 0;
75
+ const prefix = s[0];
76
+ if (prefix >= 'a' && prefix <= 'z') {
77
+ const len = prefix.charCodeAt(0) - 97 + 1;
78
+ const digits = s.slice(1, 1 + len);
79
+ return fromBase62(digits);
80
+ } else if (prefix >= 'A' && prefix <= 'Z') {
81
+ const len = 90 - prefix.charCodeAt(0) + 1;
82
+ const inverted = s.slice(1, 1 + len);
83
+ let digits = '';
84
+ for (let i = 0; i < inverted.length; i++) {
85
+ const idx = BASE_62.indexOf(inverted[i]);
86
+ digits += idx !== -1 ? BASE_62[61 - idx] : '0';
87
+ }
88
+ const pos = fromBase62(digits);
89
+ return -pos - 1;
90
+ }
91
+ return 0;
92
+ }
93
+
94
+ /**
95
+ * Extracts the integer component from an order key.
96
+ */
97
+ export function getIntegerPart(key: string): string {
98
+ if (!key || key.length < 2) return 'a0';
99
+ const prefix = key[0];
100
+ if (prefix >= 'a' && prefix <= 'z') {
101
+ const len = prefix.charCodeAt(0) - 97 + 1;
102
+ return key.slice(0, Math.min(key.length, 1 + len));
103
+ } else if (prefix >= 'A' && prefix <= 'Z') {
104
+ const len = 90 - prefix.charCodeAt(0) + 1;
105
+ return key.slice(0, Math.min(key.length, 1 + len));
106
+ }
107
+ return 'a0';
108
+ }
109
+
110
+ /**
111
+ * Computes a fractional suffix strictly between suffixes `a` and `b` (a < result < b).
112
+ * Missing digits in `a` are treated as '0', so `a` may be shorter than `b`.
113
+ * `b === null` means there is no upper bound.
114
+ */
115
+ function midpointSuffix(a: string, b: string | null): string {
116
+ if (b !== null) {
117
+ let n = 0;
118
+ while (n < b.length && (a[n] ?? '0') === b[n]) {
119
+ n++;
120
+ }
121
+ if (n > 0) {
122
+ return b.slice(0, n) + midpointSuffix(a.slice(n), b.slice(n));
123
+ }
124
+ }
125
+
126
+ const digitA = a.length > 0 ? BASE_62.indexOf(a[0]) : 0;
127
+ const digitB = b !== null ? BASE_62.indexOf(b[0]) : BASE_62.length;
128
+
129
+ if (digitB - digitA > 1) {
130
+ return BASE_62[Math.floor((digitA + digitB) / 2)];
131
+ }
132
+
133
+ // Adjacent digits: if b has more digits, its first digit alone already sits between a and b.
134
+ if (b !== null && b.length > 1) {
135
+ return b[0];
136
+ }
137
+
138
+ // Otherwise keep a's digit and subdivide the remainder with no upper bound.
139
+ return BASE_62[digitA] + midpointSuffix(a.slice(1), null);
140
+ }
141
+
142
+ /**
143
+ * Generates a default initial order key for an index with optional spacing.
144
+ * E.g. index 0 -> "a0", index 1 (spacing 2) -> "a2", index 2 -> "a4"
145
+ */
146
+ export function getInitialKey(index: number, spacing: number = 2): string {
147
+ return encodeInteger(Math.max(0, index) * Math.max(1, spacing));
148
+ }
149
+
150
+ /**
151
+ * Generates a single key strictly between keys `a` and `b` (a < key < b).
152
+ * Handles null/undefined for lower and upper bounds.
153
+ */
154
+ export function generateKeyBetween(
155
+ a: string | null | undefined,
156
+ b: string | null | undefined
157
+ ): string {
158
+ const hasA = a !== null && a !== undefined && a !== '';
159
+ const hasB = b !== null && b !== undefined && b !== '';
160
+
161
+ if (!hasA && !hasB) {
162
+ return 'a0';
163
+ }
164
+
165
+ if (!hasA && hasB) {
166
+ const intB = getIntegerPart(b!);
167
+ if (intB === b) {
168
+ const valB = decodeInteger(intB);
169
+ return encodeInteger(valB - 1);
170
+ }
171
+ // If b has fractional suffix (e.g. "a0V"), integer part is already strictly smaller than b
172
+ return intB;
173
+ }
174
+
175
+ if (hasA && !hasB) {
176
+ const intA = getIntegerPart(a!);
177
+ const valA = decodeInteger(intA);
178
+ return encodeInteger(valA + 1);
179
+ }
180
+
181
+ // Both a and b are present
182
+ if (a! >= b!) {
183
+ throw new RangeError(`generateKeyBetween: lower bound "${a}" must sort before upper bound "${b}"`);
184
+ }
185
+
186
+ const intA = getIntegerPart(a!);
187
+ const intB = getIntegerPart(b!);
188
+
189
+ if (intA !== intB) {
190
+ const valA = decodeInteger(intA);
191
+ const valB = decodeInteger(intB);
192
+
193
+ if (valB - valA > 1) {
194
+ const midVal = Math.floor((valA + valB) / 2);
195
+ return encodeInteger(midVal);
196
+ }
197
+
198
+ if (valB - valA === 1) {
199
+ const suffixA = a!.slice(intA.length);
200
+ return intA + midpointSuffix(suffixA, null);
201
+ }
202
+ }
203
+
204
+ // Same integer part or fractional subdivision
205
+ const suffixA = a!.slice(intA.length);
206
+ const suffixB = b!.slice(intB.length);
207
+ return intA + midpointSuffix(suffixA, suffixB);
208
+ }
209
+
210
+ /**
211
+ * Generates `count` keys in strictly ascending order between keys `a` and `b`.
212
+ * Uses a balanced divide-and-conquer partition to guarantee even spacing.
213
+ */
214
+ export function generateNKeysBetween(
215
+ a: string | null | undefined,
216
+ b: string | null | undefined,
217
+ count: number
218
+ ): string[] {
219
+ if (count <= 0) return [];
220
+ if (count === 1) return [generateKeyBetween(a, b)];
221
+
222
+ const result: string[] = new Array(count);
223
+
224
+ function fill(
225
+ leftKey: string | null | undefined,
226
+ rightKey: string | null | undefined,
227
+ startIdx: number,
228
+ endIdx: number
229
+ ) {
230
+ if (startIdx > endIdx) return;
231
+ const midIdx = Math.floor((startIdx + endIdx) / 2);
232
+ const midKey = generateKeyBetween(leftKey, rightKey);
233
+ result[midIdx] = midKey;
234
+ fill(leftKey, midKey, startIdx, midIdx - 1);
235
+ fill(midKey, rightKey, midIdx + 1, endIdx);
236
+ }
237
+
238
+ fill(a, b, 0, count - 1);
239
+ return result;
240
+ }
241
+
242
+ /**
243
+ * Standard comparator for fractional order indices.
244
+ * Uses strict code-point comparison matching Firestore, SQLite, and JavaScript array.sort().
245
+ */
246
+ export function compareOrderIndices(
247
+ a: string | null | undefined,
248
+ b: string | null | undefined
249
+ ): number {
250
+ if (!a && !b) return 0;
251
+ if (!a) return 1;
252
+ if (!b) return -1;
253
+ return a < b ? -1 : a > b ? 1 : 0;
254
+ }
@@ -2,4 +2,6 @@ export * from './status.js';
2
2
  export * from './key.js';
3
3
  export * from './workflow.js';
4
4
  export * from './mentions.js';
5
+ export * from './fractional-index.js';
6
+
5
7
 
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect } from 'vitest';
2
- import { generateProjectKey, validateProjectKey, formatTaskKey } from './key.js';
2
+ import { generateProjectKey, validateProjectKey, formatTaskKey, isTempTaskId } from './key.js';
3
3
 
4
4
  describe('Project Key Utilities', () => {
5
5
  describe('generateProjectKey', () => {
@@ -52,4 +52,25 @@ describe('Project Key Utilities', () => {
52
52
  expect(formatTaskKey('', 10)).toBe('TASK-10');
53
53
  });
54
54
  });
55
+
56
+ describe('isTempTaskId', () => {
57
+ it('detects temp_ prefixed IDs', () => {
58
+ expect(isTempTaskId('temp_123456_abc')).toBe(true);
59
+ expect(isTempTaskId('#temp_123456_abc')).toBe(true);
60
+ });
61
+
62
+ it('detects temp- prefixed IDs', () => {
63
+ expect(isTempTaskId('temp-task-1')).toBe(true);
64
+ expect(isTempTaskId('#temp-task-1')).toBe(true);
65
+ });
66
+
67
+ it('returns false for permanent or invalid IDs', () => {
68
+ expect(isTempTaskId('task_123')).toBe(false);
69
+ expect(isTempTaskId('PROJ-1')).toBe(false);
70
+ expect(isTempTaskId(null)).toBe(false);
71
+ expect(isTempTaskId(undefined)).toBe(false);
72
+ expect(isTempTaskId('')).toBe(false);
73
+ });
74
+ });
55
75
  });
76
+
package/src/utils/key.ts CHANGED
@@ -49,3 +49,14 @@ export function formatTaskKey(projectKey: string, taskNumber: number): string {
49
49
  const prefix = projectKey ? projectKey.toUpperCase() : 'TASK';
50
50
  return `${prefix}-${taskNumber}`;
51
51
  }
52
+
53
+ /**
54
+ * Checks whether a given task ID represents a temporary/optimistic task
55
+ * (e.g. temp_1790... or temp-task-...) while it is actively being created.
56
+ */
57
+ export function isTempTaskId(id?: string | null): boolean {
58
+ if (!id || typeof id !== 'string') return false;
59
+ const clean = id.trim().replace(/^#/, '');
60
+ return clean.startsWith('temp_') || clean.startsWith('temp-');
61
+ }
62
+
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect } from 'vitest';
2
- import { extractMentions, parseMentionSegments } from './mentions.js';
2
+ import { extractMentions, parseMentionSegments, stripMarkdownCode } from './mentions.js';
3
3
 
4
4
  describe('mentions utility', () => {
5
5
  describe('extractMentions', () => {
@@ -37,6 +37,42 @@ describe('mentions utility', () => {
37
37
  const text = 'Check with @turquoise. Then ping @john.doe! Also ask @coordinator, and @"Jane Doe".';
38
38
  expect(extractMentions(text)).toEqual(['turquoise', 'john.doe', 'coordinator', 'Jane Doe']);
39
39
  });
40
+
41
+ it('suppresses mentions inside fenced code blocks and inline backticks (UCH-128, UCH-138)', () => {
42
+ const markdown = `
43
+ Hey @alice, please review this test output:
44
+ \`\`\`ts
45
+ import { describe } from '@vitest/runner';
46
+ // mention in code comment: @bob
47
+ const handler = () => '@charlie';
48
+ \`\`\`
49
+ Also do not match \`@david\` in inline backticks or ~~~@eva~~~ in tilde fences.
50
+ Only real mentions like @frank should match.
51
+ `;
52
+ expect(extractMentions(markdown)).toEqual(['alice', 'frank']);
53
+ });
54
+
55
+ it('suppresses mentions inside HTML <pre> and <code> blocks', () => {
56
+ const html = 'Hello @alice! Check <pre>npm i @types/node</pre> and <code>@bob</code>. Thanks @charlie!';
57
+ expect(extractMentions(html)).toEqual(['alice', 'charlie']);
58
+ });
59
+
60
+ it('suppresses handles inside URLs and markdown link destinations', () => {
61
+ const text = 'Visit https://github.com/@org/repo and [profile](https://example.com/@jack) then ping @jack';
62
+ expect(extractMentions(text)).toEqual(['jack']);
63
+ });
64
+
65
+ it('preserves rich text HTML mention nodes while ignoring attributes', () => {
66
+ const html = '<p>Assigned to <span data-type="mention" data-label="Jane Doe" data-mention-suggestion-char="@">@Jane Doe</span> and ping @coordinator</p>';
67
+ expect(extractMentions(html)).toEqual(['Jane Doe', 'coordinator']);
68
+ });
69
+ });
70
+
71
+ describe('stripMarkdownCode', () => {
72
+ it('strips code blocks, tilde blocks, inline backticks, pre and code tags', () => {
73
+ const raw = 'Before ```code @foo``` and `inline @bar` and <pre>pre @baz</pre> and <code>c @qux</code> after @real';
74
+ expect(stripMarkdownCode(raw)).toBe('Before and and and after @real');
75
+ });
40
76
  });
41
77
 
42
78
  describe('parseMentionSegments', () => {
@@ -6,29 +6,72 @@ export interface MentionSegment {
6
6
 
7
7
  /**
8
8
  * Regex matching mentions:
9
- * - Quoted mentions: @"Jane Doe"
10
- * - Standard mentions: @jane_doe, @planner, @user-1, @john.smith
11
- * Note: Does not match emails like foo@bar.com (requires word boundary or start of string before @).
9
+ * - Quoted mentions: @"Jane Doe", &quot;Jane Doe&quot;
10
+ * - Standard handles: @planner, @user-1, @john.smith
11
+ * Unquoted handles exclude trailing punctuation (e.g. @turquoise. matches handle "turquoise" without the dot).
12
12
  */
13
- export const MENTION_REGEX = /(?:^|\s)@(?:"([^"]+)"|([a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)*))/g;
13
+ export const MENTION_REGEX =
14
+ /(?:^|[\s>(*_"';\\/[\]{}~`:]|&quot;|&gt;|&lt;|&amp;)@(?:"([^"]+)"|&quot;([^&]+)&quot;|([a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)*))/g;
14
15
 
15
16
  /**
16
- * Extracts unique mention handles from a text string.
17
- * Strips quotes and the leading '@' symbol.
17
+ * Strips code blocks and inline code from markdown or HTML content:
18
+ * - Fenced code blocks: ```...``` and ~~~...~~~
19
+ * - Inline backtick code: `...`
20
+ * - HTML code/pre tags: <pre>...</pre>, <code>...</code>
21
+ * Used to avoid false-positive mention parsing within code snippets, terminal logs, or stack traces.
22
+ */
23
+ export function stripMarkdownCode(content: string): string {
24
+ if (!content || typeof content !== 'string') return '';
25
+ return content
26
+ .replace(/```[\s\S]*?```/g, '')
27
+ .replace(/~~~[\s\S]*?~~~/g, '')
28
+ .replace(/<pre[\s\S]*?<\/pre>/gi, '')
29
+ .replace(/<code[\s\S]*?<\/code>/gi, '')
30
+ .replace(/`[^`\n]*`/g, '');
31
+ }
32
+
33
+ /**
34
+ * Extracts unique mention handles from a text string, ignoring trailing punctuation,
35
+ * code blocks or inline code snippets, URLs, markdown link destinations, and pre-existing HTML mention nodes.
18
36
  * Preserves the order of their first appearance.
19
37
  */
20
38
  export function extractMentions(content: string): string[] {
21
39
  if (!content || typeof content !== 'string') return [];
22
40
 
41
+ // Normalize rich text mention nodes (e.g. from TipTap or custom mention spans)
42
+ const normalizedMentionNodes = content.replace(
43
+ /<span\b[^>]*\b(?:data-type=["']mention["']|class=["'][^"']*pixerate-mention-node[^"']*["'])[^>]*>([\s\S]*?)<\/span>/gi,
44
+ (match, inner) => {
45
+ const labelMatch = match.match(/\bdata-label=["']([^"']+)["']/i);
46
+ if (labelMatch) {
47
+ const val = labelMatch[1].trim();
48
+ return val.includes(' ') ? ` @"${val}" ` : ` @${val} `;
49
+ }
50
+ const idMatch = match.match(/\bdata-id=["']([^"']+)["']/i);
51
+ if (idMatch) {
52
+ const val = idMatch[1].trim();
53
+ return val.includes(' ') ? ` @"${val}" ` : ` @${val} `;
54
+ }
55
+ return ` ${inner} `;
56
+ }
57
+ );
58
+
59
+ const cleanContent = stripMarkdownCode(normalizedMentionNodes);
60
+ // Strip URLs and markdown link destinations so @package or @handles in URLs are not extracted as mentions
61
+ const withoutUrls = cleanContent
62
+ .replace(/(?:https?|ftp|file):\/\/[^\s<>()]+/gi, '')
63
+ .replace(/\]\([^)]*\)/g, ']');
64
+ // Strip remaining HTML tags
65
+ const textOnly = withoutUrls.replace(/<[^>]+>/g, ' ');
66
+
23
67
  const mentions: string[] = [];
24
68
  const seen = new Set<string>();
25
69
 
26
- // Reset regex lastIndex
27
70
  const regex = new RegExp(MENTION_REGEX.source, 'g');
28
71
  let match: RegExpExecArray | null;
29
72
 
30
- while ((match = regex.exec(content)) !== null) {
31
- const handle = match[1] ?? match[2];
73
+ while ((match = regex.exec(textOnly)) !== null) {
74
+ const handle = (match[1] ?? match[2] ?? match[3] ?? '').trim();
32
75
  if (handle && !seen.has(handle)) {
33
76
  seen.add(handle);
34
77
  mentions.push(handle);
@@ -52,12 +95,11 @@ export function parseMentionSegments(content: string): MentionSegment[] {
52
95
 
53
96
  while ((match = regex.exec(content)) !== null) {
54
97
  const fullMatch = match[0];
55
- const leadingWhitespace = fullMatch.startsWith(' ') || fullMatch.startsWith('\t') || fullMatch.startsWith('\n')
56
- ? fullMatch[0]
57
- : '';
58
- const mentionToken = fullMatch.slice(leadingWhitespace.length);
59
- const handle = match[1] ?? match[2];
60
- const matchStart = match.index + leadingWhitespace.length;
98
+ const atIndex = fullMatch.indexOf('@');
99
+ const prefix = atIndex > 0 ? fullMatch.slice(0, atIndex) : '';
100
+ const mentionToken = fullMatch.slice(atIndex);
101
+ const handle = match[1] ?? match[2] ?? match[3];
102
+ const matchStart = match.index + prefix.length;
61
103
 
62
104
  // Push text before this mention if any
63
105
  if (matchStart > lastIndex) {
@@ -74,7 +116,7 @@ export function parseMentionSegments(content: string): MentionSegment[] {
74
116
  handle
75
117
  });
76
118
 
77
- lastIndex = match.index + fullMatch.length;
119
+ lastIndex = matchStart + mentionToken.length;
78
120
  }
79
121
 
80
122
  // Push any remaining text after the last match