import { SCHEMA_REF_REGEX, parseSchemaRef, type ParsedSchemaRef, type SchemaBlock, } from "@paperclipai/shared"; export const EMPTY_SCHEMA_BLOCKS: readonly SchemaBlock[] = []; const MAX_SCANNED_MARKDOWN_CHARS = 512 * 1024; const MAX_SCHEMA_FENCE_BODY_CHARS = 64 * 1024; const MAX_SCANNED_JSON_FENCES = 64; const MAX_FENCE_META_CHARS = 256; export function isPlainRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } type CanonicalStackItem = | { kind: "token"; text: string } | { kind: "exit"; ref: object } | { kind: "value"; value: unknown }; /** * Iteratively serializes arbitrary JSON-like values with sorted object keys * using an explicit heap stack so deeply nested payloads neither overflow the * call stack nor collide under depth truncation. */ function serializeCanonicalJson(root: unknown): string { const parts: string[] = []; const activeAncestors = new Set(); const stack: CanonicalStackItem[] = [{ kind: "value", value: root }]; while (stack.length > 0) { const current = stack.pop()!; if (current.kind === "token") { parts.push(current.text); continue; } if (current.kind === "exit") { activeAncestors.delete(current.ref); continue; } const value = current.value; if (value === null || value === undefined) { parts.push("null"); continue; } if (typeof value === "boolean" || typeof value === "number") { parts.push( Number.isFinite(value as number) || typeof value === "boolean" ? String(value) : "null", ); continue; } if (typeof value === "string") { parts.push(JSON.stringify(value)); continue; } if (Array.isArray(value)) { if (activeAncestors.has(value)) { parts.push('"[Circular]"'); continue; } if (value.length === 0) { parts.push("[]"); continue; } activeAncestors.add(value); stack.push({ kind: "exit", ref: value }); stack.push({ kind: "token", text: "]" }); for (let idx = value.length - 1; idx >= 0; idx -= 1) { stack.push({ kind: "value", value: value[idx] }); if (idx > 0) { stack.push({ kind: "token", text: "," }); } } stack.push({ kind: "token", text: "[" }); continue; } if (isPlainRecord(value)) { if (activeAncestors.has(value)) { parts.push('"[Circular]"'); continue; } const keys = Object.keys(value) .filter((key) => value[key] !== undefined) .sort(); if (keys.length === 0) { parts.push("{}"); continue; } activeAncestors.add(value); stack.push({ kind: "exit", ref: value }); stack.push({ kind: "token", text: "}" }); for (let idx = keys.length - 1; idx >= 0; idx -= 1) { const key = keys[idx]!; stack.push({ kind: "value", value: value[key] }); stack.push({ kind: "token", text: `${JSON.stringify(key)}:` }); if (idx > 0) { stack.push({ kind: "token", text: "," }); } } stack.push({ kind: "token", text: "{" }); continue; } parts.push(JSON.stringify(String(value))); } return parts.join(""); } export function canonicalSchemaBlockKey(block: SchemaBlock): string { return `${block.schema.toLowerCase()}@${block.version}:${serializeCanonicalJson(block.data)}`; } function isHorizontalSpace(code: number): boolean { return code === 32 || code === 9; } export function parseSchemaFenceMeta(meta: string | null | undefined): ParsedSchemaRef | null { if (!meta || meta.length > MAX_FENCE_META_CHARS) return null; let idx = 0; const len = meta.length; while (idx < len) { while (idx < len && isHorizontalSpace(meta.charCodeAt(idx))) { idx += 1; } if (idx >= len) break; let tokenEnd = idx; while (tokenEnd < len && !isHorizontalSpace(meta.charCodeAt(tokenEnd))) { tokenEnd += 1; } const token = meta.slice(idx, tokenEnd); idx = tokenEnd; if (token.length > 7 && token.slice(0, 7).toLowerCase() === "schema=") { const candidate = token.slice(7).toLowerCase(); if (!SCHEMA_REF_REGEX.test(candidate)) return null; try { return parseSchemaRef(candidate); } catch { return null; } } } return null; } export interface ParsedFencedSchemaBlock { block: SchemaBlock; rawJson: string; } /** * Parses a JSON code-fence payload into a `SchemaBlock` when valid. * * Supports: * 1. Explicit fence metadata (` ```json schema=@ `) with raw `data` object * (or `{ schema, data }` envelope). * 2. Envelope JSON (` ```json\n{ "schema": "@", "data": { ... } }\n``` `) * emitted by `formatBlocksAsFencedJson`. * * Returns `null` when JSON is malformed, oversized, or not a schema object so callers * fall back cleanly to standard code block rendering. */ export function parseJsonSchemaBlock( rawCode: string, explicitRef?: string | null, ): ParsedFencedSchemaBlock | null { if (rawCode.length > MAX_SCHEMA_FENCE_BODY_CHARS) return null; const trimmed = rawCode.trim(); if (!trimmed.startsWith("{")) return null; let parsedRef: ParsedSchemaRef | null = null; if (explicitRef) { try { parsedRef = parseSchemaRef(explicitRef.toLowerCase()); } catch { return null; } } else if (!trimmed.includes('"schema"') || !trimmed.includes('"data"')) { return null; } let parsedJson: unknown; try { parsedJson = JSON.parse(trimmed); } catch { return null; } if (!isPlainRecord(parsedJson)) return null; if (parsedRef) { const keys = Object.keys(parsedJson); const isWrappedEnvelope = keys.length === 2 && typeof parsedJson.schema === "string" && parsedJson.schema.trim().toLowerCase() === parsedRef.ref && isPlainRecord(parsedJson.data); const data = isWrappedEnvelope ? (parsedJson.data as Record) : parsedJson; return { block: { schema: parsedRef.name, version: parsedRef.version, data, }, rawJson: JSON.stringify(data, null, 2), }; } const keys = Object.keys(parsedJson); if ( keys.length !== 2 || typeof parsedJson.schema !== "string" || !SCHEMA_REF_REGEX.test(parsedJson.schema.trim().toLowerCase()) || !isPlainRecord(parsedJson.data) ) { return null; } try { const envelopeRef = parseSchemaRef(parsedJson.schema.trim().toLowerCase()); return { block: { schema: envelopeRef.name, version: envelopeRef.version, data: parsedJson.data, }, rawJson: JSON.stringify(parsedJson.data, null, 2), }; } catch { return null; } } interface OpenMarkdownFence { markerCode: number; markerLen: number; isJson: boolean; meta: string | null; bodyStart: number; } function matchFenceOpening( markdown: string, lineStart: number, lineEnd: number, bodyStart: number, ): OpenMarkdownFence | null { let pos = lineStart; while (pos < lineEnd && pos - lineStart < 3 && markdown.charCodeAt(pos) === 32) { pos += 1; } if (pos >= lineEnd) return null; const markerCode = markdown.charCodeAt(pos); if (markerCode !== 96 && markerCode !== 126) return null; let markerEnd = pos; while (markerEnd < lineEnd && markdown.charCodeAt(markerEnd) === markerCode) { markerEnd += 1; } const markerLen = markerEnd - pos; if (markerLen < 3) return null; // CommonMark: backtick fence info strings cannot contain backticks. if (markerCode === 96) { for (let idx = markerEnd; idx < lineEnd; idx += 1) { if (markdown.charCodeAt(idx) === 96) return null; } } let infoStart = markerEnd; while (infoStart < lineEnd && isHorizontalSpace(markdown.charCodeAt(infoStart))) { infoStart += 1; } let langEnd = infoStart; while (langEnd < lineEnd && !isHorizontalSpace(markdown.charCodeAt(langEnd))) { langEnd += 1; } const lang = markdown.slice(infoStart, langEnd).toLowerCase(); const isJson = lang === "json"; let meta: string | null = null; if (isJson && langEnd < lineEnd) { const rest = markdown.slice(langEnd, lineEnd).trim(); if (rest.length > 0 && rest.length <= MAX_FENCE_META_CHARS) { meta = rest; } } return { markerCode, markerLen, isJson, meta, bodyStart, }; } function isMatchingFenceClose( markdown: string, lineStart: number, lineEnd: number, openFence: OpenMarkdownFence, ): boolean { let pos = lineStart; while (pos < lineEnd && pos - lineStart < 3 && markdown.charCodeAt(pos) === 32) { pos += 1; } if (pos >= lineEnd || markdown.charCodeAt(pos) !== openFence.markerCode) { return false; } let markerEnd = pos; while (markerEnd < lineEnd && markdown.charCodeAt(markerEnd) === openFence.markerCode) { markerEnd += 1; } if (markerEnd - pos < openFence.markerLen) { return false; } for (let idx = markerEnd; idx < lineEnd; idx += 1) { if (!isHorizontalSpace(markdown.charCodeAt(idx))) { return false; } } return true; } export interface ExtractedFencedSchemaBlocksResult { blocks: SchemaBlock[]; truncated: boolean; } /** * Single-pass O(N) CommonMark fence scanner with zero multi-line regexes or * backreferences. Unterminated fences consume to EOF once without rescanning * inner lines, ordinary non-schema JSON blocks do not consume the schema-parse * budget, and truncated scans are flagged explicitly so callers do not confuse * skipped content with a missing result block. */ export function extractFencedSchemaBlocksWithStatus( markdown: string | null | undefined, ): ExtractedFencedSchemaBlocksResult { if (!markdown) { return { blocks: EMPTY_SCHEMA_BLOCKS as SchemaBlock[], truncated: false }; } let truncated = false; let source = markdown; if (markdown.length > MAX_SCANNED_MARKDOWN_CHARS) { truncated = true; const lastNewline = markdown.lastIndexOf("\n", MAX_SCANNED_MARKDOWN_CHARS - 1); if (lastNewline === -1) { return { blocks: EMPTY_SCHEMA_BLOCKS as SchemaBlock[], truncated: true }; } source = markdown.slice(0, lastNewline); } if (!source.includes("```") && !source.includes("~~~")) { return { blocks: EMPTY_SCHEMA_BLOCKS as SchemaBlock[], truncated }; } const found: SchemaBlock[] = []; let openFence: OpenMarkdownFence | null = null; let parsedSchemaCandidates = 0; let lineStart = 0; const totalLen = source.length; while (lineStart <= totalLen) { const nlIdx = source.indexOf("\n", lineStart); const rawLineEnd = nlIdx === -1 ? totalLen : nlIdx; const lineEnd = rawLineEnd > lineStart && source.charCodeAt(rawLineEnd - 1) === 13 ? rawLineEnd - 1 : rawLineEnd; const nextLineStart = nlIdx === -1 ? totalLen + 1 : nlIdx + 1; if (openFence === null) { openFence = matchFenceOpening(source, lineStart, lineEnd, nextLineStart); } else if (isMatchingFenceClose(source, lineStart, lineEnd, openFence)) { if (openFence.isJson) { let bodyEnd = lineStart; if (bodyEnd > openFence.bodyStart && source.charCodeAt(bodyEnd - 1) === 10) { bodyEnd -= 1; if (bodyEnd > openFence.bodyStart && source.charCodeAt(bodyEnd - 1) === 13) { bodyEnd -= 1; } } const bodyLen = bodyEnd - openFence.bodyStart; const metaRef = parseSchemaFenceMeta(openFence.meta); if (bodyLen > MAX_SCHEMA_FENCE_BODY_CHARS) { if (metaRef) { truncated = true; } } else if (bodyLen > 0) { const rawBody = source.slice(openFence.bodyStart, bodyEnd); const isCandidate = Boolean(metaRef) || (rawBody.includes('"schema"') && rawBody.includes('"data"')); if (isCandidate) { if (parsedSchemaCandidates >= MAX_SCANNED_JSON_FENCES) { truncated = true; openFence = null; break; } parsedSchemaCandidates += 1; const parsed = parseJsonSchemaBlock(rawBody, metaRef?.ref ?? null); if (parsed) { found.push(parsed.block); } } } } openFence = null; } lineStart = nextLineStart; } return { blocks: found, truncated }; } export function extractFencedSchemaBlocks(markdown: string | null | undefined): SchemaBlock[] { return extractFencedSchemaBlocksWithStatus(markdown).blocks; } export function getUnfencedSchemaBlocks( markdown: string | null | undefined, blocks: readonly SchemaBlock[] | null | undefined, ): readonly SchemaBlock[] { if (!blocks || blocks.length === 0) return EMPTY_SCHEMA_BLOCKS; if (!markdown || (!markdown.includes("```") && !markdown.includes("~~~"))) { return blocks; } const fenced = extractFencedSchemaBlocks(markdown); if (fenced.length === 0) return blocks; const fencedKeys = new Set(fenced.map(canonicalSchemaBlockKey)); const remaining = blocks.filter((block) => !fencedKeys.has(canonicalSchemaBlockKey(block))); return remaining.length > 0 ? remaining : EMPTY_SCHEMA_BLOCKS; } export type SchemaBlockMatchStatus = "matched" | "missing" | "unverified"; export function checkMatchingSchemaBlock( schemaRef: string | null | undefined, sources: { schemaBlocks?: readonly SchemaBlock[] | null; markdownBodies?: ReadonlyArray; commentSchemaBlocks?: ReadonlyArray; }, ): SchemaBlockMatchStatus { if (!schemaRef) return "missing"; let target: ParsedSchemaRef; try { target = parseSchemaRef(schemaRef.trim().toLowerCase()); } catch { return "missing"; } const matches = (block: SchemaBlock) => block.schema.toLowerCase() === target.name && block.version === target.version; if (sources.schemaBlocks?.some(matches)) return "matched"; if (sources.commentSchemaBlocks?.some((list) => list?.some(matches))) return "matched"; let anyTruncated = false; if (sources.markdownBodies) { for (const body of sources.markdownBodies) { if (!body) continue; const scanned = extractFencedSchemaBlocksWithStatus(body); if (scanned.blocks.some(matches)) return "matched"; if (scanned.truncated) { anyTruncated = true; } } } return anyTruncated ? "unverified" : "missing"; } export function hasMatchingSchemaBlock( schemaRef: string | null | undefined, sources: { schemaBlocks?: readonly SchemaBlock[] | null; markdownBodies?: ReadonlyArray; commentSchemaBlocks?: ReadonlyArray; }, ): boolean { return checkMatchingSchemaBlock(schemaRef, sources) === "matched"; } export function safeHttpsUrl(raw: unknown): string | null { if (typeof raw !== "string") return null; const trimmed = raw.trim(); if (!trimmed) return null; try { const parsed = new URL(trimmed); return parsed.protocol === "https:" ? parsed.toString() : null; } catch { return null; } }