@semiont/api-client 0.2.34-build.92 → 0.2.34

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.
@@ -288,15 +288,10 @@ function findTextWithContext(content, exact, prefix, suffix, positionHint) {
288
288
  index = content.indexOf(exact, index + 1);
289
289
  }
290
290
  if (occurrences.length === 0) {
291
- console.warn(`[FuzzyAnchor] Exact text not found, trying fuzzy match: "${exact.substring(0, 50)}..."`);
292
291
  const fuzzyMatch = findBestTextMatch(content, exact, positionHint);
293
292
  if (fuzzyMatch) {
294
- console.warn(
295
- `[FuzzyAnchor] Found ${fuzzyMatch.matchQuality} match at position ${fuzzyMatch.start}`
296
- );
297
293
  return { start: fuzzyMatch.start, end: fuzzyMatch.end };
298
294
  }
299
- console.warn(`[FuzzyAnchor] No acceptable match found for: "${exact.substring(0, 50)}..."`);
300
295
  return null;
301
296
  }
302
297
  if (occurrences.length === 1) {
@@ -315,23 +310,16 @@ function findTextWithContext(content, exact, prefix, suffix, positionHint) {
315
310
  return { start: pos2, end: pos2 + exact.length };
316
311
  }
317
312
  }
318
- console.warn(
319
- `[FuzzyAnchor] Multiple matches found but none match prefix/suffix exactly. Exact: "${exact.substring(0, 30)}...", Prefix: "${prefix?.substring(0, 20) || "none"}", Suffix: "${suffix?.substring(0, 20) || "none"}"`
320
- );
321
313
  for (const pos2 of occurrences) {
322
314
  const actualPrefix = content.substring(Math.max(0, pos2 - (prefix?.length || 0)), pos2);
323
315
  const actualSuffix = content.substring(pos2 + exact.length, pos2 + exact.length + (suffix?.length || 0));
324
316
  const fuzzyPrefixMatch = !prefix || actualPrefix.includes(prefix.trim());
325
317
  const fuzzySuffixMatch = !suffix || actualSuffix.includes(suffix.trim());
326
318
  if (fuzzyPrefixMatch && fuzzySuffixMatch) {
327
- console.warn(`[FuzzyAnchor] Using fuzzy context match at position ${pos2}`);
328
319
  return { start: pos2, end: pos2 + exact.length };
329
320
  }
330
321
  }
331
322
  }
332
- console.warn(
333
- `[FuzzyAnchor] Multiple matches but no context match. Using first occurrence. Exact: "${exact.substring(0, 30)}..."`
334
- );
335
323
  const pos = occurrences[0];
336
324
  return { start: pos, end: pos + exact.length };
337
325
  }
@@ -595,7 +583,6 @@ function extractContext(content, start, end) {
595
583
  return { prefix, suffix };
596
584
  }
597
585
  function validateAndCorrectOffsets(content, aiStart, aiEnd, exact) {
598
- const exactPreview = exact.length > 50 ? exact.substring(0, 50) + "..." : exact;
599
586
  const textAtOffset = content.substring(aiStart, aiEnd);
600
587
  if (textAtOffset === exact) {
601
588
  const context2 = extractContext(content, aiStart, aiEnd);
@@ -609,47 +596,13 @@ function validateAndCorrectOffsets(content, aiStart, aiEnd, exact) {
609
596
  matchQuality: "exact"
610
597
  };
611
598
  }
612
- const foundPreview = textAtOffset.length > 50 ? textAtOffset.substring(0, 50) + "..." : textAtOffset;
613
- console.warn(
614
- `[validateAndCorrectOffsets] \u26A0 AI offset mismatch:
615
- Expected text: "${exactPreview}"
616
- Found at AI offset (${aiStart}-${aiEnd}): "${foundPreview}"
617
- Attempting multi-strategy search...`
618
- );
619
599
  const match = findBestTextMatch(content, exact, aiStart);
620
600
  if (!match) {
621
- const exactLong = exact.length > 100 ? exact.substring(0, 100) + "..." : exact;
622
- console.error(
623
- `[validateAndCorrectOffsets] \u2717 No acceptable match found:
624
- AI offsets: start=${aiStart}, end=${aiEnd}
625
- AI text: "${exactLong}"
626
- Text at AI offset: "${foundPreview}"
627
- All search strategies (exact, case-insensitive, fuzzy) failed.
628
- This suggests the AI hallucinated text that doesn't exist in the document.`
629
- );
630
601
  throw new Error(
631
602
  "Cannot find acceptable match for text in content. All search strategies failed. Text may be hallucinated."
632
603
  );
633
604
  }
634
605
  const actualText = content.substring(match.start, match.end);
635
- const actualPreview = actualText.length > 50 ? actualText.substring(0, 50) + "..." : actualText;
636
- const offsetDelta = match.start - aiStart;
637
- const matchSymbol = match.matchQuality === "exact" ? "\u2713" : match.matchQuality === "case-insensitive" ? "\u2248" : "~";
638
- console.warn(
639
- `[validateAndCorrectOffsets] ${matchSymbol} Found ${match.matchQuality} match:
640
- AI offsets: start=${aiStart}, end=${aiEnd}
641
- Corrected: start=${match.start}, end=${match.end}
642
- Offset delta: ${offsetDelta} characters
643
- Actual text: "${actualPreview}"`
644
- );
645
- if (match.matchQuality === "fuzzy") {
646
- console.warn(
647
- `[validateAndCorrectOffsets] Fuzzy match details:
648
- AI provided: "${exactPreview}"
649
- Found in doc: "${actualPreview}"
650
- Minor text differences detected - using document version`
651
- );
652
- }
653
606
  const context = extractContext(content, match.start, match.end);
654
607
  return {
655
608
  start: match.start,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/annotations.ts","../../src/utils/fuzzy-anchor.ts","../../src/utils/locales.ts","../../src/utils/resources.ts","../../src/utils/svg-utils.ts","../../src/utils/text-context.ts","../../src/utils/text-encoding.ts","../../src/utils/validation.ts"],"names":["pos","context"],"mappings":";;;AA+BO,SAAS,cAAc,IAAA,EAA8C;AAC1E,EAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAA,EAAG;AAEvB,IAAA,KAAA,MAAW,QAAQ,IAAA,EAAM;AACvB,MAAA,IACE,OAAO,SAAS,QAAA,IAChB,IAAA,KAAS,QACT,MAAA,IAAU,IAAA,IACV,YAAY,IAAA,EACZ;AACA,QAAA,MAAM,WAAY,IAAA,CAA2B,IAAA;AAC7C,QAAA,MAAM,aAAc,IAAA,CAA6B,MAAA;AAEjD,QAAA,IAAI,QAAA,KAAa,kBAAA,IAAsB,OAAO,UAAA,KAAe,QAAA,EAAU;AACrE,UAAA,OAAO,YAAY,UAAU,CAAA;AAAA,QAC/B;AAAA,MACF;AAAA,IACF;AACA,IAAA,OAAO,IAAA;AAAA,EACT;AAGA,EAAA,IACE,OAAO,SAAS,QAAA,IAChB,IAAA,KAAS,QACT,MAAA,IAAU,IAAA,IACV,YAAY,IAAA,EACZ;AACA,IAAA,MAAM,WAAY,IAAA,CAA2B,IAAA;AA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AAM,OAAA,GAAU;AAAA,OAClD;AAAA,IACF;AAAA,EACF;AACF;AAiBO,SAAS,YAAA,CACd,QACA,IAAA,EACqB;AACrB,EAAA,IAAI;AACF,IAAA,MAAM,SAAA,GAAY,MAAA,CAAO,KAAA,CAAM,IAAI,CAAA;AACnC,IAAA,OAAO,EAAE,OAAA,EAAS,IAAA,EAAM,IAAA,EAAM,SAAA,EAAU;AAAA,EAC1C,SAAS,KAAA,EAAO;AACd,IAAA,OAAO;AAAA,MACL,OAAA,EAAS,KAAA;AAAA,MACT,KAAA,EAAO,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU;AAAA,KAClD;AAAA,EACF;AACF;AAUO,SAAS,aAAa,KAAA,EAAwB;AACnD,EAAA,IAAI,KAAA,CAAM,MAAA,GAAS,CAAA,IAAK,KAAA,CAAM,SAAS,GAAA,EAAK;AAC1C,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,MAAM,UAAA,GAAa,4BAAA;AACnB,EAAA,OAAO,UAAA,CAAW,KAAK,KAAK,CAAA;AAC9B","file":"index.js","sourcesContent":["/**\n * Annotation and Selector Utilities\n *\n * Pure TypeScript utilities for working with W3C Web Annotations.\n * No React dependencies - safe to use in any JavaScript environment.\n *\n * Body is either empty array (stub) or single SpecificResource (resolved)\n * Body can be array of TextualBody (tagging) + SpecificResource (linking)\n * Target can be simple string IRI or object with source and optional selector\n */\n\nimport type { components } from '@semiont/core';\nimport type { ResourceUri } from '@semiont/core';\nimport { resourceUri } from '@semiont/core';\n\ntype Annotation = components['schemas']['Annotation'];\ntype HighlightAnnotation = Annotation;\ntype ReferenceAnnotation = Annotation;\ntype TextPositionSelector = components['schemas']['TextPositionSelector'];\ntype TextQuoteSelector = components['schemas']['TextQuoteSelector'];\ntype SvgSelector = components['schemas']['SvgSelector'];\ntype FragmentSelector = components['schemas']['FragmentSelector'];\ntype Selector = TextPositionSelector | TextQuoteSelector | SvgSelector | FragmentSelector;\n\n// Re-export selector types for convenience\nexport type { TextPositionSelector, TextQuoteSelector, SvgSelector, FragmentSelector, Selector };\n\n/**\n * Get the source from an annotation body (null if stub)\n * Search for SpecificResource in body array\n */\nexport function getBodySource(body: Annotation['body']): ResourceUri | null {\n if (Array.isArray(body)) {\n // Search for SpecificResource with source\n for (const item of body) {\n if (\n typeof item === 'object' &&\n item !== null &&\n 'type' in item &&\n 'source' in item\n ) {\n const itemType = (item as { type: unknown }).type;\n const itemSource = (item as { source: unknown }).source;\n\n if (itemType === 'SpecificResource' && typeof itemSource === 'string') {\n return resourceUri(itemSource);\n }\n }\n }\n return null; // No SpecificResource found = stub\n }\n\n // Single body object (SpecificResource)\n if (\n typeof body === 'object' &&\n body !== null &&\n 'type' in body &&\n 'source' in body\n ) {\n const bodyType = (body as { type: unknown }).type;\n const bodySource = (body as { source: unknown }).source;\n\n if (bodyType === 'SpecificResource' && typeof bodySource === 'string') {\n return resourceUri(bodySource);\n }\n }\n\n return null;\n}\n\n/**\n * Get the type from an annotation body (returns first body type in array)\n */\nexport function getBodyType(body: Annotation['body']): 'TextualBody' | 'SpecificResource' | null {\n if (Array.isArray(body)) {\n if (body.length === 0) {\n return null;\n }\n // Return type of first body item\n if (typeof body[0] === 'object' && body[0] !== null && 'type' in body[0]) {\n const firstType = (body[0] as { type: unknown }).type;\n if (firstType === 'TextualBody' || firstType === 'SpecificResource') {\n return firstType;\n }\n }\n return null;\n }\n\n // Single body object\n if (typeof body === 'object' && body !== null && 'type' in body) {\n const bodyType = (body as { type: unknown }).type;\n if (bodyType === 'TextualBody' || bodyType === 'SpecificResource') {\n return bodyType;\n }\n }\n\n return null;\n}\n\n/**\n * Check if body is resolved (has a source)\n * Check for SpecificResource in body array\n */\nexport function isBodyResolved(body: Annotation['body']): boolean {\n return getBodySource(body) !== null;\n}\n\n/**\n * Get the source IRI from target (handles both string and object forms)\n */\nexport function getTargetSource(target: Annotation['target']): ResourceUri {\n if (typeof target === 'string') {\n return resourceUri(target);\n }\n return resourceUri(target.source);\n}\n\n/**\n * Get the selector from target (undefined if string or no selector)\n */\nexport function getTargetSelector(target: Annotation['target']) {\n if (typeof target === 'string') {\n return undefined;\n }\n return target.selector;\n}\n\n/**\n * Check if target has a selector\n */\nexport function hasTargetSelector(target: Annotation['target']): boolean {\n return typeof target !== 'string' && target.selector !== undefined;\n}\n\n/**\n * Type guard to check if an annotation is a highlight\n */\nexport function isHighlight(annotation: Annotation): annotation is HighlightAnnotation {\n return annotation.motivation === 'highlighting';\n}\n\n/**\n * Type guard to check if an annotation is a reference (linking)\n */\nexport function isReference(annotation: Annotation): annotation is ReferenceAnnotation {\n return annotation.motivation === 'linking';\n}\n\n/**\n * Type guard to check if an annotation is an assessment\n */\nexport function isAssessment(annotation: Annotation): annotation is Annotation {\n return annotation.motivation === 'assessing';\n}\n\n/**\n * Type guard to check if an annotation is a comment\n */\nexport function isComment(annotation: Annotation): annotation is Annotation {\n return annotation.motivation === 'commenting';\n}\n\n/**\n * Type guard to check if an annotation is a tag\n */\nexport function isTag(annotation: Annotation): annotation is Annotation {\n return annotation.motivation === 'tagging';\n}\n\n/**\n * Extract comment text from a comment annotation's body\n * @param annotation - The annotation to extract comment text from\n * @returns The comment text, or undefined if not a comment or no text found\n */\nexport function getCommentText(annotation: Annotation): string | undefined {\n if (!isComment(annotation)) return undefined;\n const body = Array.isArray(annotation.body) ? annotation.body[0] : annotation.body;\n if (body && 'value' in body) {\n return body.value;\n }\n return undefined;\n}\n\n/**\n * Type guard to check if a reference annotation is a stub (unresolved)\n * Stub if no SpecificResource in body array\n */\nexport function isStubReference(annotation: Annotation): boolean {\n return isReference(annotation) && !isBodyResolved(annotation.body);\n}\n\n/**\n * Type guard to check if a reference annotation is resolved\n * Resolved if SpecificResource exists in body array\n */\nexport function isResolvedReference(annotation: Annotation): annotation is ReferenceAnnotation {\n return isReference(annotation) && isBodyResolved(annotation.body);\n}\n\n// =============================================================================\n// SELECTOR UTILITIES\n// =============================================================================\n\n/**\n * Get the exact text from a selector (single or array)\n *\n * When selector is an array, tries to find a TextQuoteSelector (which has exact text).\n * TextPositionSelector does not have exact text, only character offsets.\n * Handles undefined selector (when target is a string IRI with no selector)\n */\nexport function getExactText(selector: Selector | Selector[] | undefined): string {\n if (!selector) {\n return ''; // No selector means entire resource\n }\n const selectors = Array.isArray(selector) ? selector : [selector];\n\n // Try to find TextQuoteSelector (has exact text)\n const quoteSelector = selectors.find(s => s.type === 'TextQuoteSelector') as TextQuoteSelector | undefined;\n if (quoteSelector) {\n return quoteSelector.exact;\n }\n\n // No TextQuoteSelector found\n return '';\n}\n\n/**\n * Get the exact text from an annotation's target selector\n * Uses getTargetSelector helper to safely get selector\n */\nexport function getAnnotationExactText(annotation: Annotation): string {\n const selector = getTargetSelector(annotation.target);\n return getExactText(selector as Selector | Selector[] | undefined);\n}\n\n/**\n * Get the primary selector from a selector (single or array)\n *\n * When selector is an array, returns the first selector.\n * When selector is a single object, returns it as-is.\n */\nexport function getPrimarySelector(selector: Selector | Selector[]): Selector {\n if (Array.isArray(selector)) {\n if (selector.length === 0) {\n throw new Error('Empty selector array');\n }\n const first = selector[0];\n if (!first) {\n throw new Error('Invalid selector array');\n }\n return first;\n }\n return selector;\n}\n\n/**\n * Get TextPositionSelector from a selector (single or array)\n *\n * Returns the first TextPositionSelector found, or null if none exists.\n * Handles undefined selector (when target is a string IRI with no selector)\n */\nexport function getTextPositionSelector(selector: Selector | Selector[] | undefined): TextPositionSelector | null {\n if (!selector) return null; // No selector means entire resource\n const selectors = Array.isArray(selector) ? selector : [selector];\n const found = selectors.find(s => s.type === 'TextPositionSelector');\n if (!found) return null;\n return found.type === 'TextPositionSelector' ? found : null;\n}\n\n/**\n * Get TextQuoteSelector from a selector (single or array)\n *\n * Returns the first TextQuoteSelector found, or null if none exists.\n */\nexport function getTextQuoteSelector(selector: Selector | Selector[]): TextQuoteSelector | null {\n const selectors = Array.isArray(selector) ? selector : [selector];\n const found = selectors.find(s => s.type === 'TextQuoteSelector');\n if (!found) return null;\n return found.type === 'TextQuoteSelector' ? found : null;\n}\n\n/**\n * Get SvgSelector from a selector (single or array)\n *\n * Returns the first SvgSelector found, or null if none exists.\n */\nexport function getSvgSelector(selector: Selector | Selector[] | undefined): SvgSelector | null {\n if (!selector) return null;\n const selectors = Array.isArray(selector) ? selector : [selector];\n const found = selectors.find(s => s.type === 'SvgSelector');\n if (!found) return null;\n return found.type === 'SvgSelector' ? found : null;\n}\n\n/**\n * Get FragmentSelector from a selector (single or array)\n *\n * Returns the first FragmentSelector found, or null if none exists.\n */\nexport function getFragmentSelector(selector: Selector | Selector[] | undefined): FragmentSelector | null {\n if (!selector) return null;\n const selectors = Array.isArray(selector) ? selector : [selector];\n const found = selectors.find(s => s.type === 'FragmentSelector');\n if (!found) return null;\n return found.type === 'FragmentSelector' ? found : null;\n}\n\n/**\n * Validate SVG markup for W3C compliance\n *\n * Checks that:\n * - SVG contains xmlns attribute\n * - SVG is well-formed XML\n * - SVG contains at least one shape element\n *\n * @returns null if valid, error message if invalid\n */\nexport function validateSvgMarkup(svg: string): string | null {\n // Check for xmlns attribute (required by W3C spec)\n if (!svg.includes('xmlns=\"http://www.w3.org/2000/svg\"')) {\n return 'SVG must include xmlns=\"http://www.w3.org/2000/svg\" attribute';\n }\n\n // Check for basic SVG tag structure\n if (!svg.includes('<svg') || !svg.includes('</svg>')) {\n return 'SVG must have opening and closing tags';\n }\n\n // Check for at least one shape element\n const shapeElements = ['rect', 'circle', 'ellipse', 'polygon', 'polyline', 'path', 'line'];\n const hasShape = shapeElements.some(shape =>\n svg.includes(`<${shape}`) || svg.includes(`<${shape} `)\n );\n\n if (!hasShape) {\n return 'SVG must contain at least one shape element (rect, circle, ellipse, polygon, polyline, path, or line)';\n }\n\n return null; // Valid\n}\n\n/**\n * Extract bounding box from SVG markup\n *\n * Attempts to extract x, y, width, height from the SVG viewBox or root element.\n * Returns null if bounding box cannot be determined.\n */\nexport function extractBoundingBox(svg: string): { x: number; y: number; width: number; height: number } | null {\n // Try to extract viewBox attribute from SVG element\n const viewBoxMatch = svg.match(/<svg[^>]*viewBox=\"([^\"]+)\"/);\n if (viewBoxMatch) {\n const values = viewBoxMatch[1].split(/\\s+/).map(parseFloat);\n if (values.length === 4 && values.every(v => !isNaN(v))) {\n return {\n x: values[0],\n y: values[1],\n width: values[2],\n height: values[3]\n };\n }\n }\n\n // Try to extract width/height attributes from SVG element (assume x=0, y=0)\n const svgTagMatch = svg.match(/<svg[^>]*>/);\n if (svgTagMatch) {\n const svgTag = svgTagMatch[0];\n const widthMatch = svgTag.match(/width=\"([^\"]+)\"/);\n const heightMatch = svgTag.match(/height=\"([^\"]+)\"/);\n\n if (widthMatch && heightMatch) {\n const width = parseFloat(widthMatch[1]);\n const height = parseFloat(heightMatch[1]);\n\n if (!isNaN(width) && !isNaN(height)) {\n return { x: 0, y: 0, width, height };\n }\n }\n }\n\n return null;\n}\n","/**\n * Fuzzy Anchoring for W3C Web Annotation TextQuoteSelector\n *\n * Uses prefix/suffix context to disambiguate when the same text appears multiple times.\n * Implements fuzzy matching as specified in the W3C Web Annotation Data Model.\n *\n * @see https://www.w3.org/TR/annotation-model/#text-quote-selector\n */\n\nexport interface TextPosition {\n start: number;\n end: number;\n}\n\nexport type MatchQuality = 'exact' | 'normalized' | 'case-insensitive' | 'fuzzy';\n\n/**\n * Normalize text for comparison - handles common document editing changes\n *\n * Collapses whitespace, converts curly quotes to straight quotes,\n * and normalizes common punctuation variations.\n */\nexport function normalizeText(text: string): string {\n return text\n .replace(/\\s+/g, ' ') // collapse whitespace\n .replace(/[\\u2018\\u2019]/g, \"'\") // curly single quotes → straight\n .replace(/[\\u201C\\u201D]/g, '\"') // curly double quotes → straight\n .replace(/\\u2014/g, '--') // em-dash → double hyphen\n .replace(/\\u2013/g, '-') // en-dash → hyphen\n .trim();\n}\n\n/**\n * Calculate Levenshtein distance between two strings\n * Used for fuzzy matching when exact text doesn't match\n */\nfunction levenshteinDistance(str1: string, str2: string): number {\n const len1 = str1.length;\n const len2 = str2.length;\n const matrix: number[][] = [];\n\n // Initialize matrix\n for (let i = 0; i <= len1; i++) {\n matrix[i] = [i];\n }\n for (let j = 0; j <= len2; j++) {\n matrix[0]![j] = j;\n }\n\n // Fill matrix\n for (let i = 1; i <= len1; i++) {\n for (let j = 1; j <= len2; j++) {\n const cost = str1[i - 1] === str2[j - 1] ? 0 : 1;\n const deletion = matrix[i - 1]![j]! + 1;\n const insertion = matrix[i]![j - 1]! + 1;\n const substitution = matrix[i - 1]![j - 1]! + cost;\n matrix[i]![j] = Math.min(deletion, insertion, substitution);\n }\n }\n\n return matrix[len1]![len2]!;\n}\n\n/**\n * Find best match for text in content using multi-strategy search\n *\n * Shared core logic used by both findTextWithContext and validateAndCorrectOffsets.\n *\n * @param content - Full text content to search within\n * @param searchText - The text to find\n * @param positionHint - Optional hint for where to search (TextPositionSelector.start)\n * @returns Match with position and quality, or null if not found\n */\nexport function findBestTextMatch(\n content: string,\n searchText: string,\n positionHint?: number\n): { start: number; end: number; matchQuality: MatchQuality } | null {\n const maxFuzzyDistance = Math.max(5, Math.floor(searchText.length * 0.05)); // 5% tolerance or min 5 chars\n\n // Strategy 1: Exact match (case-sensitive, exact whitespace)\n const exactIndex = content.indexOf(searchText);\n if (exactIndex !== -1) {\n return {\n start: exactIndex,\n end: exactIndex + searchText.length,\n matchQuality: 'exact'\n };\n }\n\n // Strategy 2: Normalized match (handles whitespace/quote variations)\n const normalizedSearch = normalizeText(searchText);\n const normalizedContent = normalizeText(content);\n const normalizedIndex = normalizedContent.indexOf(normalizedSearch);\n if (normalizedIndex !== -1) {\n // Find actual position in original content by counting characters\n let actualPos = 0;\n let normalizedPos = 0;\n while (normalizedPos < normalizedIndex && actualPos < content.length) {\n const char = content[actualPos]!;\n const normalizedChar = normalizeText(char);\n if (normalizedChar) {\n normalizedPos += normalizedChar.length;\n }\n actualPos++;\n }\n return {\n start: actualPos,\n end: actualPos + searchText.length,\n matchQuality: 'normalized'\n };\n }\n\n // Strategy 3: Case-insensitive match\n const lowerContent = content.toLowerCase();\n const lowerSearch = searchText.toLowerCase();\n const caseInsensitiveIndex = lowerContent.indexOf(lowerSearch);\n if (caseInsensitiveIndex !== -1) {\n return {\n start: caseInsensitiveIndex,\n end: caseInsensitiveIndex + searchText.length,\n matchQuality: 'case-insensitive'\n };\n }\n\n // Strategy 4: Fuzzy match using Levenshtein distance with sliding window\n // Search near position hint if provided, otherwise search full content\n const windowSize = searchText.length;\n const searchRadius = Math.min(500, content.length);\n const searchStart = positionHint !== undefined\n ? Math.max(0, positionHint - searchRadius)\n : 0;\n const searchEnd = positionHint !== undefined\n ? Math.min(content.length, positionHint + searchRadius)\n : content.length;\n\n let bestMatch: { start: number; distance: number } | null = null;\n\n // Scan through content with sliding window\n for (let i = searchStart; i <= searchEnd - windowSize; i++) {\n const candidate = content.substring(i, i + windowSize);\n const distance = levenshteinDistance(searchText, candidate);\n\n if (distance <= maxFuzzyDistance) {\n if (!bestMatch || distance < bestMatch.distance) {\n bestMatch = { start: i, distance };\n }\n }\n }\n\n if (bestMatch) {\n return {\n start: bestMatch.start,\n end: bestMatch.start + windowSize,\n matchQuality: 'fuzzy'\n };\n }\n\n return null;\n}\n\n/**\n * Find text using exact match with optional prefix/suffix context\n *\n * When the exact text appears multiple times in the content, prefix and suffix\n * are used to disambiguate and find the correct occurrence.\n *\n * If exact text is not found, uses multi-strategy fuzzy matching (normalization,\n * case-insensitive, Levenshtein distance) to locate changed text.\n *\n * @param content - Full text content to search within\n * @param exact - The exact text to find\n * @param prefix - Optional text that should appear immediately before the match\n * @param suffix - Optional text that should appear immediately after the match\n * @param positionHint - Optional position hint (from TextPositionSelector) for fuzzy search\n * @returns Position of the matched text, or null if not found\n *\n * @example\n * ```typescript\n * const content = \"The cat sat. The cat ran.\";\n * // Find second \"The cat\" occurrence\n * const pos = findTextWithContext(content, \"The cat\", \"sat. \", \" ran\");\n * // Returns { start: 13, end: 20 }\n * ```\n */\nexport function findTextWithContext(\n content: string,\n exact: string,\n prefix?: string,\n suffix?: string,\n positionHint?: number\n): TextPosition | null {\n if (!exact) return null;\n\n // Find all occurrences of exact text\n const occurrences: number[] = [];\n let index = content.indexOf(exact);\n while (index !== -1) {\n occurrences.push(index);\n index = content.indexOf(exact, index + 1);\n }\n\n // No exact matches found - try fuzzy matching\n if (occurrences.length === 0) {\n console.warn(`[FuzzyAnchor] Exact text not found, trying fuzzy match: \"${exact.substring(0, 50)}...\"`);\n\n const fuzzyMatch = findBestTextMatch(content, exact, positionHint);\n\n if (fuzzyMatch) {\n console.warn(\n `[FuzzyAnchor] Found ${fuzzyMatch.matchQuality} match at position ${fuzzyMatch.start}`\n );\n return { start: fuzzyMatch.start, end: fuzzyMatch.end };\n }\n\n console.warn(`[FuzzyAnchor] No acceptable match found for: \"${exact.substring(0, 50)}...\"`);\n return null;\n }\n\n // Only one match - no need for prefix/suffix disambiguation\n if (occurrences.length === 1) {\n const pos = occurrences[0]!; // Safe: length === 1 means first element exists\n return { start: pos, end: pos + exact.length };\n }\n\n // Multiple matches - use prefix/suffix to disambiguate\n if (prefix || suffix) {\n for (const pos of occurrences) {\n // Extract actual prefix from content\n const actualPrefixStart = Math.max(0, pos - (prefix?.length || 0));\n const actualPrefix = content.substring(actualPrefixStart, pos);\n\n // Extract actual suffix from content\n const actualSuffixEnd = Math.min(content.length, pos + exact.length + (suffix?.length || 0));\n const actualSuffix = content.substring(pos + exact.length, actualSuffixEnd);\n\n // Check if prefix matches\n const prefixMatch = !prefix || actualPrefix.endsWith(prefix);\n\n // Check if suffix matches\n const suffixMatch = !suffix || actualSuffix.startsWith(suffix);\n\n if (prefixMatch && suffixMatch) {\n return { start: pos, end: pos + exact.length };\n }\n }\n\n // No match with exact prefix/suffix - try fuzzy matching\n console.warn(\n `[FuzzyAnchor] Multiple matches found but none match prefix/suffix exactly. ` +\n `Exact: \"${exact.substring(0, 30)}...\", ` +\n `Prefix: \"${prefix?.substring(0, 20) || 'none'}\", ` +\n `Suffix: \"${suffix?.substring(0, 20) || 'none'}\"`\n );\n\n // Fallback: try partial prefix/suffix match\n for (const pos of occurrences) {\n const actualPrefix = content.substring(Math.max(0, pos - (prefix?.length || 0)), pos);\n const actualSuffix = content.substring(pos + exact.length, pos + exact.length + (suffix?.length || 0));\n\n // Fuzzy match: check if prefix/suffix are substrings (handles whitespace variations)\n const fuzzyPrefixMatch = !prefix || actualPrefix.includes(prefix.trim());\n const fuzzySuffixMatch = !suffix || actualSuffix.includes(suffix.trim());\n\n if (fuzzyPrefixMatch && fuzzySuffixMatch) {\n console.warn(`[FuzzyAnchor] Using fuzzy context match at position ${pos}`);\n return { start: pos, end: pos + exact.length };\n }\n }\n }\n\n // Fallback: return first occurrence if no prefix/suffix or no match\n console.warn(\n `[FuzzyAnchor] Multiple matches but no context match. Using first occurrence. ` +\n `Exact: \"${exact.substring(0, 30)}...\"`\n );\n const pos = occurrences[0]!; // Safe: we checked length > 0 earlier\n return { start: pos, end: pos + exact.length };\n}\n\n/**\n * Verify that a position correctly points to the exact text\n * Useful for debugging and validation\n */\nexport function verifyPosition(\n content: string,\n position: TextPosition,\n expectedExact: string\n): boolean {\n const actualText = content.substring(position.start, position.end);\n return actualText === expectedExact;\n}\n","/**\n * Locale information\n * Copied from SDK for frontend use\n */\n\nexport interface LocaleInfo {\n code: string;\n nativeName: string;\n englishName: string;\n}\n\nexport const LOCALES: readonly LocaleInfo[] = [\n { code: 'ar', nativeName: 'العربية', englishName: 'Arabic' },\n { code: 'bn', nativeName: 'বাংলা', englishName: 'Bengali' },\n { code: 'cs', nativeName: 'Čeština', englishName: 'Czech' },\n { code: 'da', nativeName: 'Dansk', englishName: 'Danish' },\n { code: 'de', nativeName: 'Deutsch', englishName: 'German' },\n { code: 'el', nativeName: 'Ελληνικά', englishName: 'Greek' },\n { code: 'en', nativeName: 'English', englishName: 'English' },\n { code: 'es', nativeName: 'Español', englishName: 'Spanish' },\n { code: 'fa', nativeName: 'فارسی', englishName: 'Persian' },\n { code: 'fi', nativeName: 'Suomi', englishName: 'Finnish' },\n { code: 'fr', nativeName: 'Français', englishName: 'French' },\n { code: 'he', nativeName: 'עברית', englishName: 'Hebrew' },\n { code: 'hi', nativeName: 'हिन्दी', englishName: 'Hindi' },\n { code: 'id', nativeName: 'Bahasa Indonesia', englishName: 'Indonesian' },\n { code: 'it', nativeName: 'Italiano', englishName: 'Italian' },\n { code: 'ja', nativeName: '日本語', englishName: 'Japanese' },\n { code: 'ko', nativeName: '한국어', englishName: 'Korean' },\n { code: 'ms', nativeName: 'Bahasa Melayu', englishName: 'Malay' },\n { code: 'nl', nativeName: 'Nederlands', englishName: 'Dutch' },\n { code: 'no', nativeName: 'Norsk', englishName: 'Norwegian' },\n { code: 'pl', nativeName: 'Polski', englishName: 'Polish' },\n { code: 'pt', nativeName: 'Português', englishName: 'Portuguese' },\n { code: 'ro', nativeName: 'Română', englishName: 'Romanian' },\n { code: 'sv', nativeName: 'Svenska', englishName: 'Swedish' },\n { code: 'th', nativeName: 'ไทย', englishName: 'Thai' },\n { code: 'tr', nativeName: 'Türkçe', englishName: 'Turkish' },\n { code: 'uk', nativeName: 'Українська', englishName: 'Ukrainian' },\n { code: 'vi', nativeName: 'Tiếng Việt', englishName: 'Vietnamese' },\n { code: 'zh', nativeName: '中文', englishName: 'Chinese' },\n] as const;\n\n// Create lookup map for efficient access\nconst localeByCode = new Map<string, LocaleInfo>(\n LOCALES.map(locale => [locale.code.toLowerCase(), locale])\n);\n\n/**\n * Get locale information by code\n */\nexport function getLocaleInfo(code: string | undefined): LocaleInfo | undefined {\n if (!code) return undefined;\n return localeByCode.get(code.toLowerCase());\n}\n\n/**\n * Get the native name of a language by its locale code\n */\nexport function getLocaleNativeName(code: string | undefined): string | undefined {\n return getLocaleInfo(code)?.nativeName;\n}\n\n/**\n * Get the English name of a language by its locale code\n */\nexport function getLocaleEnglishName(code: string | undefined): string | undefined {\n return getLocaleInfo(code)?.englishName;\n}\n\n/**\n * Format locale code for display as \"Native Name (code)\"\n */\nexport function formatLocaleDisplay(code: string | undefined): string | undefined {\n if (!code) return undefined;\n\n const info = getLocaleInfo(code);\n if (!info) return code;\n\n return `${info.nativeName} (${code.toLowerCase()})`;\n}\n\n/**\n * Get all supported locale codes\n */\nexport function getAllLocaleCodes(): readonly string[] {\n return LOCALES.map(l => l.code);\n}\n","/**\n * Helper functions for working with W3C ResourceDescriptor\n */\n\nimport type { components } from '@semiont/core';\n\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\ntype Representation = components['schemas']['Representation'];\n\n/**\n * Get the resource ID from @id property\n *\n * For internal resources: extracts UUID from \"http://localhost:4000/resources/{uuid}\"\n * For external resources: returns undefined\n *\n * This is used for routing - the frontend URL should contain only the resource ID,\n * not the full HTTP URI.\n */\nexport function getResourceId(resource: ResourceDescriptor | undefined): string | undefined {\n if (!resource) return undefined;\n\n const fullId = resource['@id'];\n\n // For internal resources, extract the last path segment\n // http://localhost:4000/resources/{uuid} -> {uuid}\n if (fullId.includes('/resources/')) {\n const parts = fullId.split('/resources/');\n const lastPart = parts[parts.length - 1];\n return lastPart || undefined;\n }\n\n // For external resources, cannot extract ID\n return undefined;\n}\n\n/**\n * Get the primary representation (first or only representation)\n */\nexport function getPrimaryRepresentation(resource: ResourceDescriptor | undefined): Representation | undefined {\n if (!resource?.representations) return undefined;\n const reps = Array.isArray(resource.representations)\n ? resource.representations\n : [resource.representations];\n return reps[0];\n}\n\n/**\n * Get the media type from the primary representation\n */\nexport function getPrimaryMediaType(resource: ResourceDescriptor | undefined): string | undefined {\n return getPrimaryRepresentation(resource)?.mediaType;\n}\n\n/**\n * Get the checksum from the primary representation\n */\nexport function getChecksum(resource: ResourceDescriptor | undefined): string | undefined {\n return getPrimaryRepresentation(resource)?.checksum;\n}\n\n/**\n * Get the language from the primary representation\n */\nexport function getLanguage(resource: ResourceDescriptor | undefined): string | undefined {\n return getPrimaryRepresentation(resource)?.language;\n}\n\n/**\n * Get storage URI from primary representation\n *\n * @param resource - ResourceDescriptor\n * @returns Storage URI or undefined\n */\nexport function getStorageUri(resource: ResourceDescriptor | undefined): string | undefined {\n return getPrimaryRepresentation(resource)?.storageUri;\n}\n\n/**\n * Get creator agent from wasAttributedTo\n * Handles both single agent and array of agents\n *\n * @param resource - ResourceDescriptor\n * @returns First agent or undefined\n */\nexport function getCreator(resource: ResourceDescriptor | undefined): components['schemas']['Agent'] | undefined {\n if (!resource?.wasAttributedTo) return undefined;\n\n return Array.isArray(resource.wasAttributedTo)\n ? resource.wasAttributedTo[0]\n : resource.wasAttributedTo;\n}\n\n/**\n * Get derived-from URI\n * Handles both single URI and array of URIs\n *\n * @param resource - ResourceDescriptor\n * @returns First derivation URI or undefined\n */\nexport function getDerivedFrom(resource: ResourceDescriptor | undefined): string | undefined {\n if (!resource?.wasDerivedFrom) return undefined;\n\n return Array.isArray(resource.wasDerivedFrom)\n ? resource.wasDerivedFrom[0]\n : resource.wasDerivedFrom;\n}\n\n/**\n * Check if resource is archived (application-specific field)\n *\n * @param resource - ResourceDescriptor\n * @returns True if archived, false otherwise\n */\nexport function isArchived(resource: ResourceDescriptor | undefined): boolean {\n return resource?.archived === true;\n}\n\n/**\n * Get entity types from resource (application-specific field)\n *\n * @param resource - ResourceDescriptor\n * @returns Array of entity types, empty if not set\n */\nexport function getResourceEntityTypes(resource: ResourceDescriptor | undefined): string[] {\n return resource?.entityTypes || [];\n}\n\n/**\n * Check if resource is a draft (application-specific field)\n *\n * @param resource - ResourceDescriptor\n * @returns True if draft, false otherwise\n */\nexport function isDraft(resource: ResourceDescriptor | undefined): boolean {\n return resource?.isDraft === true;\n}\n\n/**\n * Map charset names to Node.js Buffer encoding names\n * Node.js Buffer.toString() supports: 'utf8', 'utf16le', 'latin1', 'base64', 'hex', 'ascii', 'binary', 'ucs2'\n *\n * @param charset - Charset name (e.g., \"UTF-8\", \"ISO-8859-1\", \"Windows-1252\")\n * @returns Node.js BufferEncoding\n */\nexport function getNodeEncoding(charset: string): BufferEncoding {\n const normalized = charset.toLowerCase().replace(/[-_]/g, '');\n\n // Map common charset names to Node.js encodings\n const charsetMap: Record<string, BufferEncoding> = {\n 'utf8': 'utf8',\n 'iso88591': 'latin1',\n 'latin1': 'latin1',\n 'ascii': 'ascii',\n 'usascii': 'ascii',\n 'utf16le': 'utf16le',\n 'ucs2': 'ucs2',\n 'binary': 'binary',\n 'windows1252': 'latin1', // Windows-1252 is a superset of Latin-1\n 'cp1252': 'latin1',\n };\n\n return charsetMap[normalized] || 'utf8';\n}\n\n/**\n * Decode a representation buffer to string using the correct charset\n * Extracts charset from media type and uses appropriate encoding\n *\n * @param buffer - The raw representation data\n * @param mediaType - Media type with optional charset (e.g., \"text/plain; charset=iso-8859-1\")\n * @returns Decoded string\n *\n * @example\n * ```typescript\n * const content = decodeRepresentation(buffer, \"text/plain; charset=utf-8\");\n * const legacy = decodeRepresentation(buffer, \"text/plain; charset=windows-1252\");\n * ```\n */\nexport function decodeRepresentation(buffer: Buffer, mediaType: string): string {\n // Extract charset from mediaType (e.g., \"text/plain; charset=iso-8859-1\")\n const charsetMatch = mediaType.match(/charset=([^\\s;]+)/i);\n const charset = (charsetMatch?.[1] || 'utf-8').toLowerCase();\n\n // Map to Node.js encoding\n const encoding = getNodeEncoding(charset);\n\n return buffer.toString(encoding);\n}\n","/**\n * SVG Utility Functions\n *\n * Utilities for creating, parsing, and manipulating W3C-compliant SVG selectors\n * for image annotation.\n */\n\nexport interface Point {\n x: number;\n y: number;\n}\n\nexport interface BoundingBox {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/**\n * Create W3C-compliant SVG rectangle selector\n */\nexport function createRectangleSvg(start: Point, end: Point): string {\n const x = Math.min(start.x, end.x);\n const y = Math.min(start.y, end.y);\n const width = Math.abs(end.x - start.x);\n const height = Math.abs(end.y - start.y);\n\n return `<svg xmlns=\"http://www.w3.org/2000/svg\"><rect x=\"${x}\" y=\"${y}\" width=\"${width}\" height=\"${height}\"/></svg>`;\n}\n\n/**\n * Create W3C-compliant SVG polygon selector\n */\nexport function createPolygonSvg(points: Point[]): string {\n if (points.length < 3) {\n throw new Error('Polygon requires at least 3 points');\n }\n\n const pointsStr = points.map(p => `${p.x},${p.y}`).join(' ');\n return `<svg xmlns=\"http://www.w3.org/2000/svg\"><polygon points=\"${pointsStr}\"/></svg>`;\n}\n\n/**\n * Create W3C-compliant SVG circle selector\n */\nexport function createCircleSvg(center: Point, radius: number): string {\n if (radius <= 0) {\n throw new Error('Circle radius must be positive');\n }\n\n return `<svg xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"${center.x}\" cy=\"${center.y}\" r=\"${radius}\"/></svg>`;\n}\n\n/**\n * Parse SVG selector to extract shape type and data\n */\nexport function parseSvgSelector(svg: string): {\n type: 'rect' | 'polygon' | 'circle' | 'path';\n data: any;\n} | null {\n // Extract rectangle\n const rectMatch = svg.match(/<rect\\s+([^>]+)\\/>/);\n if (rectMatch && rectMatch[1]) {\n const attrs = rectMatch[1];\n const x = parseFloat(attrs.match(/x=\"([^\"]+)\"/)?.[1] || '0');\n const y = parseFloat(attrs.match(/y=\"([^\"]+)\"/)?.[1] || '0');\n const width = parseFloat(attrs.match(/width=\"([^\"]+)\"/)?.[1] || '0');\n const height = parseFloat(attrs.match(/height=\"([^\"]+)\"/)?.[1] || '0');\n\n return {\n type: 'rect',\n data: { x, y, width, height }\n };\n }\n\n // Extract polygon\n const polygonMatch = svg.match(/<polygon\\s+points=\"([^\"]+)\"/);\n if (polygonMatch && polygonMatch[1]) {\n const pointsStr = polygonMatch[1];\n const points = pointsStr.split(/\\s+/).map(pair => {\n const [x, y] = pair.split(',').map(parseFloat);\n return { x, y };\n });\n\n return {\n type: 'polygon',\n data: { points }\n };\n }\n\n // Extract circle\n const circleMatch = svg.match(/<circle\\s+([^>]+)\\/>/);\n if (circleMatch && circleMatch[1]) {\n const attrs = circleMatch[1];\n const cx = parseFloat(attrs.match(/cx=\"([^\"]+)\"/)?.[1] || '0');\n const cy = parseFloat(attrs.match(/cy=\"([^\"]+)\"/)?.[1] || '0');\n const r = parseFloat(attrs.match(/r=\"([^\"]+)\"/)?.[1] || '0');\n\n return {\n type: 'circle',\n data: { cx, cy, r }\n };\n }\n\n return null;\n}\n\n/**\n * Normalize coordinates from display space to image native resolution\n */\nexport function normalizeCoordinates(\n point: Point,\n displayWidth: number,\n displayHeight: number,\n imageWidth: number,\n imageHeight: number\n): Point {\n return {\n x: (point.x / displayWidth) * imageWidth,\n y: (point.y / displayHeight) * imageHeight\n };\n}\n\n/**\n * Scale entire SVG selector from display space to image native resolution\n */\nexport function scaleSvgToNative(\n svg: string,\n displayWidth: number,\n displayHeight: number,\n imageWidth: number,\n imageHeight: number\n): string {\n const parsed = parseSvgSelector(svg);\n if (!parsed) return svg;\n\n const scaleX = imageWidth / displayWidth;\n const scaleY = imageHeight / displayHeight;\n\n switch (parsed.type) {\n case 'rect': {\n const { x, y, width, height } = parsed.data;\n return createRectangleSvg(\n { x: x * scaleX, y: y * scaleY },\n { x: (x + width) * scaleX, y: (y + height) * scaleY }\n );\n }\n\n case 'circle': {\n const { cx, cy, r } = parsed.data;\n return createCircleSvg(\n { x: cx * scaleX, y: cy * scaleY },\n r * Math.min(scaleX, scaleY)\n );\n }\n\n case 'polygon': {\n const points = parsed.data.points.map((p: Point) => ({\n x: p.x * scaleX,\n y: p.y * scaleY\n }));\n return createPolygonSvg(points);\n }\n }\n\n return svg;\n}\n","/**\n * Text context extraction utilities for W3C Web Annotation TextQuoteSelector\n *\n * Provides robust prefix/suffix context extraction with word boundary detection\n * to ensure fuzzy anchoring works correctly when the same text appears multiple times.\n *\n * Also provides AI offset validation and correction for handling AI-generated annotations\n * where the model may return slightly incorrect character offsets.\n *\n * @see https://www.w3.org/TR/annotation-model/#text-quote-selector\n */\n\nimport { findBestTextMatch, type MatchQuality } from './fuzzy-anchor';\n\n/**\n * Extract prefix and suffix context for TextQuoteSelector\n *\n * Extracts up to 64 characters before and after the selected text,\n * extending to word boundaries to avoid cutting words in half.\n * This ensures prefix/suffix are meaningful context for fuzzy anchoring.\n *\n * @param content - Full text content\n * @param start - Start offset of selection\n * @param end - End offset of selection\n * @returns Object with prefix and suffix (undefined if at boundaries)\n *\n * @example\n * ```typescript\n * const content = \"The United States Congress...\";\n * const context = extractContext(content, 4, 17); // \"United States\"\n * // Returns: { prefix: \"The \", suffix: \" Congress...\" }\n * // NOT: { prefix: \"nited \", suffix: \"gress...\" }\n * ```\n */\nexport function extractContext(\n content: string,\n start: number,\n end: number\n): { prefix?: string; suffix?: string } {\n const CONTEXT_LENGTH = 64;\n const MAX_EXTENSION = 32; // Maximum additional chars to extend for word boundary\n\n // Extract prefix (up to CONTEXT_LENGTH chars before start, extended to word boundary)\n let prefix: string | undefined;\n if (start > 0) {\n let prefixStart = Math.max(0, start - CONTEXT_LENGTH);\n\n // Extend backward to word boundary (whitespace or punctuation)\n // Stop if we hit start of content or exceed MAX_EXTENSION\n let extensionCount = 0;\n while (prefixStart > 0 && extensionCount < MAX_EXTENSION) {\n const char = content[prefixStart - 1];\n // Break on whitespace, punctuation, or common delimiters\n if (!char || /[\\s.,;:!?'\"()\\[\\]{}<>\\/\\\\]/.test(char)) {\n break;\n }\n prefixStart--;\n extensionCount++;\n }\n\n prefix = content.substring(prefixStart, start);\n }\n\n // Extract suffix (up to CONTEXT_LENGTH chars after end, extended to word boundary)\n let suffix: string | undefined;\n if (end < content.length) {\n let suffixEnd = Math.min(content.length, end + CONTEXT_LENGTH);\n\n // Extend forward to word boundary (whitespace or punctuation)\n // Stop if we hit end of content or exceed MAX_EXTENSION\n let extensionCount = 0;\n while (suffixEnd < content.length && extensionCount < MAX_EXTENSION) {\n const char = content[suffixEnd];\n // Break on whitespace, punctuation, or common delimiters\n if (!char || /[\\s.,;:!?'\"()\\[\\]{}<>\\/\\\\]/.test(char)) {\n break;\n }\n suffixEnd++;\n extensionCount++;\n }\n\n suffix = content.substring(end, suffixEnd);\n }\n\n return { prefix, suffix };\n}\n\n/**\n * Result of validating and correcting AI-provided annotation offsets\n */\nexport interface ValidatedAnnotation {\n start: number;\n end: number;\n exact: string;\n prefix?: string;\n suffix?: string;\n corrected: boolean; // True if offsets were adjusted from AI's original values\n fuzzyMatched?: boolean; // True if we had to use fuzzy matching (minor text differences)\n matchQuality?: MatchQuality; // How we found the match\n}\n\n\n/**\n * Validate and correct AI-provided annotation offsets with fuzzy matching tolerance\n *\n * AI models sometimes return offsets that don't match the actual text position,\n * or provide text with minor variations (case differences, whitespace, typos).\n *\n * This function uses a multi-strategy approach:\n * 1. Check if AI's offsets are exactly correct\n * 2. Try exact case-sensitive search\n * 3. Try case-insensitive search\n * 4. Try fuzzy matching with Levenshtein distance (5% tolerance)\n *\n * This ensures we're maximally tolerant of AI errors while still maintaining\n * annotation quality and logging what corrections were made.\n *\n * @param content - Full text content\n * @param aiStart - Start offset from AI\n * @param aiEnd - End offset from AI\n * @param exact - The exact text that should be at this position (from AI)\n * @returns Validated annotation with corrected offsets and context\n * @throws Error if no acceptable match can be found\n *\n * @example\n * ```typescript\n * // AI said start=1143, but actual text is at 1161\n * const result = validateAndCorrectOffsets(\n * content,\n * 1143,\n * 1289,\n * \"the question \\\"whether...\"\n * );\n * // Returns: { start: 1161, end: 1303, exact: \"...\", corrected: true, matchQuality: 'exact', ... }\n * ```\n */\nexport function validateAndCorrectOffsets(\n content: string,\n aiStart: number,\n aiEnd: number,\n exact: string\n): ValidatedAnnotation {\n const exactPreview = exact.length > 50 ? exact.substring(0, 50) + '...' : exact;\n\n // First, check if AI's offsets are correct\n const textAtOffset = content.substring(aiStart, aiEnd);\n\n if (textAtOffset === exact) {\n // AI got it right! Just add proper context\n const context = extractContext(content, aiStart, aiEnd);\n return {\n start: aiStart,\n end: aiEnd,\n exact,\n prefix: context.prefix,\n suffix: context.suffix,\n corrected: false,\n matchQuality: 'exact'\n };\n }\n\n // AI's offsets are wrong - try to find the text using multiple strategies\n const foundPreview = textAtOffset.length > 50 ? textAtOffset.substring(0, 50) + '...' : textAtOffset;\n\n console.warn(\n '[validateAndCorrectOffsets] ⚠ AI offset mismatch:\\n' +\n ` Expected text: \"${exactPreview}\"\\n` +\n ` Found at AI offset (${aiStart}-${aiEnd}): \"${foundPreview}\"\\n` +\n ` Attempting multi-strategy search...`\n );\n\n const match = findBestTextMatch(content, exact, aiStart);\n\n if (!match) {\n const exactLong = exact.length > 100 ? exact.substring(0, 100) + '...' : exact;\n console.error(\n '[validateAndCorrectOffsets] ✗ No acceptable match found:\\n' +\n ` AI offsets: start=${aiStart}, end=${aiEnd}\\n` +\n ` AI text: \"${exactLong}\"\\n` +\n ` Text at AI offset: \"${foundPreview}\"\\n` +\n ' All search strategies (exact, case-insensitive, fuzzy) failed.\\n' +\n ' This suggests the AI hallucinated text that doesn\\'t exist in the document.'\n );\n throw new Error(\n 'Cannot find acceptable match for text in content. ' +\n 'All search strategies failed. Text may be hallucinated.'\n );\n }\n\n // Found a match! Extract the actual text from content\n const actualText = content.substring(match.start, match.end);\n const actualPreview = actualText.length > 50 ? actualText.substring(0, 50) + '...' : actualText;\n\n const offsetDelta = match.start - aiStart;\n const matchSymbol = match.matchQuality === 'exact' ? '✓' : match.matchQuality === 'case-insensitive' ? '≈' : '~';\n\n console.warn(\n `[validateAndCorrectOffsets] ${matchSymbol} Found ${match.matchQuality} match:\\n` +\n ` AI offsets: start=${aiStart}, end=${aiEnd}\\n` +\n ` Corrected: start=${match.start}, end=${match.end}\\n` +\n ` Offset delta: ${offsetDelta} characters\\n` +\n ` Actual text: \"${actualPreview}\"`\n );\n\n // If fuzzy match, log the difference for debugging\n if (match.matchQuality === 'fuzzy') {\n console.warn(\n '[validateAndCorrectOffsets] Fuzzy match details:\\n' +\n ` AI provided: \"${exactPreview}\"\\n` +\n ` Found in doc: \"${actualPreview}\"\\n` +\n ' Minor text differences detected - using document version'\n );\n }\n\n // Extract context using corrected offsets\n const context = extractContext(content, match.start, match.end);\n\n return {\n start: match.start,\n end: match.end,\n exact: actualText, // Use actual text from document, not AI's version\n prefix: context.prefix,\n suffix: context.suffix,\n corrected: true,\n fuzzyMatched: match.matchQuality !== 'exact',\n matchQuality: match.matchQuality\n };\n}\n","/**\n * Text encoding utilities for consistent charset handling\n *\n * Ensures frontend decoding matches backend decoding by respecting\n * charset parameters in mediaType (e.g., \"text/plain; charset=iso-8859-1\")\n */\n\n/**\n * Extract charset from mediaType parameter\n *\n * @param mediaType - Media type with optional charset (e.g., \"text/plain; charset=utf-8\")\n * @returns Charset name in lowercase (defaults to \"utf-8\")\n *\n * @example\n * extractCharset(\"text/plain; charset=iso-8859-1\") // \"iso-8859-1\"\n * extractCharset(\"text/plain\") // \"utf-8\"\n */\nexport function extractCharset(mediaType: string): string {\n const charsetMatch = mediaType.match(/charset=([^\\s;]+)/i);\n return (charsetMatch?.[1] || 'utf-8').toLowerCase();\n}\n\n/**\n * Decode ArrayBuffer to string using charset from mediaType\n *\n * Uses TextDecoder with the charset extracted from mediaType parameter.\n * This ensures the same character space is used for both annotation creation\n * (backend) and rendering (frontend).\n *\n * @param buffer - Binary data to decode\n * @param mediaType - Media type with optional charset parameter\n * @returns Decoded string in the original character space\n *\n * @example\n * const buffer = new Uint8Array([...]);\n * const text = decodeWithCharset(buffer, \"text/plain; charset=iso-8859-1\");\n */\nexport function decodeWithCharset(buffer: ArrayBuffer, mediaType: string): string {\n const charset = extractCharset(mediaType);\n\n // TextDecoder supports standard charset names\n // Common mappings that work in browsers:\n // - utf-8, utf-16, utf-16le, utf-16be\n // - iso-8859-1 through iso-8859-15\n // - windows-1252, windows-1251, etc.\n const decoder = new TextDecoder(charset);\n return decoder.decode(buffer);\n}\n","/**\n * Generic validation utilities for @semiont/api-client\n *\n * Pure TypeScript validation with no external dependencies.\n * Safe to use in any JavaScript environment (Node.js, browser, Deno, etc.)\n */\n\n/**\n * Validation result types\n */\nexport type ValidationSuccess<T> = { success: true; data: T };\nexport type ValidationFailure = { success: false; error: string; details?: string[] };\nexport type ValidationResult<T> = ValidationSuccess<T> | ValidationFailure;\n\n/**\n * JWT Token validation\n *\n * Validates JWT token format (header.payload.signature).\n * Does not verify signature - use for format validation only.\n */\nexport const JWTTokenSchema = {\n parse(token: unknown): string {\n if (typeof token !== 'string') {\n throw new Error('Token must be a string');\n }\n if (!token || token.length === 0) {\n throw new Error('Token is required');\n }\n // JWT format: header.payload.signature\n const jwtRegex = /^[A-Za-z0-9\\-_]+\\.[A-Za-z0-9\\-_]+\\.[A-Za-z0-9\\-_]*$/;\n if (!jwtRegex.test(token)) {\n throw new Error('Invalid JWT token format');\n }\n return token;\n },\n\n safeParse(token: unknown): ValidationResult<string> {\n try {\n const validated = this.parse(token);\n return { success: true, data: validated };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Invalid JWT token',\n };\n }\n },\n};\n\n/**\n * Generic validation helper with error formatting\n *\n * Wraps any schema's parse method with try/catch and returns ValidationResult.\n *\n * @example\n * ```typescript\n * const result = validateData(JWTTokenSchema, 'eyJ...');\n * if (result.success) {\n * console.log('Valid token:', result.data);\n * } else {\n * console.error('Invalid:', result.error);\n * }\n * ```\n */\nexport function validateData<T>(\n schema: { parse(data: unknown): T },\n data: unknown\n): ValidationResult<T> {\n try {\n const validated = schema.parse(data);\n return { success: true, data: validated };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Validation failed',\n };\n }\n}\n\n/**\n * Email validation helper\n *\n * Validates email format using RFC 5322 simplified regex.\n *\n * @param email - Email address to validate\n * @returns true if valid email format\n */\nexport function isValidEmail(email: string): boolean {\n if (email.length < 1 || email.length > 255) {\n return false;\n }\n // RFC 5322 simplified email regex\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return emailRegex.test(email);\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/annotations.ts","../../src/utils/fuzzy-anchor.ts","../../src/utils/locales.ts","../../src/utils/resources.ts","../../src/utils/svg-utils.ts","../../src/utils/text-context.ts","../../src/utils/text-encoding.ts","../../src/utils/validation.ts"],"names":["pos","context"],"mappings":";;;AA+BO,SAAS,cAAc,IAAA,EAA8C;AAC1E,EAAA,IAAI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;AAC1C,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,MAAM,UAAA,GAAa,4BAAA;AACnB,EAAA,OAAO,UAAA,CAAW,KAAK,KAAK,CAAA;AAC9B","file":"index.js","sourcesContent":["/**\n * Annotation and Selector Utilities\n *\n * Pure TypeScript utilities for working with W3C Web Annotations.\n * No React dependencies - safe to use in any JavaScript environment.\n *\n * Body is either empty array (stub) or single SpecificResource (resolved)\n * Body can be array of TextualBody (tagging) + SpecificResource (linking)\n * Target can be simple string IRI or object with source and optional selector\n */\n\nimport type { components } from '@semiont/core';\nimport type { ResourceUri } from '@semiont/core';\nimport { resourceUri } from '@semiont/core';\n\ntype Annotation = components['schemas']['Annotation'];\ntype HighlightAnnotation = Annotation;\ntype ReferenceAnnotation = Annotation;\ntype TextPositionSelector = components['schemas']['TextPositionSelector'];\ntype TextQuoteSelector = components['schemas']['TextQuoteSelector'];\ntype SvgSelector = components['schemas']['SvgSelector'];\ntype FragmentSelector = components['schemas']['FragmentSelector'];\ntype Selector = TextPositionSelector | TextQuoteSelector | SvgSelector | FragmentSelector;\n\n// Re-export selector types for convenience\nexport type { TextPositionSelector, TextQuoteSelector, SvgSelector, FragmentSelector, Selector };\n\n/**\n * Get the source from an annotation body (null if stub)\n * Search for SpecificResource in body array\n */\nexport function getBodySource(body: Annotation['body']): ResourceUri | null {\n if (Array.isArray(body)) {\n // Search for SpecificResource with source\n for (const item of body) {\n if (\n typeof item === 'object' &&\n item !== null &&\n 'type' in item &&\n 'source' in item\n ) {\n const itemType = (item as { type: unknown }).type;\n const itemSource = (item as { source: unknown }).source;\n\n if (itemType === 'SpecificResource' && typeof itemSource === 'string') {\n return resourceUri(itemSource);\n }\n }\n }\n return null; // No SpecificResource found = stub\n }\n\n // Single body object (SpecificResource)\n if (\n typeof body === 'object' &&\n body !== null &&\n 'type' in body &&\n 'source' in body\n ) {\n const bodyType = (body as { type: unknown }).type;\n const bodySource = (body as { source: unknown }).source;\n\n if (bodyType === 'SpecificResource' && typeof bodySource === 'string') {\n return resourceUri(bodySource);\n }\n }\n\n return null;\n}\n\n/**\n * Get the type from an annotation body (returns first body type in array)\n */\nexport function getBodyType(body: Annotation['body']): 'TextualBody' | 'SpecificResource' | null {\n if (Array.isArray(body)) {\n if (body.length === 0) {\n return null;\n }\n // Return type of first body item\n if (typeof body[0] === 'object' && body[0] !== null && 'type' in body[0]) {\n const firstType = (body[0] as { type: unknown }).type;\n if (firstType === 'TextualBody' || firstType === 'SpecificResource') {\n return firstType;\n }\n }\n return null;\n }\n\n // Single body object\n if (typeof body === 'object' && body !== null && 'type' in body) {\n const bodyType = (body as { type: unknown }).type;\n if (bodyType === 'TextualBody' || bodyType === 'SpecificResource') {\n return bodyType;\n }\n }\n\n return null;\n}\n\n/**\n * Check if body is resolved (has a source)\n * Check for SpecificResource in body array\n */\nexport function isBodyResolved(body: Annotation['body']): boolean {\n return getBodySource(body) !== null;\n}\n\n/**\n * Get the source IRI from target (handles both string and object forms)\n */\nexport function getTargetSource(target: Annotation['target']): ResourceUri {\n if (typeof target === 'string') {\n return resourceUri(target);\n }\n return resourceUri(target.source);\n}\n\n/**\n * Get the selector from target (undefined if string or no selector)\n */\nexport function getTargetSelector(target: Annotation['target']) {\n if (typeof target === 'string') {\n return undefined;\n }\n return target.selector;\n}\n\n/**\n * Check if target has a selector\n */\nexport function hasTargetSelector(target: Annotation['target']): boolean {\n return typeof target !== 'string' && target.selector !== undefined;\n}\n\n/**\n * Type guard to check if an annotation is a highlight\n */\nexport function isHighlight(annotation: Annotation): annotation is HighlightAnnotation {\n return annotation.motivation === 'highlighting';\n}\n\n/**\n * Type guard to check if an annotation is a reference (linking)\n */\nexport function isReference(annotation: Annotation): annotation is ReferenceAnnotation {\n return annotation.motivation === 'linking';\n}\n\n/**\n * Type guard to check if an annotation is an assessment\n */\nexport function isAssessment(annotation: Annotation): annotation is Annotation {\n return annotation.motivation === 'assessing';\n}\n\n/**\n * Type guard to check if an annotation is a comment\n */\nexport function isComment(annotation: Annotation): annotation is Annotation {\n return annotation.motivation === 'commenting';\n}\n\n/**\n * Type guard to check if an annotation is a tag\n */\nexport function isTag(annotation: Annotation): annotation is Annotation {\n return annotation.motivation === 'tagging';\n}\n\n/**\n * Extract comment text from a comment annotation's body\n * @param annotation - The annotation to extract comment text from\n * @returns The comment text, or undefined if not a comment or no text found\n */\nexport function getCommentText(annotation: Annotation): string | undefined {\n if (!isComment(annotation)) return undefined;\n const body = Array.isArray(annotation.body) ? annotation.body[0] : annotation.body;\n if (body && 'value' in body) {\n return body.value;\n }\n return undefined;\n}\n\n/**\n * Type guard to check if a reference annotation is a stub (unresolved)\n * Stub if no SpecificResource in body array\n */\nexport function isStubReference(annotation: Annotation): boolean {\n return isReference(annotation) && !isBodyResolved(annotation.body);\n}\n\n/**\n * Type guard to check if a reference annotation is resolved\n * Resolved if SpecificResource exists in body array\n */\nexport function isResolvedReference(annotation: Annotation): annotation is ReferenceAnnotation {\n return isReference(annotation) && isBodyResolved(annotation.body);\n}\n\n// =============================================================================\n// SELECTOR UTILITIES\n// =============================================================================\n\n/**\n * Get the exact text from a selector (single or array)\n *\n * When selector is an array, tries to find a TextQuoteSelector (which has exact text).\n * TextPositionSelector does not have exact text, only character offsets.\n * Handles undefined selector (when target is a string IRI with no selector)\n */\nexport function getExactText(selector: Selector | Selector[] | undefined): string {\n if (!selector) {\n return ''; // No selector means entire resource\n }\n const selectors = Array.isArray(selector) ? selector : [selector];\n\n // Try to find TextQuoteSelector (has exact text)\n const quoteSelector = selectors.find(s => s.type === 'TextQuoteSelector') as TextQuoteSelector | undefined;\n if (quoteSelector) {\n return quoteSelector.exact;\n }\n\n // No TextQuoteSelector found\n return '';\n}\n\n/**\n * Get the exact text from an annotation's target selector\n * Uses getTargetSelector helper to safely get selector\n */\nexport function getAnnotationExactText(annotation: Annotation): string {\n const selector = getTargetSelector(annotation.target);\n return getExactText(selector as Selector | Selector[] | undefined);\n}\n\n/**\n * Get the primary selector from a selector (single or array)\n *\n * When selector is an array, returns the first selector.\n * When selector is a single object, returns it as-is.\n */\nexport function getPrimarySelector(selector: Selector | Selector[]): Selector {\n if (Array.isArray(selector)) {\n if (selector.length === 0) {\n throw new Error('Empty selector array');\n }\n const first = selector[0];\n if (!first) {\n throw new Error('Invalid selector array');\n }\n return first;\n }\n return selector;\n}\n\n/**\n * Get TextPositionSelector from a selector (single or array)\n *\n * Returns the first TextPositionSelector found, or null if none exists.\n * Handles undefined selector (when target is a string IRI with no selector)\n */\nexport function getTextPositionSelector(selector: Selector | Selector[] | undefined): TextPositionSelector | null {\n if (!selector) return null; // No selector means entire resource\n const selectors = Array.isArray(selector) ? selector : [selector];\n const found = selectors.find(s => s.type === 'TextPositionSelector');\n if (!found) return null;\n return found.type === 'TextPositionSelector' ? found : null;\n}\n\n/**\n * Get TextQuoteSelector from a selector (single or array)\n *\n * Returns the first TextQuoteSelector found, or null if none exists.\n */\nexport function getTextQuoteSelector(selector: Selector | Selector[]): TextQuoteSelector | null {\n const selectors = Array.isArray(selector) ? selector : [selector];\n const found = selectors.find(s => s.type === 'TextQuoteSelector');\n if (!found) return null;\n return found.type === 'TextQuoteSelector' ? found : null;\n}\n\n/**\n * Get SvgSelector from a selector (single or array)\n *\n * Returns the first SvgSelector found, or null if none exists.\n */\nexport function getSvgSelector(selector: Selector | Selector[] | undefined): SvgSelector | null {\n if (!selector) return null;\n const selectors = Array.isArray(selector) ? selector : [selector];\n const found = selectors.find(s => s.type === 'SvgSelector');\n if (!found) return null;\n return found.type === 'SvgSelector' ? found : null;\n}\n\n/**\n * Get FragmentSelector from a selector (single or array)\n *\n * Returns the first FragmentSelector found, or null if none exists.\n */\nexport function getFragmentSelector(selector: Selector | Selector[] | undefined): FragmentSelector | null {\n if (!selector) return null;\n const selectors = Array.isArray(selector) ? selector : [selector];\n const found = selectors.find(s => s.type === 'FragmentSelector');\n if (!found) return null;\n return found.type === 'FragmentSelector' ? found : null;\n}\n\n/**\n * Validate SVG markup for W3C compliance\n *\n * Checks that:\n * - SVG contains xmlns attribute\n * - SVG is well-formed XML\n * - SVG contains at least one shape element\n *\n * @returns null if valid, error message if invalid\n */\nexport function validateSvgMarkup(svg: string): string | null {\n // Check for xmlns attribute (required by W3C spec)\n if (!svg.includes('xmlns=\"http://www.w3.org/2000/svg\"')) {\n return 'SVG must include xmlns=\"http://www.w3.org/2000/svg\" attribute';\n }\n\n // Check for basic SVG tag structure\n if (!svg.includes('<svg') || !svg.includes('</svg>')) {\n return 'SVG must have opening and closing tags';\n }\n\n // Check for at least one shape element\n const shapeElements = ['rect', 'circle', 'ellipse', 'polygon', 'polyline', 'path', 'line'];\n const hasShape = shapeElements.some(shape =>\n svg.includes(`<${shape}`) || svg.includes(`<${shape} `)\n );\n\n if (!hasShape) {\n return 'SVG must contain at least one shape element (rect, circle, ellipse, polygon, polyline, path, or line)';\n }\n\n return null; // Valid\n}\n\n/**\n * Extract bounding box from SVG markup\n *\n * Attempts to extract x, y, width, height from the SVG viewBox or root element.\n * Returns null if bounding box cannot be determined.\n */\nexport function extractBoundingBox(svg: string): { x: number; y: number; width: number; height: number } | null {\n // Try to extract viewBox attribute from SVG element\n const viewBoxMatch = svg.match(/<svg[^>]*viewBox=\"([^\"]+)\"/);\n if (viewBoxMatch) {\n const values = viewBoxMatch[1].split(/\\s+/).map(parseFloat);\n if (values.length === 4 && values.every(v => !isNaN(v))) {\n return {\n x: values[0],\n y: values[1],\n width: values[2],\n height: values[3]\n };\n }\n }\n\n // Try to extract width/height attributes from SVG element (assume x=0, y=0)\n const svgTagMatch = svg.match(/<svg[^>]*>/);\n if (svgTagMatch) {\n const svgTag = svgTagMatch[0];\n const widthMatch = svgTag.match(/width=\"([^\"]+)\"/);\n const heightMatch = svgTag.match(/height=\"([^\"]+)\"/);\n\n if (widthMatch && heightMatch) {\n const width = parseFloat(widthMatch[1]);\n const height = parseFloat(heightMatch[1]);\n\n if (!isNaN(width) && !isNaN(height)) {\n return { x: 0, y: 0, width, height };\n }\n }\n }\n\n return null;\n}\n","/**\n * Fuzzy Anchoring for W3C Web Annotation TextQuoteSelector\n *\n * Uses prefix/suffix context to disambiguate when the same text appears multiple times.\n * Implements fuzzy matching as specified in the W3C Web Annotation Data Model.\n *\n * @see https://www.w3.org/TR/annotation-model/#text-quote-selector\n */\n\nexport interface TextPosition {\n start: number;\n end: number;\n}\n\nexport type MatchQuality = 'exact' | 'normalized' | 'case-insensitive' | 'fuzzy';\n\n/**\n * Normalize text for comparison - handles common document editing changes\n *\n * Collapses whitespace, converts curly quotes to straight quotes,\n * and normalizes common punctuation variations.\n */\nexport function normalizeText(text: string): string {\n return text\n .replace(/\\s+/g, ' ') // collapse whitespace\n .replace(/[\\u2018\\u2019]/g, \"'\") // curly single quotes → straight\n .replace(/[\\u201C\\u201D]/g, '\"') // curly double quotes → straight\n .replace(/\\u2014/g, '--') // em-dash → double hyphen\n .replace(/\\u2013/g, '-') // en-dash → hyphen\n .trim();\n}\n\n/**\n * Calculate Levenshtein distance between two strings\n * Used for fuzzy matching when exact text doesn't match\n */\nfunction levenshteinDistance(str1: string, str2: string): number {\n const len1 = str1.length;\n const len2 = str2.length;\n const matrix: number[][] = [];\n\n // Initialize matrix\n for (let i = 0; i <= len1; i++) {\n matrix[i] = [i];\n }\n for (let j = 0; j <= len2; j++) {\n matrix[0]![j] = j;\n }\n\n // Fill matrix\n for (let i = 1; i <= len1; i++) {\n for (let j = 1; j <= len2; j++) {\n const cost = str1[i - 1] === str2[j - 1] ? 0 : 1;\n const deletion = matrix[i - 1]![j]! + 1;\n const insertion = matrix[i]![j - 1]! + 1;\n const substitution = matrix[i - 1]![j - 1]! + cost;\n matrix[i]![j] = Math.min(deletion, insertion, substitution);\n }\n }\n\n return matrix[len1]![len2]!;\n}\n\n/**\n * Find best match for text in content using multi-strategy search\n *\n * Shared core logic used by both findTextWithContext and validateAndCorrectOffsets.\n *\n * @param content - Full text content to search within\n * @param searchText - The text to find\n * @param positionHint - Optional hint for where to search (TextPositionSelector.start)\n * @returns Match with position and quality, or null if not found\n */\nexport function findBestTextMatch(\n content: string,\n searchText: string,\n positionHint?: number\n): { start: number; end: number; matchQuality: MatchQuality } | null {\n const maxFuzzyDistance = Math.max(5, Math.floor(searchText.length * 0.05)); // 5% tolerance or min 5 chars\n\n // Strategy 1: Exact match (case-sensitive, exact whitespace)\n const exactIndex = content.indexOf(searchText);\n if (exactIndex !== -1) {\n return {\n start: exactIndex,\n end: exactIndex + searchText.length,\n matchQuality: 'exact'\n };\n }\n\n // Strategy 2: Normalized match (handles whitespace/quote variations)\n const normalizedSearch = normalizeText(searchText);\n const normalizedContent = normalizeText(content);\n const normalizedIndex = normalizedContent.indexOf(normalizedSearch);\n if (normalizedIndex !== -1) {\n // Find actual position in original content by counting characters\n let actualPos = 0;\n let normalizedPos = 0;\n while (normalizedPos < normalizedIndex && actualPos < content.length) {\n const char = content[actualPos]!;\n const normalizedChar = normalizeText(char);\n if (normalizedChar) {\n normalizedPos += normalizedChar.length;\n }\n actualPos++;\n }\n return {\n start: actualPos,\n end: actualPos + searchText.length,\n matchQuality: 'normalized'\n };\n }\n\n // Strategy 3: Case-insensitive match\n const lowerContent = content.toLowerCase();\n const lowerSearch = searchText.toLowerCase();\n const caseInsensitiveIndex = lowerContent.indexOf(lowerSearch);\n if (caseInsensitiveIndex !== -1) {\n return {\n start: caseInsensitiveIndex,\n end: caseInsensitiveIndex + searchText.length,\n matchQuality: 'case-insensitive'\n };\n }\n\n // Strategy 4: Fuzzy match using Levenshtein distance with sliding window\n // Search near position hint if provided, otherwise search full content\n const windowSize = searchText.length;\n const searchRadius = Math.min(500, content.length);\n const searchStart = positionHint !== undefined\n ? Math.max(0, positionHint - searchRadius)\n : 0;\n const searchEnd = positionHint !== undefined\n ? Math.min(content.length, positionHint + searchRadius)\n : content.length;\n\n let bestMatch: { start: number; distance: number } | null = null;\n\n // Scan through content with sliding window\n for (let i = searchStart; i <= searchEnd - windowSize; i++) {\n const candidate = content.substring(i, i + windowSize);\n const distance = levenshteinDistance(searchText, candidate);\n\n if (distance <= maxFuzzyDistance) {\n if (!bestMatch || distance < bestMatch.distance) {\n bestMatch = { start: i, distance };\n }\n }\n }\n\n if (bestMatch) {\n return {\n start: bestMatch.start,\n end: bestMatch.start + windowSize,\n matchQuality: 'fuzzy'\n };\n }\n\n return null;\n}\n\n/**\n * Find text using exact match with optional prefix/suffix context\n *\n * When the exact text appears multiple times in the content, prefix and suffix\n * are used to disambiguate and find the correct occurrence.\n *\n * If exact text is not found, uses multi-strategy fuzzy matching (normalization,\n * case-insensitive, Levenshtein distance) to locate changed text.\n *\n * @param content - Full text content to search within\n * @param exact - The exact text to find\n * @param prefix - Optional text that should appear immediately before the match\n * @param suffix - Optional text that should appear immediately after the match\n * @param positionHint - Optional position hint (from TextPositionSelector) for fuzzy search\n * @returns Position of the matched text, or null if not found\n *\n * @example\n * ```typescript\n * const content = \"The cat sat. The cat ran.\";\n * // Find second \"The cat\" occurrence\n * const pos = findTextWithContext(content, \"The cat\", \"sat. \", \" ran\");\n * // Returns { start: 13, end: 20 }\n * ```\n */\nexport function findTextWithContext(\n content: string,\n exact: string,\n prefix?: string,\n suffix?: string,\n positionHint?: number\n): TextPosition | null {\n if (!exact) return null;\n\n // Find all occurrences of exact text\n const occurrences: number[] = [];\n let index = content.indexOf(exact);\n while (index !== -1) {\n occurrences.push(index);\n index = content.indexOf(exact, index + 1);\n }\n\n // No exact matches found - try fuzzy matching\n if (occurrences.length === 0) {\n const fuzzyMatch = findBestTextMatch(content, exact, positionHint);\n\n if (fuzzyMatch) {\n return { start: fuzzyMatch.start, end: fuzzyMatch.end };\n }\n\n return null;\n }\n\n // Only one match - no need for prefix/suffix disambiguation\n if (occurrences.length === 1) {\n const pos = occurrences[0]!; // Safe: length === 1 means first element exists\n return { start: pos, end: pos + exact.length };\n }\n\n // Multiple matches - use prefix/suffix to disambiguate\n if (prefix || suffix) {\n for (const pos of occurrences) {\n // Extract actual prefix from content\n const actualPrefixStart = Math.max(0, pos - (prefix?.length || 0));\n const actualPrefix = content.substring(actualPrefixStart, pos);\n\n // Extract actual suffix from content\n const actualSuffixEnd = Math.min(content.length, pos + exact.length + (suffix?.length || 0));\n const actualSuffix = content.substring(pos + exact.length, actualSuffixEnd);\n\n // Check if prefix matches\n const prefixMatch = !prefix || actualPrefix.endsWith(prefix);\n\n // Check if suffix matches\n const suffixMatch = !suffix || actualSuffix.startsWith(suffix);\n\n if (prefixMatch && suffixMatch) {\n return { start: pos, end: pos + exact.length };\n }\n }\n\n // No match with exact prefix/suffix - try partial prefix/suffix match\n for (const pos of occurrences) {\n const actualPrefix = content.substring(Math.max(0, pos - (prefix?.length || 0)), pos);\n const actualSuffix = content.substring(pos + exact.length, pos + exact.length + (suffix?.length || 0));\n\n // Fuzzy match: check if prefix/suffix are substrings (handles whitespace variations)\n const fuzzyPrefixMatch = !prefix || actualPrefix.includes(prefix.trim());\n const fuzzySuffixMatch = !suffix || actualSuffix.includes(suffix.trim());\n\n if (fuzzyPrefixMatch && fuzzySuffixMatch) {\n return { start: pos, end: pos + exact.length };\n }\n }\n }\n\n // Fallback: return first occurrence if no prefix/suffix or no match\n const pos = occurrences[0]!; // Safe: we checked length > 0 earlier\n return { start: pos, end: pos + exact.length };\n}\n\n/**\n * Verify that a position correctly points to the exact text\n * Useful for debugging and validation\n */\nexport function verifyPosition(\n content: string,\n position: TextPosition,\n expectedExact: string\n): boolean {\n const actualText = content.substring(position.start, position.end);\n return actualText === expectedExact;\n}\n","/**\n * Locale information\n * Copied from SDK for frontend use\n */\n\nexport interface LocaleInfo {\n code: string;\n nativeName: string;\n englishName: string;\n}\n\nexport const LOCALES: readonly LocaleInfo[] = [\n { code: 'ar', nativeName: 'العربية', englishName: 'Arabic' },\n { code: 'bn', nativeName: 'বাংলা', englishName: 'Bengali' },\n { code: 'cs', nativeName: 'Čeština', englishName: 'Czech' },\n { code: 'da', nativeName: 'Dansk', englishName: 'Danish' },\n { code: 'de', nativeName: 'Deutsch', englishName: 'German' },\n { code: 'el', nativeName: 'Ελληνικά', englishName: 'Greek' },\n { code: 'en', nativeName: 'English', englishName: 'English' },\n { code: 'es', nativeName: 'Español', englishName: 'Spanish' },\n { code: 'fa', nativeName: 'فارسی', englishName: 'Persian' },\n { code: 'fi', nativeName: 'Suomi', englishName: 'Finnish' },\n { code: 'fr', nativeName: 'Français', englishName: 'French' },\n { code: 'he', nativeName: 'עברית', englishName: 'Hebrew' },\n { code: 'hi', nativeName: 'हिन्दी', englishName: 'Hindi' },\n { code: 'id', nativeName: 'Bahasa Indonesia', englishName: 'Indonesian' },\n { code: 'it', nativeName: 'Italiano', englishName: 'Italian' },\n { code: 'ja', nativeName: '日本語', englishName: 'Japanese' },\n { code: 'ko', nativeName: '한국어', englishName: 'Korean' },\n { code: 'ms', nativeName: 'Bahasa Melayu', englishName: 'Malay' },\n { code: 'nl', nativeName: 'Nederlands', englishName: 'Dutch' },\n { code: 'no', nativeName: 'Norsk', englishName: 'Norwegian' },\n { code: 'pl', nativeName: 'Polski', englishName: 'Polish' },\n { code: 'pt', nativeName: 'Português', englishName: 'Portuguese' },\n { code: 'ro', nativeName: 'Română', englishName: 'Romanian' },\n { code: 'sv', nativeName: 'Svenska', englishName: 'Swedish' },\n { code: 'th', nativeName: 'ไทย', englishName: 'Thai' },\n { code: 'tr', nativeName: 'Türkçe', englishName: 'Turkish' },\n { code: 'uk', nativeName: 'Українська', englishName: 'Ukrainian' },\n { code: 'vi', nativeName: 'Tiếng Việt', englishName: 'Vietnamese' },\n { code: 'zh', nativeName: '中文', englishName: 'Chinese' },\n] as const;\n\n// Create lookup map for efficient access\nconst localeByCode = new Map<string, LocaleInfo>(\n LOCALES.map(locale => [locale.code.toLowerCase(), locale])\n);\n\n/**\n * Get locale information by code\n */\nexport function getLocaleInfo(code: string | undefined): LocaleInfo | undefined {\n if (!code) return undefined;\n return localeByCode.get(code.toLowerCase());\n}\n\n/**\n * Get the native name of a language by its locale code\n */\nexport function getLocaleNativeName(code: string | undefined): string | undefined {\n return getLocaleInfo(code)?.nativeName;\n}\n\n/**\n * Get the English name of a language by its locale code\n */\nexport function getLocaleEnglishName(code: string | undefined): string | undefined {\n return getLocaleInfo(code)?.englishName;\n}\n\n/**\n * Format locale code for display as \"Native Name (code)\"\n */\nexport function formatLocaleDisplay(code: string | undefined): string | undefined {\n if (!code) return undefined;\n\n const info = getLocaleInfo(code);\n if (!info) return code;\n\n return `${info.nativeName} (${code.toLowerCase()})`;\n}\n\n/**\n * Get all supported locale codes\n */\nexport function getAllLocaleCodes(): readonly string[] {\n return LOCALES.map(l => l.code);\n}\n","/**\n * Helper functions for working with W3C ResourceDescriptor\n */\n\nimport type { components } from '@semiont/core';\n\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\ntype Representation = components['schemas']['Representation'];\n\n/**\n * Get the resource ID from @id property\n *\n * For internal resources: extracts UUID from \"http://localhost:4000/resources/{uuid}\"\n * For external resources: returns undefined\n *\n * This is used for routing - the frontend URL should contain only the resource ID,\n * not the full HTTP URI.\n */\nexport function getResourceId(resource: ResourceDescriptor | undefined): string | undefined {\n if (!resource) return undefined;\n\n const fullId = resource['@id'];\n\n // For internal resources, extract the last path segment\n // http://localhost:4000/resources/{uuid} -> {uuid}\n if (fullId.includes('/resources/')) {\n const parts = fullId.split('/resources/');\n const lastPart = parts[parts.length - 1];\n return lastPart || undefined;\n }\n\n // For external resources, cannot extract ID\n return undefined;\n}\n\n/**\n * Get the primary representation (first or only representation)\n */\nexport function getPrimaryRepresentation(resource: ResourceDescriptor | undefined): Representation | undefined {\n if (!resource?.representations) return undefined;\n const reps = Array.isArray(resource.representations)\n ? resource.representations\n : [resource.representations];\n return reps[0];\n}\n\n/**\n * Get the media type from the primary representation\n */\nexport function getPrimaryMediaType(resource: ResourceDescriptor | undefined): string | undefined {\n return getPrimaryRepresentation(resource)?.mediaType;\n}\n\n/**\n * Get the checksum from the primary representation\n */\nexport function getChecksum(resource: ResourceDescriptor | undefined): string | undefined {\n return getPrimaryRepresentation(resource)?.checksum;\n}\n\n/**\n * Get the language from the primary representation\n */\nexport function getLanguage(resource: ResourceDescriptor | undefined): string | undefined {\n return getPrimaryRepresentation(resource)?.language;\n}\n\n/**\n * Get storage URI from primary representation\n *\n * @param resource - ResourceDescriptor\n * @returns Storage URI or undefined\n */\nexport function getStorageUri(resource: ResourceDescriptor | undefined): string | undefined {\n return getPrimaryRepresentation(resource)?.storageUri;\n}\n\n/**\n * Get creator agent from wasAttributedTo\n * Handles both single agent and array of agents\n *\n * @param resource - ResourceDescriptor\n * @returns First agent or undefined\n */\nexport function getCreator(resource: ResourceDescriptor | undefined): components['schemas']['Agent'] | undefined {\n if (!resource?.wasAttributedTo) return undefined;\n\n return Array.isArray(resource.wasAttributedTo)\n ? resource.wasAttributedTo[0]\n : resource.wasAttributedTo;\n}\n\n/**\n * Get derived-from URI\n * Handles both single URI and array of URIs\n *\n * @param resource - ResourceDescriptor\n * @returns First derivation URI or undefined\n */\nexport function getDerivedFrom(resource: ResourceDescriptor | undefined): string | undefined {\n if (!resource?.wasDerivedFrom) return undefined;\n\n return Array.isArray(resource.wasDerivedFrom)\n ? resource.wasDerivedFrom[0]\n : resource.wasDerivedFrom;\n}\n\n/**\n * Check if resource is archived (application-specific field)\n *\n * @param resource - ResourceDescriptor\n * @returns True if archived, false otherwise\n */\nexport function isArchived(resource: ResourceDescriptor | undefined): boolean {\n return resource?.archived === true;\n}\n\n/**\n * Get entity types from resource (application-specific field)\n *\n * @param resource - ResourceDescriptor\n * @returns Array of entity types, empty if not set\n */\nexport function getResourceEntityTypes(resource: ResourceDescriptor | undefined): string[] {\n return resource?.entityTypes || [];\n}\n\n/**\n * Check if resource is a draft (application-specific field)\n *\n * @param resource - ResourceDescriptor\n * @returns True if draft, false otherwise\n */\nexport function isDraft(resource: ResourceDescriptor | undefined): boolean {\n return resource?.isDraft === true;\n}\n\n/**\n * Map charset names to Node.js Buffer encoding names\n * Node.js Buffer.toString() supports: 'utf8', 'utf16le', 'latin1', 'base64', 'hex', 'ascii', 'binary', 'ucs2'\n *\n * @param charset - Charset name (e.g., \"UTF-8\", \"ISO-8859-1\", \"Windows-1252\")\n * @returns Node.js BufferEncoding\n */\nexport function getNodeEncoding(charset: string): BufferEncoding {\n const normalized = charset.toLowerCase().replace(/[-_]/g, '');\n\n // Map common charset names to Node.js encodings\n const charsetMap: Record<string, BufferEncoding> = {\n 'utf8': 'utf8',\n 'iso88591': 'latin1',\n 'latin1': 'latin1',\n 'ascii': 'ascii',\n 'usascii': 'ascii',\n 'utf16le': 'utf16le',\n 'ucs2': 'ucs2',\n 'binary': 'binary',\n 'windows1252': 'latin1', // Windows-1252 is a superset of Latin-1\n 'cp1252': 'latin1',\n };\n\n return charsetMap[normalized] || 'utf8';\n}\n\n/**\n * Decode a representation buffer to string using the correct charset\n * Extracts charset from media type and uses appropriate encoding\n *\n * @param buffer - The raw representation data\n * @param mediaType - Media type with optional charset (e.g., \"text/plain; charset=iso-8859-1\")\n * @returns Decoded string\n *\n * @example\n * ```typescript\n * const content = decodeRepresentation(buffer, \"text/plain; charset=utf-8\");\n * const legacy = decodeRepresentation(buffer, \"text/plain; charset=windows-1252\");\n * ```\n */\nexport function decodeRepresentation(buffer: Buffer, mediaType: string): string {\n // Extract charset from mediaType (e.g., \"text/plain; charset=iso-8859-1\")\n const charsetMatch = mediaType.match(/charset=([^\\s;]+)/i);\n const charset = (charsetMatch?.[1] || 'utf-8').toLowerCase();\n\n // Map to Node.js encoding\n const encoding = getNodeEncoding(charset);\n\n return buffer.toString(encoding);\n}\n","/**\n * SVG Utility Functions\n *\n * Utilities for creating, parsing, and manipulating W3C-compliant SVG selectors\n * for image annotation.\n */\n\nexport interface Point {\n x: number;\n y: number;\n}\n\nexport interface BoundingBox {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/**\n * Create W3C-compliant SVG rectangle selector\n */\nexport function createRectangleSvg(start: Point, end: Point): string {\n const x = Math.min(start.x, end.x);\n const y = Math.min(start.y, end.y);\n const width = Math.abs(end.x - start.x);\n const height = Math.abs(end.y - start.y);\n\n return `<svg xmlns=\"http://www.w3.org/2000/svg\"><rect x=\"${x}\" y=\"${y}\" width=\"${width}\" height=\"${height}\"/></svg>`;\n}\n\n/**\n * Create W3C-compliant SVG polygon selector\n */\nexport function createPolygonSvg(points: Point[]): string {\n if (points.length < 3) {\n throw new Error('Polygon requires at least 3 points');\n }\n\n const pointsStr = points.map(p => `${p.x},${p.y}`).join(' ');\n return `<svg xmlns=\"http://www.w3.org/2000/svg\"><polygon points=\"${pointsStr}\"/></svg>`;\n}\n\n/**\n * Create W3C-compliant SVG circle selector\n */\nexport function createCircleSvg(center: Point, radius: number): string {\n if (radius <= 0) {\n throw new Error('Circle radius must be positive');\n }\n\n return `<svg xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"${center.x}\" cy=\"${center.y}\" r=\"${radius}\"/></svg>`;\n}\n\n/**\n * Parse SVG selector to extract shape type and data\n */\nexport function parseSvgSelector(svg: string): {\n type: 'rect' | 'polygon' | 'circle' | 'path';\n data: any;\n} | null {\n // Extract rectangle\n const rectMatch = svg.match(/<rect\\s+([^>]+)\\/>/);\n if (rectMatch && rectMatch[1]) {\n const attrs = rectMatch[1];\n const x = parseFloat(attrs.match(/x=\"([^\"]+)\"/)?.[1] || '0');\n const y = parseFloat(attrs.match(/y=\"([^\"]+)\"/)?.[1] || '0');\n const width = parseFloat(attrs.match(/width=\"([^\"]+)\"/)?.[1] || '0');\n const height = parseFloat(attrs.match(/height=\"([^\"]+)\"/)?.[1] || '0');\n\n return {\n type: 'rect',\n data: { x, y, width, height }\n };\n }\n\n // Extract polygon\n const polygonMatch = svg.match(/<polygon\\s+points=\"([^\"]+)\"/);\n if (polygonMatch && polygonMatch[1]) {\n const pointsStr = polygonMatch[1];\n const points = pointsStr.split(/\\s+/).map(pair => {\n const [x, y] = pair.split(',').map(parseFloat);\n return { x, y };\n });\n\n return {\n type: 'polygon',\n data: { points }\n };\n }\n\n // Extract circle\n const circleMatch = svg.match(/<circle\\s+([^>]+)\\/>/);\n if (circleMatch && circleMatch[1]) {\n const attrs = circleMatch[1];\n const cx = parseFloat(attrs.match(/cx=\"([^\"]+)\"/)?.[1] || '0');\n const cy = parseFloat(attrs.match(/cy=\"([^\"]+)\"/)?.[1] || '0');\n const r = parseFloat(attrs.match(/r=\"([^\"]+)\"/)?.[1] || '0');\n\n return {\n type: 'circle',\n data: { cx, cy, r }\n };\n }\n\n return null;\n}\n\n/**\n * Normalize coordinates from display space to image native resolution\n */\nexport function normalizeCoordinates(\n point: Point,\n displayWidth: number,\n displayHeight: number,\n imageWidth: number,\n imageHeight: number\n): Point {\n return {\n x: (point.x / displayWidth) * imageWidth,\n y: (point.y / displayHeight) * imageHeight\n };\n}\n\n/**\n * Scale entire SVG selector from display space to image native resolution\n */\nexport function scaleSvgToNative(\n svg: string,\n displayWidth: number,\n displayHeight: number,\n imageWidth: number,\n imageHeight: number\n): string {\n const parsed = parseSvgSelector(svg);\n if (!parsed) return svg;\n\n const scaleX = imageWidth / displayWidth;\n const scaleY = imageHeight / displayHeight;\n\n switch (parsed.type) {\n case 'rect': {\n const { x, y, width, height } = parsed.data;\n return createRectangleSvg(\n { x: x * scaleX, y: y * scaleY },\n { x: (x + width) * scaleX, y: (y + height) * scaleY }\n );\n }\n\n case 'circle': {\n const { cx, cy, r } = parsed.data;\n return createCircleSvg(\n { x: cx * scaleX, y: cy * scaleY },\n r * Math.min(scaleX, scaleY)\n );\n }\n\n case 'polygon': {\n const points = parsed.data.points.map((p: Point) => ({\n x: p.x * scaleX,\n y: p.y * scaleY\n }));\n return createPolygonSvg(points);\n }\n }\n\n return svg;\n}\n","/**\n * Text context extraction utilities for W3C Web Annotation TextQuoteSelector\n *\n * Provides robust prefix/suffix context extraction with word boundary detection\n * to ensure fuzzy anchoring works correctly when the same text appears multiple times.\n *\n * Also provides AI offset validation and correction for handling AI-generated annotations\n * where the model may return slightly incorrect character offsets.\n *\n * @see https://www.w3.org/TR/annotation-model/#text-quote-selector\n */\n\nimport { findBestTextMatch, type MatchQuality } from './fuzzy-anchor';\n\n/**\n * Extract prefix and suffix context for TextQuoteSelector\n *\n * Extracts up to 64 characters before and after the selected text,\n * extending to word boundaries to avoid cutting words in half.\n * This ensures prefix/suffix are meaningful context for fuzzy anchoring.\n *\n * @param content - Full text content\n * @param start - Start offset of selection\n * @param end - End offset of selection\n * @returns Object with prefix and suffix (undefined if at boundaries)\n *\n * @example\n * ```typescript\n * const content = \"The United States Congress...\";\n * const context = extractContext(content, 4, 17); // \"United States\"\n * // Returns: { prefix: \"The \", suffix: \" Congress...\" }\n * // NOT: { prefix: \"nited \", suffix: \"gress...\" }\n * ```\n */\nexport function extractContext(\n content: string,\n start: number,\n end: number\n): { prefix?: string; suffix?: string } {\n const CONTEXT_LENGTH = 64;\n const MAX_EXTENSION = 32; // Maximum additional chars to extend for word boundary\n\n // Extract prefix (up to CONTEXT_LENGTH chars before start, extended to word boundary)\n let prefix: string | undefined;\n if (start > 0) {\n let prefixStart = Math.max(0, start - CONTEXT_LENGTH);\n\n // Extend backward to word boundary (whitespace or punctuation)\n // Stop if we hit start of content or exceed MAX_EXTENSION\n let extensionCount = 0;\n while (prefixStart > 0 && extensionCount < MAX_EXTENSION) {\n const char = content[prefixStart - 1];\n // Break on whitespace, punctuation, or common delimiters\n if (!char || /[\\s.,;:!?'\"()\\[\\]{}<>\\/\\\\]/.test(char)) {\n break;\n }\n prefixStart--;\n extensionCount++;\n }\n\n prefix = content.substring(prefixStart, start);\n }\n\n // Extract suffix (up to CONTEXT_LENGTH chars after end, extended to word boundary)\n let suffix: string | undefined;\n if (end < content.length) {\n let suffixEnd = Math.min(content.length, end + CONTEXT_LENGTH);\n\n // Extend forward to word boundary (whitespace or punctuation)\n // Stop if we hit end of content or exceed MAX_EXTENSION\n let extensionCount = 0;\n while (suffixEnd < content.length && extensionCount < MAX_EXTENSION) {\n const char = content[suffixEnd];\n // Break on whitespace, punctuation, or common delimiters\n if (!char || /[\\s.,;:!?'\"()\\[\\]{}<>\\/\\\\]/.test(char)) {\n break;\n }\n suffixEnd++;\n extensionCount++;\n }\n\n suffix = content.substring(end, suffixEnd);\n }\n\n return { prefix, suffix };\n}\n\n/**\n * Result of validating and correcting AI-provided annotation offsets\n */\nexport interface ValidatedAnnotation {\n start: number;\n end: number;\n exact: string;\n prefix?: string;\n suffix?: string;\n corrected: boolean; // True if offsets were adjusted from AI's original values\n fuzzyMatched?: boolean; // True if we had to use fuzzy matching (minor text differences)\n matchQuality?: MatchQuality; // How we found the match\n}\n\n\n/**\n * Validate and correct AI-provided annotation offsets with fuzzy matching tolerance\n *\n * AI models sometimes return offsets that don't match the actual text position,\n * or provide text with minor variations (case differences, whitespace, typos).\n *\n * This function uses a multi-strategy approach:\n * 1. Check if AI's offsets are exactly correct\n * 2. Try exact case-sensitive search\n * 3. Try case-insensitive search\n * 4. Try fuzzy matching with Levenshtein distance (5% tolerance)\n *\n * This ensures we're maximally tolerant of AI errors while still maintaining\n * annotation quality and logging what corrections were made.\n *\n * @param content - Full text content\n * @param aiStart - Start offset from AI\n * @param aiEnd - End offset from AI\n * @param exact - The exact text that should be at this position (from AI)\n * @returns Validated annotation with corrected offsets and context\n * @throws Error if no acceptable match can be found\n *\n * @example\n * ```typescript\n * // AI said start=1143, but actual text is at 1161\n * const result = validateAndCorrectOffsets(\n * content,\n * 1143,\n * 1289,\n * \"the question \\\"whether...\"\n * );\n * // Returns: { start: 1161, end: 1303, exact: \"...\", corrected: true, matchQuality: 'exact', ... }\n * ```\n */\nexport function validateAndCorrectOffsets(\n content: string,\n aiStart: number,\n aiEnd: number,\n exact: string\n): ValidatedAnnotation {\n // First, check if AI's offsets are correct\n const textAtOffset = content.substring(aiStart, aiEnd);\n\n if (textAtOffset === exact) {\n // AI got it right! Just add proper context\n const context = extractContext(content, aiStart, aiEnd);\n return {\n start: aiStart,\n end: aiEnd,\n exact,\n prefix: context.prefix,\n suffix: context.suffix,\n corrected: false,\n matchQuality: 'exact'\n };\n }\n\n // AI's offsets are wrong - try to find the text using multiple strategies\n const match = findBestTextMatch(content, exact, aiStart);\n\n if (!match) {\n throw new Error(\n 'Cannot find acceptable match for text in content. ' +\n 'All search strategies failed. Text may be hallucinated.'\n );\n }\n\n // Found a match! Extract the actual text from content\n const actualText = content.substring(match.start, match.end);\n\n // Extract context using corrected offsets\n const context = extractContext(content, match.start, match.end);\n\n return {\n start: match.start,\n end: match.end,\n exact: actualText, // Use actual text from document, not AI's version\n prefix: context.prefix,\n suffix: context.suffix,\n corrected: true,\n fuzzyMatched: match.matchQuality !== 'exact',\n matchQuality: match.matchQuality\n };\n}\n","/**\n * Text encoding utilities for consistent charset handling\n *\n * Ensures frontend decoding matches backend decoding by respecting\n * charset parameters in mediaType (e.g., \"text/plain; charset=iso-8859-1\")\n */\n\n/**\n * Extract charset from mediaType parameter\n *\n * @param mediaType - Media type with optional charset (e.g., \"text/plain; charset=utf-8\")\n * @returns Charset name in lowercase (defaults to \"utf-8\")\n *\n * @example\n * extractCharset(\"text/plain; charset=iso-8859-1\") // \"iso-8859-1\"\n * extractCharset(\"text/plain\") // \"utf-8\"\n */\nexport function extractCharset(mediaType: string): string {\n const charsetMatch = mediaType.match(/charset=([^\\s;]+)/i);\n return (charsetMatch?.[1] || 'utf-8').toLowerCase();\n}\n\n/**\n * Decode ArrayBuffer to string using charset from mediaType\n *\n * Uses TextDecoder with the charset extracted from mediaType parameter.\n * This ensures the same character space is used for both annotation creation\n * (backend) and rendering (frontend).\n *\n * @param buffer - Binary data to decode\n * @param mediaType - Media type with optional charset parameter\n * @returns Decoded string in the original character space\n *\n * @example\n * const buffer = new Uint8Array([...]);\n * const text = decodeWithCharset(buffer, \"text/plain; charset=iso-8859-1\");\n */\nexport function decodeWithCharset(buffer: ArrayBuffer, mediaType: string): string {\n const charset = extractCharset(mediaType);\n\n // TextDecoder supports standard charset names\n // Common mappings that work in browsers:\n // - utf-8, utf-16, utf-16le, utf-16be\n // - iso-8859-1 through iso-8859-15\n // - windows-1252, windows-1251, etc.\n const decoder = new TextDecoder(charset);\n return decoder.decode(buffer);\n}\n","/**\n * Generic validation utilities for @semiont/api-client\n *\n * Pure TypeScript validation with no external dependencies.\n * Safe to use in any JavaScript environment (Node.js, browser, Deno, etc.)\n */\n\n/**\n * Validation result types\n */\nexport type ValidationSuccess<T> = { success: true; data: T };\nexport type ValidationFailure = { success: false; error: string; details?: string[] };\nexport type ValidationResult<T> = ValidationSuccess<T> | ValidationFailure;\n\n/**\n * JWT Token validation\n *\n * Validates JWT token format (header.payload.signature).\n * Does not verify signature - use for format validation only.\n */\nexport const JWTTokenSchema = {\n parse(token: unknown): string {\n if (typeof token !== 'string') {\n throw new Error('Token must be a string');\n }\n if (!token || token.length === 0) {\n throw new Error('Token is required');\n }\n // JWT format: header.payload.signature\n const jwtRegex = /^[A-Za-z0-9\\-_]+\\.[A-Za-z0-9\\-_]+\\.[A-Za-z0-9\\-_]*$/;\n if (!jwtRegex.test(token)) {\n throw new Error('Invalid JWT token format');\n }\n return token;\n },\n\n safeParse(token: unknown): ValidationResult<string> {\n try {\n const validated = this.parse(token);\n return { success: true, data: validated };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Invalid JWT token',\n };\n }\n },\n};\n\n/**\n * Generic validation helper with error formatting\n *\n * Wraps any schema's parse method with try/catch and returns ValidationResult.\n *\n * @example\n * ```typescript\n * const result = validateData(JWTTokenSchema, 'eyJ...');\n * if (result.success) {\n * console.log('Valid token:', result.data);\n * } else {\n * console.error('Invalid:', result.error);\n * }\n * ```\n */\nexport function validateData<T>(\n schema: { parse(data: unknown): T },\n data: unknown\n): ValidationResult<T> {\n try {\n const validated = schema.parse(data);\n return { success: true, data: validated };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Validation failed',\n };\n }\n}\n\n/**\n * Email validation helper\n *\n * Validates email format using RFC 5322 simplified regex.\n *\n * @param email - Email address to validate\n * @returns true if valid email format\n */\nexport function isValidEmail(email: string): boolean {\n if (email.length < 1 || email.length > 255) {\n return false;\n }\n // RFC 5322 simplified email regex\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return emailRegex.test(email);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@semiont/api-client",
3
- "version": "0.2.34-build.92",
3
+ "version": "0.2.34",
4
4
  "description": "Semiont API SDK - types, client, and utilities",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",