@deepcitation/deepcitation-js 1.1.38 → 1.1.40

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.
package/README.md CHANGED
@@ -66,7 +66,7 @@ import { DeepCitation, wrapCitationPrompt } from "@deepcitation/deepcitation-js"
66
66
  const dc = new DeepCitation({ apiKey: process.env.DEEPCITATION_API_KEY });
67
67
 
68
68
  // Upload source files, this can be done before the user types their prompt
69
- const { fileDataParts, deepTextPromptPortion } = await dc.prepareFiles([
69
+ const { fileDataParts, deepTextPromptPortion } = await deepcitation.prepareFiles([
70
70
  { file: pdfBuffer, filename: "report.pdf" },
71
71
  ]);
72
72
 
@@ -91,7 +91,7 @@ const response = await llm.chat({
91
91
  Verify citations against the source documents.
92
92
 
93
93
  ```typescript
94
- const result = await dc.verifyAll({
94
+ const result = await deepcitation.verify({
95
95
  llmOutput: response.content,
96
96
  });
97
97
 
@@ -149,16 +149,16 @@ const dc = new DeepCitation({
149
149
  });
150
150
 
151
151
  // Upload and prepare source files
152
- await dc.prepareFiles(files: FileInput[])
152
+ await deepcitation.prepareFiles(files: FileInput[])
153
153
 
154
154
  // Convert URLs/Office docs to PDF
155
- await dc.convertToPdf(urlOrOptions: string | ConvertOptions)
155
+ await deepcitation.convertToPdf(urlOrOptions: string | ConvertOptions)
156
156
 
157
- // Verify LLM citations (parse and verify all)
158
- await dc.verifyAll({ llmOutput, outputImageFormat? })
157
+ // Verify LLM citations (recommended - parses and verifies all)
158
+ await deepcitation.verify({ llmOutput, outputImageFormat? })
159
159
 
160
- // Verify pre-parsed citations against a specific file
161
- await dc.verify(attachmentId, citations, options?)
160
+ // Verify pre-parsed citations against a specific attachment
161
+ await deepcitation.verifyAttachment(attachmentId, citations, options?)
162
162
  ```
163
163
 
164
164
  ### Prompt Utilities
@@ -1 +1 @@
1
- function E(t){return new TextEncoder().encode(t)}function Z(t){let e=1732584193,i=4023233417,r=2562383102,n=271733878,o=3285377520,p=t.length,a=p*8,c=p+1+8,l=Math.ceil(c/64)*64,s=new ArrayBuffer(l),C=new Uint8Array(s),d=new DataView(s);C.set(t),C[p]=128,d.setUint32(l-8,Math.floor(a/4294967296),false),d.setUint32(l-4,a>>>0,false);let u=new Uint32Array(80);for(let x=0;x<l;x+=64){for(let g=0;g<16;g++)u[g]=d.getUint32(x+g*4,false);for(let g=16;g<80;g++){let I=u[g-3]^u[g-8]^u[g-14]^u[g-16];u[g]=I<<1|I>>>31;}let f=e,h=i,_=r,k=n,S=o;for(let g=0;g<80;g++){let I,m;g<20?(I=h&_|~h&k,m=1518500249):g<40?(I=h^_^k,m=1859775393):g<60?(I=h&_|h&k|_&k,m=2400959708):(I=h^_^k,m=3395469782);let b=(f<<5|f>>>27)+I+S+m+u[g]>>>0;S=k,k=_,_=(h<<30|h>>>2)>>>0,h=f,f=b;}e=e+f>>>0,i=i+h>>>0,r=r+_>>>0,n=n+k>>>0,o=o+S>>>0;}let y=x=>x.toString(16).padStart(8,"0");return y(e)+y(i)+y(r)+y(n)+y(o)}function P(t){try{if(!t)return "";let e=typeof t=="string"?t:JSON.stringify(t);return Z(E(e))}catch(e){console.error("Error in making the hash:",e);}return ""}function Y(...t){return t.filter(Boolean).join(" ")}function U(t){return t.type==="url"||typeof t.url=="string"&&t.url.length>0}function A(t){let e=t.pageNumber||v(t.startPageKey),i=[t.attachmentId||"",e?.toString()||"",t.fullPhrase||"",t.keySpan?.toString()||"",t.lineIds?.join(",")||"",t.timestamps?.startTime||"",t.timestamps?.endTime||""];return U(t)&&i.push(t.url||"",t.title||"",t.domain||""),P(i.join("|")).slice(0,16)}function j(t){let e=[t.attachmentId||"",t.label||"",t.verifiedFullPhrase||"",t.verifiedKeySpan||"",t.verifiedLineIds?.join(",")||"",t.verifiedPageNumber?.toString()||"",t.verifiedTimestamps?.startTime||"",t.verifiedTimestamps?.endTime||"",t.verifiedMatchSnippet||"",t.hitIndexWithinPage?.toString()||""];return P(e.join("|")).slice(0,16)}function Q(t){let e=Math.random().toString(36).slice(2,11);return `${t}-${e}`}function tt(t,e={}){let{fallbackDisplay:i}=e;return t.keySpan?.toString()||t.citationNumber?.toString()||i||"1"}function et(t){return t.citationNumber?.toString()||"1"}function nt(t){return t.keySpan?.toString()||""}function it(...t){return t.filter(Boolean).join(" ")}var rt=4,st=1;function D(t){if(!t)return;let e=[],i=t.split(",");for(let r of i){let n=r.trim();if(n)if(n.includes("-")){let[o,p]=n.split("-"),a=parseInt(o,10),c=parseInt(p,10);if(!isNaN(a)&&!isNaN(c)&&a<=c)for(let l=a;l<=c;l++)e.push(l);else isNaN(a)||e.push(a);}else {let o=parseInt(n,10);isNaN(o)||e.push(o);}}if(e.length!==0)return [...new Set(e)].sort((r,n)=>r-n)}function R(t){let e=t?.status,i=e==="not_found",r=e==="found_phrase_missed_value",n=e==="found_key_span_only",o=e==="partial_text_found"||e==="found_on_other_page"||e==="found_on_other_line"||e==="first_word_found";return {isVerified:e==="found"||n||o||r,isMiss:i,isPartialMatch:o,isPending:e==="pending"||e==="loading"||!e}}var B=(t,e,i,r)=>{let n=m=>m?m.replace(/^['"]|['"]$/g,"").replace(/\\'/g,"'"):void 0,o=i?.current?i.current++:void 0,p=t.substring(0,t.indexOf("<cite")),a=t.includes("/>")?t.slice(t.indexOf("/>")+2):"",c=t.substring(t.indexOf("<cite"),t.indexOf("/>")+2),l=(m,b)=>{for(let O of b){let L=new RegExp(`${O}='((?:[^'\\\\]|\\\\.)*)'`),K=m.match(L);if(K)return K[1]}},s=l(c,["attachment_id","attachmentId","file_id","fileId"]),C=s?.length===20?s:e||s,d=l(c,["start_page_key","startPageKey","start_page"]),u,y;if(d){let m=d.match(/page[\_a-zA-Z]*(\d+)_index_(\d+)/);m&&(u=parseInt(m[1]),y=parseInt(m[2]));}let x=n(l(c,["full_phrase","fullPhrase"])),f=n(l(c,["key_span","keySpan"])),h=n(l(c,["reasoning"])),_=n(l(c,["value"])),k;try{let b=l(c,["line_ids","lineIds"])?.replace(/[A-Za-z_[\](){}:]/g,"");k=b?D(b):void 0;}catch(m){r&&console.error("Error parsing lineIds",m);}let S=l(c,["timestamps"]),g;if(S){let[m,b]=S.split("-")||[];g={startTime:m,endTime:b};}let I={attachmentId:C,pageNumber:u,startPageKey:`page_number_${u||1}_index_${y||0}`,fullPhrase:x,keySpan:f||_,citationNumber:o,lineIds:k,beforeCite:p,timestamps:g,reasoning:h};return {beforeCite:p,afterCite:a,citation:I}},J=(t,e)=>{if(!t)return null;let i=t.fullPhrase??t.full_phrase,r=t.startPageKey??t.start_page_key,n=t.keySpan??t.key_span,o=t.lineIds??t.line_ids,p=t.attachmentId??t.attachment_id??t.fileId??t.file_id,a=t.reasoning,c=t.value;if(!i)return null;let l;if(r){let d=r.match(/page[_a-zA-Z]*(\d+)_index_(\d+)/i);if(d)l=parseInt(d[1],10);else {let u=r.match(/^(\d+)_(\d+)$/);u&&(l=parseInt(u[1],10));}}let s=o?.length?[...o].sort((d,u)=>d-u):void 0;return {attachmentId:p,pageNumber:l,fullPhrase:i,citationNumber:e,lineIds:s,keySpan:n||c,reasoning:a}},V=t=>typeof t=="object"&&t!==null&&("fullPhrase"in t||"full_phrase"in t||"startPageKey"in t||"start_page_key"in t||"keySpan"in t||"key_span"in t||"lineIds"in t||"line_ids"in t),N=t=>Array.isArray(t)?t.length>0&&t.some(V):typeof t=="object"&&t!==null?V(t):false,M=t=>{let e={},i=Array.isArray(t)?t:[t],r=1;for(let n of i){let o=J(n,r++);if(o&&o.fullPhrase){let p=A(o);e[p]=o;}}return e},w=(t,e)=>{if(!(!t||typeof t!="object")){if(t.citation&&N(t.citation)){let i=Array.isArray(t.citation)?t.citation:[t.citation];e.push(...i);}if(t.citations&&N(t.citations)){let i=Array.isArray(t.citations)?t.citations:[t.citations];e.push(...i);}if(Array.isArray(t))for(let i of t)w(i,e);else for(let i of Object.keys(t))i!=="citation"&&i!=="citations"&&w(t[i],e);}},T=t=>{let e=$(t),i=/<cite\s+[^>]*\/>/g,r=e.match(i);if(!r||r.length===0)return {};let n={},o={current:1};for(let p of r){let{citation:a}=B(p,void 0,o);if(a&&a.fullPhrase){let c=A(a);n[c]=a;}}return n},lt=t=>{if(!t)return {};let e={};if(typeof t=="object"){if(N(t)){let n=M(t);Object.assign(e,n);}else {let n=[];if(w(t,n),n.length>0){let o=M(n);Object.assign(e,o);}}let i=JSON.stringify(t),r=T(i);Object.assign(e,r);}else if(typeof t=="string"){let i=T(t);Object.assign(e,i);}return e};function ut(t){let e=new Map,i=Array.isArray(t)?t.map((r,n)=>[A(r)||String(n+1),r]):Object.entries(t);for(let[r,n]of i){let o=n.attachmentId||"";e.has(o)||e.set(o,{}),e.get(o)[r]=n;}return e}function pt(t){let e={},i=Array.isArray(t)?t.map((r,n)=>[A(r)||String(n+1),r]):Object.entries(t);for(let[r,n]of i){let o=n.attachmentId||"";e[o]||(e[o]={}),e[o][r]=n;}return e}var F=t=>{let e={},i=/([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(['"])((?:[^'"\\]|\\.)*)\2/g,r;for(;(r=i.exec(t))!==null;){let n=r[1].toLowerCase().replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase(),o=r[3],p=n==="fileid"||n==="file_id"||n==="attachmentid"?"attachment_id":n==="keyspan"?"key_span":n==="fullphrase"?"full_phrase":n==="lineids"?"line_ids":n==="startpagekey"||n==="start_pagekey"?"start_page_key":n;e[p]=o;}return e},W=t=>{if(!t)return "\u25CC";let e=R(t);return e.isPending?"\u25CC":e.isMiss?"\u2717":e.isPartialMatch?"\u26A0":e.isVerified?"\u2713":"\u25CC"},H=(t,e={})=>{let{leaveKeySpanBehind:i=false,verifications:r,showVerificationStatus:n=false}=e,o=0,p=/<cite\s+[^>]*?\/>/g;return t.replace(p,a=>{o++;let c=F(a),l="";if(i&&c.key_span&&(l=c.key_span.replace(/\\'/g,"'").replace(/\\"/g,'"')),n&&r){let s,C=String(o);if(s=r[C],!s&&c.attachment_id){for(let[,u]of Object.entries(r))if(u.attachmentId===c.attachment_id){s=u;break}}let d=W(s);l=l?`${l}${d}`:d;}return l})},dt=(t,e)=>H(t,{leaveKeySpanBehind:e}),mt=t=>t.replace(/<page_number_\d+_index_\d+>/g,"").replace(/<\/page_number_\d+_index_\d+>/g,"").trim(),ht=t=>{let e=/<line id="[^"]*">|<\/line>/g;return t.replace(e,"")},v=t=>{if(!t)return null;let e=t.match(/\d+/)?.[0];return e?parseInt(e):null},$=t=>{let e=t?.trim()||"",i=e.split(/(<cite[\s\S]*?(?:\/>|<\/cite>))/gm);return i.length<=1?z(e):(e=i.map(r=>r.startsWith("<cite")?z(r):r).join(""),e)},z=t=>{let e=t;e=e.replace(/><\/cite>/g,"/>");let i=p=>{let a=p.toLowerCase();return a==="fullphrase"||a==="full_phrase"?"full_phrase":a==="lineids"||a==="line_ids"?"line_ids":a==="startpagekey"||a==="start_pagekey"||a==="start_page_key"?"start_page_key":a==="fileid"||a==="file_id"||a==="attachmentid"||a==="attachment_id"?"attachment_id":a==="keyspan"||a==="key_span"?"key_span":a==="reasoning"||a==="value"?a:a==="timestamps"||a==="timestamp"||a==="timestamps"?"timestamps":a},r=p=>p.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),n=/(fullPhrase|full_phrase|keySpan|key_span|reasoning|value)\s*=\s*(['"])([\s\S]*?)(?=\s+(?:line_ids|lineIds|timestamps|fileId|file_id|attachmentId|attachment_id|start_page_key|start_pageKey|startPageKey|keySpan|key_span|reasoning|value|full_phrase)|\s*\/?>)/gm;e=e.replace(n,(p,a,c,l)=>{let s=l;return s.endsWith(c)&&(s=s.slice(0,-1)),s=s.replace(/(\r?\n)+/g," "),s=r(s),s=s.replace(/(\*|_){2,}/g,""),s=s.replace(/\\\\'/g,"'"),s=s.replace(/\\'/g,"'"),s=s.replace(/'/g,"\\'"),s=s.replace(/\\\\"/g,'"'),s=s.replace(/\\"/g,'"'),s=s.replace(/"/g,'\\"'),s=s.replace(/\*/g,""),`${i(a)}='${s}'`}),e=e.replace(/(line_ids|lineIds|timestamps)=['"]?([\[\]\(\){}A-Za-z0-9_\-, ]+)['"]?(\s*\/?>|\s+)/gm,(p,a,c,l)=>{let s=c.replace(/[A-Za-z\[\]\(\){}]/g,"");return s=s.replace(/(\d+)-(\d+)/g,(C,d,u)=>{let y=parseInt(d,10),x=parseInt(u,10),f=[];if(y<=x)for(let h=y;h<=x;h++)f.push(h);else f.push(y);return f.join(",")}),s=s.replace(/,+/g,",").replace(/^,|,$/g,""),`${i(a)}='${s}'${l}`});let o=p=>{let a=/([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(['"])((?:[^'"\\\n]|\\.)*)(?:\2)/g,c={},l;for(;l=a.exec(p);){let f=l[1],h=l[3],_=i(f);c[_]=h;}let s=Object.keys(c);if(s.length===0)return p;let C=typeof c.timestamps=="string"&&c.timestamps.length>0,d=s.filter(f=>f.startsWith("start_page")),u=[];c.attachment_id&&u.push("attachment_id"),C?(c.full_phrase&&u.push("full_phrase"),u.push("timestamps")):(d.includes("start_page_key")&&u.push("start_page_key"),d.filter(f=>f!=="start_page_key").sort().forEach(f=>u.push(f)),c.full_phrase&&u.push("full_phrase"),c.key_span&&u.push("key_span"),c.line_ids&&u.push("line_ids")),c.reasoning&&u.push("reasoning"),c.value&&u.push("value");let y=new Set(u);return s.filter(f=>!y.has(f)).sort().forEach(f=>u.push(f)),`<cite ${u.map(f=>`${f}='${c[f]}'`).join(" ")} />`};return e=e.replace(/<cite\b[\s\S]*?\/>/gm,p=>o(p)),e};export{H as a,dt as b,mt as c,ht as d,v as e,$ as f,P as g,Y as h,U as i,A as j,j as k,Q as l,tt as m,et as n,nt as o,it as p,rt as q,st as r,R as s,B as t,lt as u,ut as v,pt as w};
1
+ function E(t){return new TextEncoder().encode(t)}function Z(t){let e=1732584193,i=4023233417,r=2562383102,n=271733878,o=3285377520,p=t.length,a=p*8,c=p+1+8,u=Math.ceil(c/64)*64,s=new ArrayBuffer(u),C=new Uint8Array(s),d=new DataView(s);C.set(t),C[p]=128,d.setUint32(u-8,Math.floor(a/4294967296),false),d.setUint32(u-4,a>>>0,false);let l=new Uint32Array(80);for(let x=0;x<u;x+=64){for(let g=0;g<16;g++)l[g]=d.getUint32(x+g*4,false);for(let g=16;g<80;g++){let I=l[g-3]^l[g-8]^l[g-14]^l[g-16];l[g]=I<<1|I>>>31;}let f=e,h=i,_=r,k=n,S=o;for(let g=0;g<80;g++){let I,m;g<20?(I=h&_|~h&k,m=1518500249):g<40?(I=h^_^k,m=1859775393):g<60?(I=h&_|h&k|_&k,m=2400959708):(I=h^_^k,m=3395469782);let b=(f<<5|f>>>27)+I+S+m+l[g]>>>0;S=k,k=_,_=(h<<30|h>>>2)>>>0,h=f,f=b;}e=e+f>>>0,i=i+h>>>0,r=r+_>>>0,n=n+k>>>0,o=o+S>>>0;}let y=x=>x.toString(16).padStart(8,"0");return y(e)+y(i)+y(r)+y(n)+y(o)}function P(t){try{if(!t)return "";let e=typeof t=="string"?t:JSON.stringify(t);return Z(E(e))}catch(e){console.error("Error in making the hash:",e);}return ""}function Y(...t){return t.filter(Boolean).join(" ")}function U(t){return t.type==="url"||typeof t.url=="string"&&t.url.length>0}function A(t){let e=t.pageNumber||v(t.startPageKey),i=[t.attachmentId||"",e?.toString()||"",t.fullPhrase||"",t.keySpan?.toString()||"",t.lineIds?.join(",")||"",t.timestamps?.startTime||"",t.timestamps?.endTime||""];return U(t)&&i.push(t.url||"",t.title||"",t.domain||""),P(i.join("|")).slice(0,16)}function j(t){let e=[t.attachmentId||"",t.label||"",t.verifiedFullPhrase||"",t.verifiedKeySpan||"",t.verifiedLineIds?.join(",")||"",t.verifiedPageNumber?.toString()||"",t.verifiedTimestamps?.startTime||"",t.verifiedTimestamps?.endTime||"",t.verifiedMatchSnippet||"",t.hitIndexWithinPage?.toString()||""];return P(e.join("|")).slice(0,16)}function Q(t){let e=Math.random().toString(36).slice(2,11);return `${t}-${e}`}function tt(t,e={}){let{fallbackDisplay:i}=e;return t.keySpan?.toString()||t.citationNumber?.toString()||i||"1"}function et(t){return t.citationNumber?.toString()||"1"}function nt(t){return t.keySpan?.toString()||""}function it(...t){return t.filter(Boolean).join(" ")}var rt=4,st=1;function D(t){if(!t)return;let e=[],i=t.split(",");for(let r of i){let n=r.trim();if(n)if(n.includes("-")){let[o,p]=n.split("-"),a=parseInt(o,10),c=parseInt(p,10);if(!isNaN(a)&&!isNaN(c)&&a<=c)for(let u=a;u<=c;u++)e.push(u);else isNaN(a)||e.push(a);}else {let o=parseInt(n,10);isNaN(o)||e.push(o);}}if(e.length!==0)return [...new Set(e)].sort((r,n)=>r-n)}function R(t){let e=t?.status,i=e==="not_found",r=e==="found_phrase_missed_value",n=e==="found_key_span_only",o=e==="partial_text_found"||e==="found_on_other_page"||e==="found_on_other_line"||e==="first_word_found";return {isVerified:e==="found"||n||o||r,isMiss:i,isPartialMatch:o,isPending:e==="pending"||e==="loading"||!e}}var B=(t,e,i,r)=>{let n=m=>m?m.replace(/^['"]|['"]$/g,"").replace(/\\'/g,"'"):void 0,o=i?.current?i.current++:void 0,p=t.substring(0,t.indexOf("<cite")),a=t.includes("/>")?t.slice(t.indexOf("/>")+2):"",c=t.substring(t.indexOf("<cite"),t.indexOf("/>")+2),u=(m,b)=>{for(let O of b){let L=new RegExp(`${O}='((?:[^'\\\\]|\\\\.)*)'`),K=m.match(L);if(K)return K[1]}},s=u(c,["attachment_id","attachmentId","file_id","fileId"]),C=s?.length===20?s:e||s,d=u(c,["start_page_key","startPageKey","start_page"]),l,y;if(d){let m=d.match(/page[\_a-zA-Z]*(\d+)_index_(\d+)/);m&&(l=parseInt(m[1]),y=parseInt(m[2]));}let x=n(u(c,["full_phrase","fullPhrase"])),f=n(u(c,["key_span","keySpan"])),h=n(u(c,["reasoning"])),_=n(u(c,["value"])),k;try{let b=u(c,["line_ids","lineIds"])?.replace(/[A-Za-z_[\](){}:]/g,"");k=b?D(b):void 0;}catch(m){r&&console.error("Error parsing lineIds",m);}let S=u(c,["timestamps"]),g;if(S){let[m,b]=S.split("-")||[];g={startTime:m,endTime:b};}let I={attachmentId:C,pageNumber:l,startPageKey:`page_number_${l||1}_index_${y||0}`,fullPhrase:x,keySpan:f||_,citationNumber:o,lineIds:k,beforeCite:p,timestamps:g,reasoning:h};return {beforeCite:p,afterCite:a,citation:I}},J=(t,e)=>{if(!t)return null;let i=t.fullPhrase??t.full_phrase,r=t.startPageKey??t.start_page_key,n=t.keySpan??t.key_span,o=t.lineIds??t.line_ids,p=t.attachmentId??t.attachment_id??t.fileId??t.file_id,a=t.reasoning,c=t.value;if(!i)return null;let u;if(r){let d=r.match(/page[_a-zA-Z]*(\d+)_index_(\d+)/i);if(d)u=parseInt(d[1],10);else {let l=r.match(/^(\d+)_(\d+)$/);l&&(u=parseInt(l[1],10));}}let s=o?.length?[...o].sort((d,l)=>d-l):void 0;return {attachmentId:p,pageNumber:u,fullPhrase:i,citationNumber:e,lineIds:s,keySpan:n||c,reasoning:a}},V=t=>typeof t=="object"&&t!==null&&("fullPhrase"in t||"full_phrase"in t||"startPageKey"in t||"start_page_key"in t||"keySpan"in t||"key_span"in t||"lineIds"in t||"line_ids"in t),N=t=>Array.isArray(t)?t.length>0&&t.some(V):typeof t=="object"&&t!==null?V(t):false,M=t=>{let e={},i=Array.isArray(t)?t:[t],r=1;for(let n of i){let o=J(n,r++);if(o&&o.fullPhrase){let p=A(o);e[p]=o;}}return e},w=(t,e)=>{if(!(!t||typeof t!="object")){if(t.citation&&N(t.citation)){let i=Array.isArray(t.citation)?t.citation:[t.citation];e.push(...i);}if(t.citations&&N(t.citations)){let i=Array.isArray(t.citations)?t.citations:[t.citations];e.push(...i);}if(Array.isArray(t))for(let i of t)w(i,e);else for(let i of Object.keys(t))i!=="citation"&&i!=="citations"&&w(t[i],e);}},T=t=>{let e=$(t),i=/<cite\s+[^>]*\/>/g,r=e.match(i);if(!r||r.length===0)return {};let n={},o={current:1};for(let p of r){let{citation:a}=B(p,void 0,o);if(a&&a.fullPhrase){let c=A(a);n[c]=a;}}return n},lt=t=>{if(!t)return {};let e={};if(typeof t=="object"){if(N(t)){let n=M(t);Object.assign(e,n);}else {let n=[];if(w(t,n),n.length>0){let o=M(n);Object.assign(e,o);}}let i=JSON.stringify(t),r=T(i);Object.assign(e,r);}else if(typeof t=="string"){let i=T(t);Object.assign(e,i);}return e};function ut(t){let e=new Map,i=Array.isArray(t)?t.map((r,n)=>[A(r)||String(n+1),r]):Object.entries(t);for(let[r,n]of i){let o=n.attachmentId||"";e.has(o)||e.set(o,{}),e.get(o)[r]=n;}return e}function pt(t){let e={},i=Array.isArray(t)?t.map((r,n)=>[A(r)||String(n+1),r]):Object.entries(t);for(let[r,n]of i){let o=n.attachmentId||"";e[o]||(e[o]={}),e[o][r]=n;}return e}var F=t=>{let e={},i=/([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(['"])((?:[^'"\\]|\\.)*)\2/g,r;for(;(r=i.exec(t))!==null;){let n=r[1].toLowerCase().replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase(),o=r[3],p=n==="fileid"||n==="file_id"||n==="attachmentid"?"attachment_id":n==="keyspan"?"key_span":n==="fullphrase"?"full_phrase":n==="lineids"?"line_ids":n==="startpagekey"||n==="start_pagekey"?"start_page_key":n;e[p]=o;}return e},W=t=>{if(!t)return "\u25CC";let e=R(t);return e.isPending?"\u25CC":e.isMiss?"\u2717":e.isPartialMatch?"\u26A0":e.isVerified?"\u2713":"\u25CC"},H=(t,e={})=>{let{leaveKeySpanBehind:i=false,verifications:r,showVerificationStatus:n=false}=e,o=0,p=/<cite\s+[^>]*?\/>/g;return t.replace(p,a=>{o++;let c=F(a),u="";if(i&&c.key_span&&(u=c.key_span.replace(/\\'/g,"'").replace(/\\"/g,'"')),n&&r){let s,C=String(o);if(s=r[C],!s&&c.attachment_id){for(let[,l]of Object.entries(r))if(l.attachmentId===c.attachment_id){s=l;break}}let d=W(s);u=u?`${u}${d}`:d;}return u})},dt=(t,e)=>H(t,{leaveKeySpanBehind:e}),mt=t=>t.replace(/<page_number_\d+_index_\d+>/g,"").replace(/<\/page_number_\d+_index_\d+>/g,"").trim(),ht=t=>{let e=/<line id="[^"]*">|<\/line>/g;return t.replace(e,"")},v=t=>{if(!t)return null;let e=t.match(/\d+/)?.[0];return e?parseInt(e):null},$=t=>{let e=t?.trim()||"",i=e.split(/(<cite[\s\S]*?(?:\/>|<\/cite>))/gm);return i.length<=1?z(e):(e=i.map(r=>r.startsWith("<cite")?z(r):r).join(""),e)},z=t=>{let e=t;e=e.replace(/><\/cite>/g,"/>");let i=p=>{let a=p.toLowerCase();return a==="fullphrase"||a==="full_phrase"?"full_phrase":a==="lineids"||a==="line_ids"?"line_ids":a==="startpagekey"||a==="start_pagekey"||a==="start_page_key"?"start_page_key":a==="fileid"||a==="file_id"||a==="attachmentid"||a==="attachment_id"?"attachment_id":a==="keyspan"||a==="key_span"?"key_span":a==="reasoning"||a==="value"?a:a==="timestamps"||a==="timestamp"||a==="timestamps"?"timestamps":a},r=p=>p.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),n=/(fullPhrase|full_phrase|keySpan|key_span|reasoning|value)\s*=\s*(['"])([\s\S]*?)(?=\s+(?:line_ids|lineIds|timestamps|fileId|file_id|attachmentId|attachment_id|start_page_key|start_pageKey|startPageKey|keySpan|key_span|reasoning|value|full_phrase)|\s*\/?>)/gm;e=e.replace(n,(p,a,c,u)=>{let s=u;return s.endsWith(c)&&(s=s.slice(0,-1)),s=s.replace(/(\r?\n)+/g," "),s=r(s),s=s.replace(/(\*|_){2,}/g,""),s=s.replace(/\\\\'/g,"'"),s=s.replace(/\\'/g,"'"),s=s.replace(/'/g,"\\'"),s=s.replace(/\\\\"/g,'"'),s=s.replace(/\\"/g,'"'),s=s.replace(/"/g,'\\"'),s=s.replace(/\*/g,""),`${i(a)}='${s}'`}),e=e.replace(/(line_ids|lineIds|timestamps)=['"]?([\[\]\(\){}A-Za-z0-9_\-, ]+)['"]?(\s*\/?>|\s+)/gm,(p,a,c,u)=>{let s=c.replace(/[A-Za-z\[\]\(\){}]/g,"");return s=s.replace(/(\d+)-(\d+)/g,(C,d,l)=>{let y=parseInt(d,10),x=parseInt(l,10),f=[];if(y<=x)for(let h=y;h<=x;h++)f.push(h);else f.push(y);return f.join(",")}),s=s.replace(/,+/g,",").replace(/^,|,$/g,""),`${i(a)}='${s}'${u}`});let o=p=>{let a=/([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(['"])((?:[^'"\\\n]|\\.)*)(?:\2)/g,c={},u;for(;u=a.exec(p);){let f=u[1],h=u[3],_=i(f);c[_]=h;}let s=Object.keys(c);if(s.length===0)return p;let C=typeof c.timestamps=="string"&&c.timestamps.length>0,d=s.filter(f=>f.startsWith("start_page")),l=[];c.attachment_id&&l.push("attachment_id"),C?(c.full_phrase&&l.push("full_phrase"),c.key_span&&l.push("key_span"),l.push("timestamps")):(d.includes("start_page_key")&&l.push("start_page_key"),d.filter(f=>f!=="start_page_key").sort().forEach(f=>l.push(f)),c.full_phrase&&l.push("full_phrase"),c.key_span&&l.push("key_span"),c.line_ids&&l.push("line_ids")),c.reasoning&&l.push("reasoning"),c.value&&l.push("value");let y=new Set(l);return s.filter(f=>!y.has(f)).sort().forEach(f=>l.push(f)),`<cite ${l.map(f=>`${f}='${c[f]}'`).join(" ")} />`};return e=e.replace(/<cite\b[\s\S]*?\/>/gm,p=>o(p)),e};export{H as a,dt as b,mt as c,ht as d,v as e,$ as f,P as g,Y as h,U as i,A as j,j as k,Q as l,tt as m,et as n,nt as o,it as p,rt as q,st as r,R as s,B as t,lt as u,ut as v,pt as w};
@@ -4,14 +4,14 @@
4
4
 
5
5
  For every claim, value, or fact; you MUST cite sources using this exact syntax:
6
6
 
7
- <cite attachment_id='ID' reasoning='why this supports the claim' key_span='1-3 key words' full_phrase='verbatim quote' start_page_key='page_number_N_index_I' line_ids='X-Y' />
7
+ <cite attachment_id='ID' reasoning='why this supports the claim' full_phrase='verbatim quote' key_span='1-3 key words' start_page_key='page_number_N_index_I' line_ids='X-Y' />
8
8
 
9
9
  ### Syntax Rules (MUST follow)
10
10
 
11
11
  1. **attachment_id**: Use the exact ID from the source document
12
12
  2. **reasoning**: Brief explanation of why this citation supports your claim (think first!)
13
- 3. **key_span**: The 1-3 most important words or value from full_phrase
14
- 4. **full_phrase**: Copy text VERBATIM from source. Escape quotes (\\') and newlines (\\n).
13
+ 3. **full_phrase**: Copy text VERBATIM from source. Escape quotes (\\') and newlines (\\n).
14
+ 4. **key_span**: The 1-3 most important words or value from full_phrase
15
15
  5. **start_page_key**: ONLY use format \`page_number_N_index_I\` from page tags (e.g., \`<page_number_1_index_0>\`). Never extract page numbers from document content.
16
16
  6. **line_ids**: Inclusive range (e.g., '2-6' or '4'). Infer intermediate lines since only every 5th line is shown.
17
17
 
@@ -24,11 +24,11 @@ For every claim, value, or fact; you MUST cite sources using this exact syntax:
24
24
 
25
25
  ### Example Citation 1
26
26
 
27
- The company reported strong growth<cite attachment_id='abc123' reasoning='directly states revenue growth percentage' key_span='increased 45%' full_phrase='Revenue increased 45% year-over-year to $2.3 billion' start_page_key='page_number_2_index_1' line_ids='12-14' />
27
+ The company reported strong growth<cite attachment_id='abc123' reasoning='directly states revenue growth percentage' full_phrase='Revenue increased 45% year-over-year to $2.3 billion' key_span='increased 45%' start_page_key='page_number_2_index_1' line_ids='12-14' />
28
28
 
29
29
  ### Example Citation 2
30
30
 
31
- The total amount is $500 USD <cite attachment_id='abc123' reasoning='directly states the total amount' key_span='$500 USD' full_phrase='The total amount is $500 USD' start_page_key='page_number_2_index_1' line_ids='12-14' />
31
+ The total amount is $500 USD <cite attachment_id='abc123' reasoning='directly states the total amount' full_phrase='The total amount is $500 USD' key_span='$500 USD' start_page_key='page_number_2_index_1' line_ids='12-14' />
32
32
 
33
33
  </citation-instructions>
34
34
  `,y=`
@@ -37,14 +37,14 @@ The total amount is $500 USD <cite attachment_id='abc123' reasoning='directly st
37
37
 
38
38
  For every claim, value, or fact; you MUST cite sources using this exact syntax:
39
39
 
40
- <cite attachment_id='ID' reasoning='why this supports the claim' key_span='1-3 key words' full_phrase='verbatim transcript quote' timestamps='HH:MM:SS.SSS-HH:MM:SS.SSS' />
40
+ <cite attachment_id='ID' reasoning='why this supports the claim' full_phrase='verbatim transcript quote' key_span='1-3 key words' timestamps='HH:MM:SS.SSS-HH:MM:SS.SSS' />
41
41
 
42
42
  ### Syntax Rules (MUST follow)
43
43
 
44
44
  1. **attachment_id**: Use the exact ID from the source
45
45
  2. **reasoning**: Brief explanation of why this citation supports your claim (think first!)
46
- 3. **key_span**: The 1-3 most important words or value from full_phrase
47
- 4. **full_phrase**: Copy transcript text VERBATIM. Escape quotes (\\') and newlines (\\n).
46
+ 3. **full_phrase**: Copy transcript text VERBATIM. Escape quotes (\\') and newlines (\\n).
47
+ 4. **key_span**: The 1-3 most important words or value from full_phrase
48
48
  5. **timestamps**: Start and end time with milliseconds (e.g., '00:01:23.456-00:01:45.789')
49
49
 
50
50
  ### Placement Rules
@@ -67,4 +67,4 @@ ${a}`).join(`
67
67
 
68
68
  ${d}
69
69
 
70
- ${i}`;}return {enhancedSystemPrompt:s,enhancedUserPrompt:c}}var O={type:"object",properties:{attachmentId:{type:"string"},reasoning:{type:"string",description:"The logic connecting the form section requirements to the supporting source citation (think first!)"},keySpan:{type:"string",description:"The verbatim 1-3 words within fullPhrase that best support the citation"},fullPhrase:{type:"string",description:"The verbatim text of the terse phrase inside <attachment_text /> to support the citation (if there is a detected OCR correction, use the corrected text)"},startPageKey:{type:"string",description:'Only return a result like "page_number_PAGE_index_INDEX" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.'},lineIds:{type:"array",items:{type:"number"},description:"Infer lineIds, as we only provide the first, last, and every 5th line. Provide inclusive lineIds for the fullPhrase."}},required:["attachmentId","reasoning","keySpan","fullPhrase","startPageKey","lineIds"]},v={type:"object",properties:{attachmentId:{type:"string"},startPageKey:{type:"string",description:'Only return a result like "page_number_PAGE_index_INDEX" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.'},fullPhrase:{type:"string",description:"The exact verbatim text of the phrase or paragraph from the source document to support the citation (if there is a detected OCR correction, use the verbatim corrected text)"},timestamps:{type:"object",properties:{startTime:{type:"string"},endTime:{type:"string"}},required:["startTime","endTime"],description:"The timestamp of the audio or video frame including milliseconds formatted as: HH:MM:SS.SSS"}},required:["attachmentId","startPageKey","fullPhrase","timestamps"]};var u=4,I=3,P=5;function S(t,n){let i={};for(let e of t){for(let r=u;r<=e.length;r++){let s=e.slice(0,r),c=(s.match(/\d/g)||[]).length,o=(s.match(/[a-zA-Z]/g)||[]).length;if(s.length<u||c>0&&o<I||c===0&&o<P||t.some(m=>m!==e&&m.startsWith(s)))continue;let p=m=>m.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),a=(n.match(new RegExp(p(s),"g"))||[]).length,l=(n.match(new RegExp(p(e),"g"))||[]).length;if(a===l){i[s]=e;break}}if(!Object.values(i).includes(e))throw new Error(`Cannot find a safe unique prefix for ID "${e}" that meets the minimum requirements (length: ${u})`)}return i}function E(t,n){if(!n||n.length===0)return {compressed:t,prefixMap:{}};let i=Array.from(new Set(n)),e=JSON.stringify(t),r=S(i,e),s=Object.keys(r).sort((o,p)=>p.length-o.length),c=e;for(let o of s){let a=r[o].replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");c=c.replace(new RegExp(a,"g"),o);}return {compressed:JSON.parse(c),prefixMap:r}}function b(t,n){if(!n||Object.keys(n).length===0)return t;let i=Object.entries(n).sort((a,l)=>l[0].length-a[0].length),e,r=false;typeof t=="string"?e=t:(e=JSON.stringify(t),r=true);let s=e?.length;for(let[a,l]of i){let m=a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");e=e.replace(new RegExp(m,"g"),l);}let c=["attachmentId","attachment_id","attachment_ID","attachmentID","fileId","file_id","file_ID","fileID","fileid"];for(let[a,l]of i){let m=a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),h=c.join("|"),f="([\"'`])",g=new RegExp(`(${h})(\\s*=\\s*)${f}${m}\\3`,"g");e=e.replace(g,`$1$2$3${l}$3`);}let o=e?.length,p=s-o;if(p>0)throw new Error(`[decompressedPromptIds] diff ${p} originalLength ${s} newLength ${o}`);return r?JSON.parse(e):e}exports.a=_;exports.b=y;exports.c=d;exports.d=T;exports.e=x;exports.f=R;exports.g=O;exports.h=v;exports.i=E;exports.j=b;
70
+ ${i}`;}return {enhancedSystemPrompt:s,enhancedUserPrompt:c}}var v={type:"object",properties:{attachmentId:{type:"string"},reasoning:{type:"string",description:"The logic connecting the form section requirements to the supporting source citation (think first!)"},fullPhrase:{type:"string",description:"The verbatim text of the terse phrase inside <attachment_text /> to support the citation (if there is a detected OCR correction, use the corrected text)"},keySpan:{type:"string",description:"The verbatim 1-3 words within fullPhrase that best support the citation"},startPageKey:{type:"string",description:'Only return a result like "page_number_PAGE_index_INDEX" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.'},lineIds:{type:"array",items:{type:"number"},description:"Infer lineIds, as we only provide the first, last, and every 5th line. Provide inclusive lineIds for the fullPhrase."}},required:["attachmentId","reasoning","fullPhrase","keySpan","startPageKey","lineIds"]},O={type:"object",properties:{attachmentId:{type:"string"},startPageKey:{type:"string",description:'Only return a result like "page_number_PAGE_index_INDEX" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.'},fullPhrase:{type:"string",description:"The exact verbatim text of the phrase or paragraph from the source document to support the citation (if there is a detected OCR correction, use the verbatim corrected text)"},keySpan:{type:"string",description:"The verbatim 1-3 words within fullPhrase that best support the citation"},timestamps:{type:"object",properties:{startTime:{type:"string"},endTime:{type:"string"}},required:["startTime","endTime"],description:"The timestamp of the audio or video frame including milliseconds formatted as: HH:MM:SS.SSS"}},required:["attachmentId","startPageKey","fullPhrase","keySpan","timestamps"]};var u=4,P=3,I=5;function S(t,n){let i={};for(let e of t){for(let r=u;r<=e.length;r++){let s=e.slice(0,r),c=(s.match(/\d/g)||[]).length,o=(s.match(/[a-zA-Z]/g)||[]).length;if(s.length<u||c>0&&o<P||c===0&&o<I||t.some(m=>m!==e&&m.startsWith(s)))continue;let p=m=>m.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),a=(n.match(new RegExp(p(s),"g"))||[]).length,l=(n.match(new RegExp(p(e),"g"))||[]).length;if(a===l){i[s]=e;break}}if(!Object.values(i).includes(e))throw new Error(`Cannot find a safe unique prefix for ID "${e}" that meets the minimum requirements (length: ${u})`)}return i}function w(t,n){if(!n||n.length===0)return {compressed:t,prefixMap:{}};let i=Array.from(new Set(n)),e=JSON.stringify(t),r=S(i,e),s=Object.keys(r).sort((o,p)=>p.length-o.length),c=e;for(let o of s){let a=r[o].replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");c=c.replace(new RegExp(a,"g"),o);}return {compressed:JSON.parse(c),prefixMap:r}}function A(t,n){if(!n||Object.keys(n).length===0)return t;let i=Object.entries(n).sort((a,l)=>l[0].length-a[0].length),e,r=false;typeof t=="string"?e=t:(e=JSON.stringify(t),r=true);let s=e?.length;for(let[a,l]of i){let m=a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");e=e.replace(new RegExp(m,"g"),l);}let c=["attachmentId","attachment_id","attachment_ID","attachmentID","fileId","file_id","file_ID","fileID","fileid"];for(let[a,l]of i){let m=a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),h=c.join("|"),f="([\"'`])",g=new RegExp(`(${h})(\\s*=\\s*)${f}${m}\\3`,"g");e=e.replace(g,`$1$2$3${l}$3`);}let o=e?.length,p=s-o;if(p>0)throw new Error(`[decompressedPromptIds] diff ${p} originalLength ${s} newLength ${o}`);return r?JSON.parse(e):e}exports.a=_;exports.b=y;exports.c=d;exports.d=T;exports.e=x;exports.f=R;exports.g=v;exports.h=O;exports.i=w;exports.j=A;
@@ -1,2 +1,2 @@
1
- 'use strict';var chunk6VPT3IIK_cjs=require('./chunk-6VPT3IIK.cjs'),chunkF2MMVEVC_cjs=require('./chunk-F2MMVEVC.cjs');var C="https://api.deepcitation.com";function F(p,t){if(typeof Buffer<"u"&&Buffer.isBuffer(p)){let e=Uint8Array.from(p);return {blob:new Blob([e]),name:t||"document"}}if(p instanceof Blob)return {blob:p,name:t||(p instanceof File?p.name:"document")};throw new Error("Invalid file type. Expected File, Blob, or Buffer.")}async function c(p,t){return (await p.json().catch(()=>({})))?.error?.message||`${t} failed with status ${p.status}`}var y=class{constructor(t){chunkF2MMVEVC_cjs.a(this,"apiKey");chunkF2MMVEVC_cjs.a(this,"apiUrl");if(!t.apiKey)throw new Error("DeepCitation API key is required. Get one at https://deepcitation.com/dashboard");this.apiKey=t.apiKey,this.apiUrl=t.apiUrl?.replace(/\/$/,"")||C;}async uploadFile(t,e){let{blob:l,name:a}=F(t,e?.filename),o=new FormData;o.append("file",l,a),e?.attachmentId&&o.append("attachmentId",e.attachmentId),e?.filename&&o.append("filename",e.filename);let i=await fetch(`${this.apiUrl}/prepareFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:o});if(!i.ok)throw new Error(await c(i,"Upload"));return await i.json()}async convertToPdf(t){let e=typeof t=="string"?{url:t}:t,{url:l,file:a,filename:o,attachmentId:i}=e;if(!l&&!a)throw new Error("Either url or file must be provided");let r;if(l)r=await fetch(`${this.apiUrl}/convertFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({url:l,filename:o,attachmentId:i})});else {let{blob:f,name:n}=F(a,o),s=new FormData;s.append("file",f,n),i&&s.append("attachmentId",i),o&&s.append("filename",o),r=await fetch(`${this.apiUrl}/convertFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s});}if(!r.ok)throw new Error(await c(r,"Conversion"));return await r.json()}async prepareConvertedFile(t){let e=await fetch(`${this.apiUrl}/prepareFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({attachmentId:t.attachmentId})});if(!e.ok)throw new Error(await c(e,"Prepare"));return await e.json()}async prepareFiles(t){if(t.length===0)return {fileDataParts:[],deepTextPromptPortion:[]};let e=t.map(({file:i,filename:r,attachmentId:f})=>this.uploadFile(i,{filename:r,attachmentId:f}).then(n=>({result:n,filename:r}))),a=(await Promise.all(e)).map(({result:i,filename:r})=>({attachmentId:i.attachmentId,deepTextPromptPortion:i.deepTextPromptPortion,filename:r||i.metadata?.filename})),o=a.map(i=>i.deepTextPromptPortion);return {fileDataParts:a,deepTextPromptPortion:o}}async verify(t,e,l){let a={};if(Array.isArray(e))for(let n of e){let s=chunk6VPT3IIK_cjs.j(n);a[s]=n;}else if(typeof e=="object"&&e!==null)if("fullPhrase"in e||"value"in e){let n=chunk6VPT3IIK_cjs.j(e);a[n]=e;}else Object.assign(a,e);else throw new Error("Invalid citations format");if(Object.keys(a).length===0)return {verifications:{}};let o=`${this.apiUrl}/verifyCitations`,i={data:{attachmentId:t,citations:a,outputImageFormat:l?.outputImageFormat||"avif"}},r=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(i)});if(!r.ok)throw new Error(await c(r,"Verification"));return await r.json()}async verifyAll(t,e){let{llmOutput:l,outputImageFormat:a="avif"}=t;if(e||(e=chunk6VPT3IIK_cjs.u(l)),Object.keys(e).length===0)return {verifications:{}};let o=new Map;for(let[n,s]of Object.entries(e)){let m=s.attachmentId||"";o.has(m)||o.set(m,{}),o.get(m)[n]=s;}let i=[];for(let[n,s]of o)n&&i.push(this.verify(n,s,{outputImageFormat:a}));let r=await Promise.all(i),f={};for(let n of r)Object.assign(f,n.verifications);return {verifications:f}}};
2
- exports.a=y;
1
+ 'use strict';var chunkSPCFZGGU_cjs=require('./chunk-SPCFZGGU.cjs'),chunkF2MMVEVC_cjs=require('./chunk-F2MMVEVC.cjs');var C="https://api.deepcitation.com";function F(p,t){if(typeof Buffer<"u"&&Buffer.isBuffer(p)){let e=Uint8Array.from(p);return {blob:new Blob([e]),name:t||"document"}}if(p instanceof Blob)return {blob:p,name:t||(p instanceof File?p.name:"document")};throw new Error("Invalid file type. Expected File, Blob, or Buffer.")}async function c(p,t){return (await p.json().catch(()=>({})))?.error?.message||`${t} failed with status ${p.status}`}var h=class{constructor(t){chunkF2MMVEVC_cjs.a(this,"apiKey");chunkF2MMVEVC_cjs.a(this,"apiUrl");if(!t.apiKey)throw new Error("DeepCitation API key is required. Get one at https://deepcitation.com/dashboard");this.apiKey=t.apiKey,this.apiUrl=t.apiUrl?.replace(/\/$/,"")||C;}async uploadFile(t,e){let{blob:l,name:a}=F(t,e?.filename),o=new FormData;o.append("file",l,a),e?.attachmentId&&o.append("attachmentId",e.attachmentId),e?.filename&&o.append("filename",e.filename);let i=await fetch(`${this.apiUrl}/prepareFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:o});if(!i.ok)throw new Error(await c(i,"Upload"));return await i.json()}async convertToPdf(t){let e=typeof t=="string"?{url:t}:t,{url:l,file:a,filename:o,attachmentId:i}=e;if(!l&&!a)throw new Error("Either url or file must be provided");let r;if(l)r=await fetch(`${this.apiUrl}/convertFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({url:l,filename:o,attachmentId:i})});else {let{blob:f,name:n}=F(a,o),s=new FormData;s.append("file",f,n),i&&s.append("attachmentId",i),o&&s.append("filename",o),r=await fetch(`${this.apiUrl}/convertFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s});}if(!r.ok)throw new Error(await c(r,"Conversion"));return await r.json()}async prepareConvertedFile(t){let e=await fetch(`${this.apiUrl}/prepareFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({attachmentId:t.attachmentId})});if(!e.ok)throw new Error(await c(e,"Prepare"));return await e.json()}async prepareFiles(t){if(t.length===0)return {fileDataParts:[],deepTextPromptPortion:[]};let e=t.map(({file:i,filename:r,attachmentId:f})=>this.uploadFile(i,{filename:r,attachmentId:f}).then(n=>({result:n,filename:r}))),a=(await Promise.all(e)).map(({result:i,filename:r})=>({attachmentId:i.attachmentId,deepTextPromptPortion:i.deepTextPromptPortion,filename:r||i.metadata?.filename})),o=a.map(i=>i.deepTextPromptPortion);return {fileDataParts:a,deepTextPromptPortion:o}}async verifyAttachment(t,e,l){let a={};if(Array.isArray(e))for(let n of e){let s=chunkSPCFZGGU_cjs.j(n);a[s]=n;}else if(typeof e=="object"&&e!==null)if("fullPhrase"in e||"value"in e){let n=chunkSPCFZGGU_cjs.j(e);a[n]=e;}else Object.assign(a,e);else throw new Error("Invalid citations format");if(Object.keys(a).length===0)return {verifications:{}};let o=`${this.apiUrl}/verifyCitations`,i={data:{attachmentId:t,citations:a,outputImageFormat:l?.outputImageFormat||"avif"}},r=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(i)});if(!r.ok)throw new Error(await c(r,"Verification"));return await r.json()}async verify(t,e){let{llmOutput:l,outputImageFormat:a="avif"}=t;if(e||(e=chunkSPCFZGGU_cjs.u(l)),Object.keys(e).length===0)return {verifications:{}};let o=new Map;for(let[n,s]of Object.entries(e)){let m=s.attachmentId||"";o.has(m)||o.set(m,{}),o.get(m)[n]=s;}let i=[];for(let[n,s]of o)n&&i.push(this.verifyAttachment(n,s,{outputImageFormat:a}));let r=await Promise.all(i),f={};for(let n of r)Object.assign(f,n.verifications);return {verifications:f}}};
2
+ exports.a=h;
@@ -4,14 +4,14 @@ var _=`
4
4
 
5
5
  For every claim, value, or fact; you MUST cite sources using this exact syntax:
6
6
 
7
- <cite attachment_id='ID' reasoning='why this supports the claim' key_span='1-3 key words' full_phrase='verbatim quote' start_page_key='page_number_N_index_I' line_ids='X-Y' />
7
+ <cite attachment_id='ID' reasoning='why this supports the claim' full_phrase='verbatim quote' key_span='1-3 key words' start_page_key='page_number_N_index_I' line_ids='X-Y' />
8
8
 
9
9
  ### Syntax Rules (MUST follow)
10
10
 
11
11
  1. **attachment_id**: Use the exact ID from the source document
12
12
  2. **reasoning**: Brief explanation of why this citation supports your claim (think first!)
13
- 3. **key_span**: The 1-3 most important words or value from full_phrase
14
- 4. **full_phrase**: Copy text VERBATIM from source. Escape quotes (\\') and newlines (\\n).
13
+ 3. **full_phrase**: Copy text VERBATIM from source. Escape quotes (\\') and newlines (\\n).
14
+ 4. **key_span**: The 1-3 most important words or value from full_phrase
15
15
  5. **start_page_key**: ONLY use format \`page_number_N_index_I\` from page tags (e.g., \`<page_number_1_index_0>\`). Never extract page numbers from document content.
16
16
  6. **line_ids**: Inclusive range (e.g., '2-6' or '4'). Infer intermediate lines since only every 5th line is shown.
17
17
 
@@ -24,11 +24,11 @@ For every claim, value, or fact; you MUST cite sources using this exact syntax:
24
24
 
25
25
  ### Example Citation 1
26
26
 
27
- The company reported strong growth<cite attachment_id='abc123' reasoning='directly states revenue growth percentage' key_span='increased 45%' full_phrase='Revenue increased 45% year-over-year to $2.3 billion' start_page_key='page_number_2_index_1' line_ids='12-14' />
27
+ The company reported strong growth<cite attachment_id='abc123' reasoning='directly states revenue growth percentage' full_phrase='Revenue increased 45% year-over-year to $2.3 billion' key_span='increased 45%' start_page_key='page_number_2_index_1' line_ids='12-14' />
28
28
 
29
29
  ### Example Citation 2
30
30
 
31
- The total amount is $500 USD <cite attachment_id='abc123' reasoning='directly states the total amount' key_span='$500 USD' full_phrase='The total amount is $500 USD' start_page_key='page_number_2_index_1' line_ids='12-14' />
31
+ The total amount is $500 USD <cite attachment_id='abc123' reasoning='directly states the total amount' full_phrase='The total amount is $500 USD' key_span='$500 USD' start_page_key='page_number_2_index_1' line_ids='12-14' />
32
32
 
33
33
  </citation-instructions>
34
34
  `,y=`
@@ -37,14 +37,14 @@ The total amount is $500 USD <cite attachment_id='abc123' reasoning='directly st
37
37
 
38
38
  For every claim, value, or fact; you MUST cite sources using this exact syntax:
39
39
 
40
- <cite attachment_id='ID' reasoning='why this supports the claim' key_span='1-3 key words' full_phrase='verbatim transcript quote' timestamps='HH:MM:SS.SSS-HH:MM:SS.SSS' />
40
+ <cite attachment_id='ID' reasoning='why this supports the claim' full_phrase='verbatim transcript quote' key_span='1-3 key words' timestamps='HH:MM:SS.SSS-HH:MM:SS.SSS' />
41
41
 
42
42
  ### Syntax Rules (MUST follow)
43
43
 
44
44
  1. **attachment_id**: Use the exact ID from the source
45
45
  2. **reasoning**: Brief explanation of why this citation supports your claim (think first!)
46
- 3. **key_span**: The 1-3 most important words or value from full_phrase
47
- 4. **full_phrase**: Copy transcript text VERBATIM. Escape quotes (\\') and newlines (\\n).
46
+ 3. **full_phrase**: Copy transcript text VERBATIM. Escape quotes (\\') and newlines (\\n).
47
+ 4. **key_span**: The 1-3 most important words or value from full_phrase
48
48
  5. **timestamps**: Start and end time with milliseconds (e.g., '00:01:23.456-00:01:45.789')
49
49
 
50
50
  ### Placement Rules
@@ -67,4 +67,4 @@ ${a}`).join(`
67
67
 
68
68
  ${d}
69
69
 
70
- ${i}`;}return {enhancedSystemPrompt:s,enhancedUserPrompt:c}}var O={type:"object",properties:{attachmentId:{type:"string"},reasoning:{type:"string",description:"The logic connecting the form section requirements to the supporting source citation (think first!)"},keySpan:{type:"string",description:"The verbatim 1-3 words within fullPhrase that best support the citation"},fullPhrase:{type:"string",description:"The verbatim text of the terse phrase inside <attachment_text /> to support the citation (if there is a detected OCR correction, use the corrected text)"},startPageKey:{type:"string",description:'Only return a result like "page_number_PAGE_index_INDEX" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.'},lineIds:{type:"array",items:{type:"number"},description:"Infer lineIds, as we only provide the first, last, and every 5th line. Provide inclusive lineIds for the fullPhrase."}},required:["attachmentId","reasoning","keySpan","fullPhrase","startPageKey","lineIds"]},v={type:"object",properties:{attachmentId:{type:"string"},startPageKey:{type:"string",description:'Only return a result like "page_number_PAGE_index_INDEX" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.'},fullPhrase:{type:"string",description:"The exact verbatim text of the phrase or paragraph from the source document to support the citation (if there is a detected OCR correction, use the verbatim corrected text)"},timestamps:{type:"object",properties:{startTime:{type:"string"},endTime:{type:"string"}},required:["startTime","endTime"],description:"The timestamp of the audio or video frame including milliseconds formatted as: HH:MM:SS.SSS"}},required:["attachmentId","startPageKey","fullPhrase","timestamps"]};var u=4,I=3,P=5;function S(t,n){let i={};for(let e of t){for(let r=u;r<=e.length;r++){let s=e.slice(0,r),c=(s.match(/\d/g)||[]).length,o=(s.match(/[a-zA-Z]/g)||[]).length;if(s.length<u||c>0&&o<I||c===0&&o<P||t.some(m=>m!==e&&m.startsWith(s)))continue;let p=m=>m.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),a=(n.match(new RegExp(p(s),"g"))||[]).length,l=(n.match(new RegExp(p(e),"g"))||[]).length;if(a===l){i[s]=e;break}}if(!Object.values(i).includes(e))throw new Error(`Cannot find a safe unique prefix for ID "${e}" that meets the minimum requirements (length: ${u})`)}return i}function E(t,n){if(!n||n.length===0)return {compressed:t,prefixMap:{}};let i=Array.from(new Set(n)),e=JSON.stringify(t),r=S(i,e),s=Object.keys(r).sort((o,p)=>p.length-o.length),c=e;for(let o of s){let a=r[o].replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");c=c.replace(new RegExp(a,"g"),o);}return {compressed:JSON.parse(c),prefixMap:r}}function b(t,n){if(!n||Object.keys(n).length===0)return t;let i=Object.entries(n).sort((a,l)=>l[0].length-a[0].length),e,r=false;typeof t=="string"?e=t:(e=JSON.stringify(t),r=true);let s=e?.length;for(let[a,l]of i){let m=a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");e=e.replace(new RegExp(m,"g"),l);}let c=["attachmentId","attachment_id","attachment_ID","attachmentID","fileId","file_id","file_ID","fileID","fileid"];for(let[a,l]of i){let m=a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),h=c.join("|"),f="([\"'`])",g=new RegExp(`(${h})(\\s*=\\s*)${f}${m}\\3`,"g");e=e.replace(g,`$1$2$3${l}$3`);}let o=e?.length,p=s-o;if(p>0)throw new Error(`[decompressedPromptIds] diff ${p} originalLength ${s} newLength ${o}`);return r?JSON.parse(e):e}export{_ as a,y as b,d as c,T as d,x as e,R as f,O as g,v as h,E as i,b as j};
70
+ ${i}`;}return {enhancedSystemPrompt:s,enhancedUserPrompt:c}}var v={type:"object",properties:{attachmentId:{type:"string"},reasoning:{type:"string",description:"The logic connecting the form section requirements to the supporting source citation (think first!)"},fullPhrase:{type:"string",description:"The verbatim text of the terse phrase inside <attachment_text /> to support the citation (if there is a detected OCR correction, use the corrected text)"},keySpan:{type:"string",description:"The verbatim 1-3 words within fullPhrase that best support the citation"},startPageKey:{type:"string",description:'Only return a result like "page_number_PAGE_index_INDEX" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.'},lineIds:{type:"array",items:{type:"number"},description:"Infer lineIds, as we only provide the first, last, and every 5th line. Provide inclusive lineIds for the fullPhrase."}},required:["attachmentId","reasoning","fullPhrase","keySpan","startPageKey","lineIds"]},O={type:"object",properties:{attachmentId:{type:"string"},startPageKey:{type:"string",description:'Only return a result like "page_number_PAGE_index_INDEX" from the provided page keys (e.g. <page_number_1_index_0>) and never from the contents inside the page.'},fullPhrase:{type:"string",description:"The exact verbatim text of the phrase or paragraph from the source document to support the citation (if there is a detected OCR correction, use the verbatim corrected text)"},keySpan:{type:"string",description:"The verbatim 1-3 words within fullPhrase that best support the citation"},timestamps:{type:"object",properties:{startTime:{type:"string"},endTime:{type:"string"}},required:["startTime","endTime"],description:"The timestamp of the audio or video frame including milliseconds formatted as: HH:MM:SS.SSS"}},required:["attachmentId","startPageKey","fullPhrase","keySpan","timestamps"]};var u=4,P=3,I=5;function S(t,n){let i={};for(let e of t){for(let r=u;r<=e.length;r++){let s=e.slice(0,r),c=(s.match(/\d/g)||[]).length,o=(s.match(/[a-zA-Z]/g)||[]).length;if(s.length<u||c>0&&o<P||c===0&&o<I||t.some(m=>m!==e&&m.startsWith(s)))continue;let p=m=>m.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),a=(n.match(new RegExp(p(s),"g"))||[]).length,l=(n.match(new RegExp(p(e),"g"))||[]).length;if(a===l){i[s]=e;break}}if(!Object.values(i).includes(e))throw new Error(`Cannot find a safe unique prefix for ID "${e}" that meets the minimum requirements (length: ${u})`)}return i}function w(t,n){if(!n||n.length===0)return {compressed:t,prefixMap:{}};let i=Array.from(new Set(n)),e=JSON.stringify(t),r=S(i,e),s=Object.keys(r).sort((o,p)=>p.length-o.length),c=e;for(let o of s){let a=r[o].replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");c=c.replace(new RegExp(a,"g"),o);}return {compressed:JSON.parse(c),prefixMap:r}}function A(t,n){if(!n||Object.keys(n).length===0)return t;let i=Object.entries(n).sort((a,l)=>l[0].length-a[0].length),e,r=false;typeof t=="string"?e=t:(e=JSON.stringify(t),r=true);let s=e?.length;for(let[a,l]of i){let m=a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");e=e.replace(new RegExp(m,"g"),l);}let c=["attachmentId","attachment_id","attachment_ID","attachmentID","fileId","file_id","file_ID","fileID","fileid"];for(let[a,l]of i){let m=a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),h=c.join("|"),f="([\"'`])",g=new RegExp(`(${h})(\\s*=\\s*)${f}${m}\\3`,"g");e=e.replace(g,`$1$2$3${l}$3`);}let o=e?.length,p=s-o;if(p>0)throw new Error(`[decompressedPromptIds] diff ${p} originalLength ${s} newLength ${o}`);return r?JSON.parse(e):e}export{_ as a,y as b,d as c,T as d,x as e,R as f,v as g,O as h,w as i,A as j};
@@ -1 +1 @@
1
- 'use strict';function E(t){return new TextEncoder().encode(t)}function Z(t){let e=1732584193,i=4023233417,r=2562383102,n=271733878,o=3285377520,p=t.length,a=p*8,c=p+1+8,l=Math.ceil(c/64)*64,s=new ArrayBuffer(l),C=new Uint8Array(s),d=new DataView(s);C.set(t),C[p]=128,d.setUint32(l-8,Math.floor(a/4294967296),false),d.setUint32(l-4,a>>>0,false);let u=new Uint32Array(80);for(let x=0;x<l;x+=64){for(let g=0;g<16;g++)u[g]=d.getUint32(x+g*4,false);for(let g=16;g<80;g++){let I=u[g-3]^u[g-8]^u[g-14]^u[g-16];u[g]=I<<1|I>>>31;}let f=e,h=i,_=r,k=n,S=o;for(let g=0;g<80;g++){let I,m;g<20?(I=h&_|~h&k,m=1518500249):g<40?(I=h^_^k,m=1859775393):g<60?(I=h&_|h&k|_&k,m=2400959708):(I=h^_^k,m=3395469782);let b=(f<<5|f>>>27)+I+S+m+u[g]>>>0;S=k,k=_,_=(h<<30|h>>>2)>>>0,h=f,f=b;}e=e+f>>>0,i=i+h>>>0,r=r+_>>>0,n=n+k>>>0,o=o+S>>>0;}let y=x=>x.toString(16).padStart(8,"0");return y(e)+y(i)+y(r)+y(n)+y(o)}function P(t){try{if(!t)return "";let e=typeof t=="string"?t:JSON.stringify(t);return Z(E(e))}catch(e){console.error("Error in making the hash:",e);}return ""}function Y(...t){return t.filter(Boolean).join(" ")}function U(t){return t.type==="url"||typeof t.url=="string"&&t.url.length>0}function A(t){let e=t.pageNumber||v(t.startPageKey),i=[t.attachmentId||"",e?.toString()||"",t.fullPhrase||"",t.keySpan?.toString()||"",t.lineIds?.join(",")||"",t.timestamps?.startTime||"",t.timestamps?.endTime||""];return U(t)&&i.push(t.url||"",t.title||"",t.domain||""),P(i.join("|")).slice(0,16)}function j(t){let e=[t.attachmentId||"",t.label||"",t.verifiedFullPhrase||"",t.verifiedKeySpan||"",t.verifiedLineIds?.join(",")||"",t.verifiedPageNumber?.toString()||"",t.verifiedTimestamps?.startTime||"",t.verifiedTimestamps?.endTime||"",t.verifiedMatchSnippet||"",t.hitIndexWithinPage?.toString()||""];return P(e.join("|")).slice(0,16)}function Q(t){let e=Math.random().toString(36).slice(2,11);return `${t}-${e}`}function tt(t,e={}){let{fallbackDisplay:i}=e;return t.keySpan?.toString()||t.citationNumber?.toString()||i||"1"}function et(t){return t.citationNumber?.toString()||"1"}function nt(t){return t.keySpan?.toString()||""}function it(...t){return t.filter(Boolean).join(" ")}var rt=4,st=1;function D(t){if(!t)return;let e=[],i=t.split(",");for(let r of i){let n=r.trim();if(n)if(n.includes("-")){let[o,p]=n.split("-"),a=parseInt(o,10),c=parseInt(p,10);if(!isNaN(a)&&!isNaN(c)&&a<=c)for(let l=a;l<=c;l++)e.push(l);else isNaN(a)||e.push(a);}else {let o=parseInt(n,10);isNaN(o)||e.push(o);}}if(e.length!==0)return [...new Set(e)].sort((r,n)=>r-n)}function R(t){let e=t?.status,i=e==="not_found",r=e==="found_phrase_missed_value",n=e==="found_key_span_only",o=e==="partial_text_found"||e==="found_on_other_page"||e==="found_on_other_line"||e==="first_word_found";return {isVerified:e==="found"||n||o||r,isMiss:i,isPartialMatch:o,isPending:e==="pending"||e==="loading"||!e}}var B=(t,e,i,r)=>{let n=m=>m?m.replace(/^['"]|['"]$/g,"").replace(/\\'/g,"'"):void 0,o=i?.current?i.current++:void 0,p=t.substring(0,t.indexOf("<cite")),a=t.includes("/>")?t.slice(t.indexOf("/>")+2):"",c=t.substring(t.indexOf("<cite"),t.indexOf("/>")+2),l=(m,b)=>{for(let O of b){let L=new RegExp(`${O}='((?:[^'\\\\]|\\\\.)*)'`),K=m.match(L);if(K)return K[1]}},s=l(c,["attachment_id","attachmentId","file_id","fileId"]),C=s?.length===20?s:e||s,d=l(c,["start_page_key","startPageKey","start_page"]),u,y;if(d){let m=d.match(/page[\_a-zA-Z]*(\d+)_index_(\d+)/);m&&(u=parseInt(m[1]),y=parseInt(m[2]));}let x=n(l(c,["full_phrase","fullPhrase"])),f=n(l(c,["key_span","keySpan"])),h=n(l(c,["reasoning"])),_=n(l(c,["value"])),k;try{let b=l(c,["line_ids","lineIds"])?.replace(/[A-Za-z_[\](){}:]/g,"");k=b?D(b):void 0;}catch(m){r&&console.error("Error parsing lineIds",m);}let S=l(c,["timestamps"]),g;if(S){let[m,b]=S.split("-")||[];g={startTime:m,endTime:b};}let I={attachmentId:C,pageNumber:u,startPageKey:`page_number_${u||1}_index_${y||0}`,fullPhrase:x,keySpan:f||_,citationNumber:o,lineIds:k,beforeCite:p,timestamps:g,reasoning:h};return {beforeCite:p,afterCite:a,citation:I}},J=(t,e)=>{if(!t)return null;let i=t.fullPhrase??t.full_phrase,r=t.startPageKey??t.start_page_key,n=t.keySpan??t.key_span,o=t.lineIds??t.line_ids,p=t.attachmentId??t.attachment_id??t.fileId??t.file_id,a=t.reasoning,c=t.value;if(!i)return null;let l;if(r){let d=r.match(/page[_a-zA-Z]*(\d+)_index_(\d+)/i);if(d)l=parseInt(d[1],10);else {let u=r.match(/^(\d+)_(\d+)$/);u&&(l=parseInt(u[1],10));}}let s=o?.length?[...o].sort((d,u)=>d-u):void 0;return {attachmentId:p,pageNumber:l,fullPhrase:i,citationNumber:e,lineIds:s,keySpan:n||c,reasoning:a}},V=t=>typeof t=="object"&&t!==null&&("fullPhrase"in t||"full_phrase"in t||"startPageKey"in t||"start_page_key"in t||"keySpan"in t||"key_span"in t||"lineIds"in t||"line_ids"in t),N=t=>Array.isArray(t)?t.length>0&&t.some(V):typeof t=="object"&&t!==null?V(t):false,M=t=>{let e={},i=Array.isArray(t)?t:[t],r=1;for(let n of i){let o=J(n,r++);if(o&&o.fullPhrase){let p=A(o);e[p]=o;}}return e},w=(t,e)=>{if(!(!t||typeof t!="object")){if(t.citation&&N(t.citation)){let i=Array.isArray(t.citation)?t.citation:[t.citation];e.push(...i);}if(t.citations&&N(t.citations)){let i=Array.isArray(t.citations)?t.citations:[t.citations];e.push(...i);}if(Array.isArray(t))for(let i of t)w(i,e);else for(let i of Object.keys(t))i!=="citation"&&i!=="citations"&&w(t[i],e);}},T=t=>{let e=$(t),i=/<cite\s+[^>]*\/>/g,r=e.match(i);if(!r||r.length===0)return {};let n={},o={current:1};for(let p of r){let{citation:a}=B(p,void 0,o);if(a&&a.fullPhrase){let c=A(a);n[c]=a;}}return n},lt=t=>{if(!t)return {};let e={};if(typeof t=="object"){if(N(t)){let n=M(t);Object.assign(e,n);}else {let n=[];if(w(t,n),n.length>0){let o=M(n);Object.assign(e,o);}}let i=JSON.stringify(t),r=T(i);Object.assign(e,r);}else if(typeof t=="string"){let i=T(t);Object.assign(e,i);}return e};function ut(t){let e=new Map,i=Array.isArray(t)?t.map((r,n)=>[A(r)||String(n+1),r]):Object.entries(t);for(let[r,n]of i){let o=n.attachmentId||"";e.has(o)||e.set(o,{}),e.get(o)[r]=n;}return e}function pt(t){let e={},i=Array.isArray(t)?t.map((r,n)=>[A(r)||String(n+1),r]):Object.entries(t);for(let[r,n]of i){let o=n.attachmentId||"";e[o]||(e[o]={}),e[o][r]=n;}return e}var F=t=>{let e={},i=/([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(['"])((?:[^'"\\]|\\.)*)\2/g,r;for(;(r=i.exec(t))!==null;){let n=r[1].toLowerCase().replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase(),o=r[3],p=n==="fileid"||n==="file_id"||n==="attachmentid"?"attachment_id":n==="keyspan"?"key_span":n==="fullphrase"?"full_phrase":n==="lineids"?"line_ids":n==="startpagekey"||n==="start_pagekey"?"start_page_key":n;e[p]=o;}return e},W=t=>{if(!t)return "\u25CC";let e=R(t);return e.isPending?"\u25CC":e.isMiss?"\u2717":e.isPartialMatch?"\u26A0":e.isVerified?"\u2713":"\u25CC"},H=(t,e={})=>{let{leaveKeySpanBehind:i=false,verifications:r,showVerificationStatus:n=false}=e,o=0,p=/<cite\s+[^>]*?\/>/g;return t.replace(p,a=>{o++;let c=F(a),l="";if(i&&c.key_span&&(l=c.key_span.replace(/\\'/g,"'").replace(/\\"/g,'"')),n&&r){let s,C=String(o);if(s=r[C],!s&&c.attachment_id){for(let[,u]of Object.entries(r))if(u.attachmentId===c.attachment_id){s=u;break}}let d=W(s);l=l?`${l}${d}`:d;}return l})},dt=(t,e)=>H(t,{leaveKeySpanBehind:e}),mt=t=>t.replace(/<page_number_\d+_index_\d+>/g,"").replace(/<\/page_number_\d+_index_\d+>/g,"").trim(),ht=t=>{let e=/<line id="[^"]*">|<\/line>/g;return t.replace(e,"")},v=t=>{if(!t)return null;let e=t.match(/\d+/)?.[0];return e?parseInt(e):null},$=t=>{let e=t?.trim()||"",i=e.split(/(<cite[\s\S]*?(?:\/>|<\/cite>))/gm);return i.length<=1?z(e):(e=i.map(r=>r.startsWith("<cite")?z(r):r).join(""),e)},z=t=>{let e=t;e=e.replace(/><\/cite>/g,"/>");let i=p=>{let a=p.toLowerCase();return a==="fullphrase"||a==="full_phrase"?"full_phrase":a==="lineids"||a==="line_ids"?"line_ids":a==="startpagekey"||a==="start_pagekey"||a==="start_page_key"?"start_page_key":a==="fileid"||a==="file_id"||a==="attachmentid"||a==="attachment_id"?"attachment_id":a==="keyspan"||a==="key_span"?"key_span":a==="reasoning"||a==="value"?a:a==="timestamps"||a==="timestamp"||a==="timestamps"?"timestamps":a},r=p=>p.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),n=/(fullPhrase|full_phrase|keySpan|key_span|reasoning|value)\s*=\s*(['"])([\s\S]*?)(?=\s+(?:line_ids|lineIds|timestamps|fileId|file_id|attachmentId|attachment_id|start_page_key|start_pageKey|startPageKey|keySpan|key_span|reasoning|value|full_phrase)|\s*\/?>)/gm;e=e.replace(n,(p,a,c,l)=>{let s=l;return s.endsWith(c)&&(s=s.slice(0,-1)),s=s.replace(/(\r?\n)+/g," "),s=r(s),s=s.replace(/(\*|_){2,}/g,""),s=s.replace(/\\\\'/g,"'"),s=s.replace(/\\'/g,"'"),s=s.replace(/'/g,"\\'"),s=s.replace(/\\\\"/g,'"'),s=s.replace(/\\"/g,'"'),s=s.replace(/"/g,'\\"'),s=s.replace(/\*/g,""),`${i(a)}='${s}'`}),e=e.replace(/(line_ids|lineIds|timestamps)=['"]?([\[\]\(\){}A-Za-z0-9_\-, ]+)['"]?(\s*\/?>|\s+)/gm,(p,a,c,l)=>{let s=c.replace(/[A-Za-z\[\]\(\){}]/g,"");return s=s.replace(/(\d+)-(\d+)/g,(C,d,u)=>{let y=parseInt(d,10),x=parseInt(u,10),f=[];if(y<=x)for(let h=y;h<=x;h++)f.push(h);else f.push(y);return f.join(",")}),s=s.replace(/,+/g,",").replace(/^,|,$/g,""),`${i(a)}='${s}'${l}`});let o=p=>{let a=/([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(['"])((?:[^'"\\\n]|\\.)*)(?:\2)/g,c={},l;for(;l=a.exec(p);){let f=l[1],h=l[3],_=i(f);c[_]=h;}let s=Object.keys(c);if(s.length===0)return p;let C=typeof c.timestamps=="string"&&c.timestamps.length>0,d=s.filter(f=>f.startsWith("start_page")),u=[];c.attachment_id&&u.push("attachment_id"),C?(c.full_phrase&&u.push("full_phrase"),u.push("timestamps")):(d.includes("start_page_key")&&u.push("start_page_key"),d.filter(f=>f!=="start_page_key").sort().forEach(f=>u.push(f)),c.full_phrase&&u.push("full_phrase"),c.key_span&&u.push("key_span"),c.line_ids&&u.push("line_ids")),c.reasoning&&u.push("reasoning"),c.value&&u.push("value");let y=new Set(u);return s.filter(f=>!y.has(f)).sort().forEach(f=>u.push(f)),`<cite ${u.map(f=>`${f}='${c[f]}'`).join(" ")} />`};return e=e.replace(/<cite\b[\s\S]*?\/>/gm,p=>o(p)),e};exports.a=H;exports.b=dt;exports.c=mt;exports.d=ht;exports.e=v;exports.f=$;exports.g=P;exports.h=Y;exports.i=U;exports.j=A;exports.k=j;exports.l=Q;exports.m=tt;exports.n=et;exports.o=nt;exports.p=it;exports.q=rt;exports.r=st;exports.s=R;exports.t=B;exports.u=lt;exports.v=ut;exports.w=pt;
1
+ 'use strict';function E(t){return new TextEncoder().encode(t)}function Z(t){let e=1732584193,i=4023233417,r=2562383102,n=271733878,o=3285377520,p=t.length,a=p*8,c=p+1+8,u=Math.ceil(c/64)*64,s=new ArrayBuffer(u),C=new Uint8Array(s),d=new DataView(s);C.set(t),C[p]=128,d.setUint32(u-8,Math.floor(a/4294967296),false),d.setUint32(u-4,a>>>0,false);let l=new Uint32Array(80);for(let x=0;x<u;x+=64){for(let g=0;g<16;g++)l[g]=d.getUint32(x+g*4,false);for(let g=16;g<80;g++){let I=l[g-3]^l[g-8]^l[g-14]^l[g-16];l[g]=I<<1|I>>>31;}let f=e,h=i,_=r,k=n,S=o;for(let g=0;g<80;g++){let I,m;g<20?(I=h&_|~h&k,m=1518500249):g<40?(I=h^_^k,m=1859775393):g<60?(I=h&_|h&k|_&k,m=2400959708):(I=h^_^k,m=3395469782);let b=(f<<5|f>>>27)+I+S+m+l[g]>>>0;S=k,k=_,_=(h<<30|h>>>2)>>>0,h=f,f=b;}e=e+f>>>0,i=i+h>>>0,r=r+_>>>0,n=n+k>>>0,o=o+S>>>0;}let y=x=>x.toString(16).padStart(8,"0");return y(e)+y(i)+y(r)+y(n)+y(o)}function P(t){try{if(!t)return "";let e=typeof t=="string"?t:JSON.stringify(t);return Z(E(e))}catch(e){console.error("Error in making the hash:",e);}return ""}function Y(...t){return t.filter(Boolean).join(" ")}function U(t){return t.type==="url"||typeof t.url=="string"&&t.url.length>0}function A(t){let e=t.pageNumber||v(t.startPageKey),i=[t.attachmentId||"",e?.toString()||"",t.fullPhrase||"",t.keySpan?.toString()||"",t.lineIds?.join(",")||"",t.timestamps?.startTime||"",t.timestamps?.endTime||""];return U(t)&&i.push(t.url||"",t.title||"",t.domain||""),P(i.join("|")).slice(0,16)}function j(t){let e=[t.attachmentId||"",t.label||"",t.verifiedFullPhrase||"",t.verifiedKeySpan||"",t.verifiedLineIds?.join(",")||"",t.verifiedPageNumber?.toString()||"",t.verifiedTimestamps?.startTime||"",t.verifiedTimestamps?.endTime||"",t.verifiedMatchSnippet||"",t.hitIndexWithinPage?.toString()||""];return P(e.join("|")).slice(0,16)}function Q(t){let e=Math.random().toString(36).slice(2,11);return `${t}-${e}`}function tt(t,e={}){let{fallbackDisplay:i}=e;return t.keySpan?.toString()||t.citationNumber?.toString()||i||"1"}function et(t){return t.citationNumber?.toString()||"1"}function nt(t){return t.keySpan?.toString()||""}function it(...t){return t.filter(Boolean).join(" ")}var rt=4,st=1;function D(t){if(!t)return;let e=[],i=t.split(",");for(let r of i){let n=r.trim();if(n)if(n.includes("-")){let[o,p]=n.split("-"),a=parseInt(o,10),c=parseInt(p,10);if(!isNaN(a)&&!isNaN(c)&&a<=c)for(let u=a;u<=c;u++)e.push(u);else isNaN(a)||e.push(a);}else {let o=parseInt(n,10);isNaN(o)||e.push(o);}}if(e.length!==0)return [...new Set(e)].sort((r,n)=>r-n)}function R(t){let e=t?.status,i=e==="not_found",r=e==="found_phrase_missed_value",n=e==="found_key_span_only",o=e==="partial_text_found"||e==="found_on_other_page"||e==="found_on_other_line"||e==="first_word_found";return {isVerified:e==="found"||n||o||r,isMiss:i,isPartialMatch:o,isPending:e==="pending"||e==="loading"||!e}}var B=(t,e,i,r)=>{let n=m=>m?m.replace(/^['"]|['"]$/g,"").replace(/\\'/g,"'"):void 0,o=i?.current?i.current++:void 0,p=t.substring(0,t.indexOf("<cite")),a=t.includes("/>")?t.slice(t.indexOf("/>")+2):"",c=t.substring(t.indexOf("<cite"),t.indexOf("/>")+2),u=(m,b)=>{for(let O of b){let L=new RegExp(`${O}='((?:[^'\\\\]|\\\\.)*)'`),K=m.match(L);if(K)return K[1]}},s=u(c,["attachment_id","attachmentId","file_id","fileId"]),C=s?.length===20?s:e||s,d=u(c,["start_page_key","startPageKey","start_page"]),l,y;if(d){let m=d.match(/page[\_a-zA-Z]*(\d+)_index_(\d+)/);m&&(l=parseInt(m[1]),y=parseInt(m[2]));}let x=n(u(c,["full_phrase","fullPhrase"])),f=n(u(c,["key_span","keySpan"])),h=n(u(c,["reasoning"])),_=n(u(c,["value"])),k;try{let b=u(c,["line_ids","lineIds"])?.replace(/[A-Za-z_[\](){}:]/g,"");k=b?D(b):void 0;}catch(m){r&&console.error("Error parsing lineIds",m);}let S=u(c,["timestamps"]),g;if(S){let[m,b]=S.split("-")||[];g={startTime:m,endTime:b};}let I={attachmentId:C,pageNumber:l,startPageKey:`page_number_${l||1}_index_${y||0}`,fullPhrase:x,keySpan:f||_,citationNumber:o,lineIds:k,beforeCite:p,timestamps:g,reasoning:h};return {beforeCite:p,afterCite:a,citation:I}},J=(t,e)=>{if(!t)return null;let i=t.fullPhrase??t.full_phrase,r=t.startPageKey??t.start_page_key,n=t.keySpan??t.key_span,o=t.lineIds??t.line_ids,p=t.attachmentId??t.attachment_id??t.fileId??t.file_id,a=t.reasoning,c=t.value;if(!i)return null;let u;if(r){let d=r.match(/page[_a-zA-Z]*(\d+)_index_(\d+)/i);if(d)u=parseInt(d[1],10);else {let l=r.match(/^(\d+)_(\d+)$/);l&&(u=parseInt(l[1],10));}}let s=o?.length?[...o].sort((d,l)=>d-l):void 0;return {attachmentId:p,pageNumber:u,fullPhrase:i,citationNumber:e,lineIds:s,keySpan:n||c,reasoning:a}},V=t=>typeof t=="object"&&t!==null&&("fullPhrase"in t||"full_phrase"in t||"startPageKey"in t||"start_page_key"in t||"keySpan"in t||"key_span"in t||"lineIds"in t||"line_ids"in t),N=t=>Array.isArray(t)?t.length>0&&t.some(V):typeof t=="object"&&t!==null?V(t):false,M=t=>{let e={},i=Array.isArray(t)?t:[t],r=1;for(let n of i){let o=J(n,r++);if(o&&o.fullPhrase){let p=A(o);e[p]=o;}}return e},w=(t,e)=>{if(!(!t||typeof t!="object")){if(t.citation&&N(t.citation)){let i=Array.isArray(t.citation)?t.citation:[t.citation];e.push(...i);}if(t.citations&&N(t.citations)){let i=Array.isArray(t.citations)?t.citations:[t.citations];e.push(...i);}if(Array.isArray(t))for(let i of t)w(i,e);else for(let i of Object.keys(t))i!=="citation"&&i!=="citations"&&w(t[i],e);}},T=t=>{let e=$(t),i=/<cite\s+[^>]*\/>/g,r=e.match(i);if(!r||r.length===0)return {};let n={},o={current:1};for(let p of r){let{citation:a}=B(p,void 0,o);if(a&&a.fullPhrase){let c=A(a);n[c]=a;}}return n},lt=t=>{if(!t)return {};let e={};if(typeof t=="object"){if(N(t)){let n=M(t);Object.assign(e,n);}else {let n=[];if(w(t,n),n.length>0){let o=M(n);Object.assign(e,o);}}let i=JSON.stringify(t),r=T(i);Object.assign(e,r);}else if(typeof t=="string"){let i=T(t);Object.assign(e,i);}return e};function ut(t){let e=new Map,i=Array.isArray(t)?t.map((r,n)=>[A(r)||String(n+1),r]):Object.entries(t);for(let[r,n]of i){let o=n.attachmentId||"";e.has(o)||e.set(o,{}),e.get(o)[r]=n;}return e}function pt(t){let e={},i=Array.isArray(t)?t.map((r,n)=>[A(r)||String(n+1),r]):Object.entries(t);for(let[r,n]of i){let o=n.attachmentId||"";e[o]||(e[o]={}),e[o][r]=n;}return e}var F=t=>{let e={},i=/([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(['"])((?:[^'"\\]|\\.)*)\2/g,r;for(;(r=i.exec(t))!==null;){let n=r[1].toLowerCase().replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase(),o=r[3],p=n==="fileid"||n==="file_id"||n==="attachmentid"?"attachment_id":n==="keyspan"?"key_span":n==="fullphrase"?"full_phrase":n==="lineids"?"line_ids":n==="startpagekey"||n==="start_pagekey"?"start_page_key":n;e[p]=o;}return e},W=t=>{if(!t)return "\u25CC";let e=R(t);return e.isPending?"\u25CC":e.isMiss?"\u2717":e.isPartialMatch?"\u26A0":e.isVerified?"\u2713":"\u25CC"},H=(t,e={})=>{let{leaveKeySpanBehind:i=false,verifications:r,showVerificationStatus:n=false}=e,o=0,p=/<cite\s+[^>]*?\/>/g;return t.replace(p,a=>{o++;let c=F(a),u="";if(i&&c.key_span&&(u=c.key_span.replace(/\\'/g,"'").replace(/\\"/g,'"')),n&&r){let s,C=String(o);if(s=r[C],!s&&c.attachment_id){for(let[,l]of Object.entries(r))if(l.attachmentId===c.attachment_id){s=l;break}}let d=W(s);u=u?`${u}${d}`:d;}return u})},dt=(t,e)=>H(t,{leaveKeySpanBehind:e}),mt=t=>t.replace(/<page_number_\d+_index_\d+>/g,"").replace(/<\/page_number_\d+_index_\d+>/g,"").trim(),ht=t=>{let e=/<line id="[^"]*">|<\/line>/g;return t.replace(e,"")},v=t=>{if(!t)return null;let e=t.match(/\d+/)?.[0];return e?parseInt(e):null},$=t=>{let e=t?.trim()||"",i=e.split(/(<cite[\s\S]*?(?:\/>|<\/cite>))/gm);return i.length<=1?z(e):(e=i.map(r=>r.startsWith("<cite")?z(r):r).join(""),e)},z=t=>{let e=t;e=e.replace(/><\/cite>/g,"/>");let i=p=>{let a=p.toLowerCase();return a==="fullphrase"||a==="full_phrase"?"full_phrase":a==="lineids"||a==="line_ids"?"line_ids":a==="startpagekey"||a==="start_pagekey"||a==="start_page_key"?"start_page_key":a==="fileid"||a==="file_id"||a==="attachmentid"||a==="attachment_id"?"attachment_id":a==="keyspan"||a==="key_span"?"key_span":a==="reasoning"||a==="value"?a:a==="timestamps"||a==="timestamp"||a==="timestamps"?"timestamps":a},r=p=>p.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),n=/(fullPhrase|full_phrase|keySpan|key_span|reasoning|value)\s*=\s*(['"])([\s\S]*?)(?=\s+(?:line_ids|lineIds|timestamps|fileId|file_id|attachmentId|attachment_id|start_page_key|start_pageKey|startPageKey|keySpan|key_span|reasoning|value|full_phrase)|\s*\/?>)/gm;e=e.replace(n,(p,a,c,u)=>{let s=u;return s.endsWith(c)&&(s=s.slice(0,-1)),s=s.replace(/(\r?\n)+/g," "),s=r(s),s=s.replace(/(\*|_){2,}/g,""),s=s.replace(/\\\\'/g,"'"),s=s.replace(/\\'/g,"'"),s=s.replace(/'/g,"\\'"),s=s.replace(/\\\\"/g,'"'),s=s.replace(/\\"/g,'"'),s=s.replace(/"/g,'\\"'),s=s.replace(/\*/g,""),`${i(a)}='${s}'`}),e=e.replace(/(line_ids|lineIds|timestamps)=['"]?([\[\]\(\){}A-Za-z0-9_\-, ]+)['"]?(\s*\/?>|\s+)/gm,(p,a,c,u)=>{let s=c.replace(/[A-Za-z\[\]\(\){}]/g,"");return s=s.replace(/(\d+)-(\d+)/g,(C,d,l)=>{let y=parseInt(d,10),x=parseInt(l,10),f=[];if(y<=x)for(let h=y;h<=x;h++)f.push(h);else f.push(y);return f.join(",")}),s=s.replace(/,+/g,",").replace(/^,|,$/g,""),`${i(a)}='${s}'${u}`});let o=p=>{let a=/([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(['"])((?:[^'"\\\n]|\\.)*)(?:\2)/g,c={},u;for(;u=a.exec(p);){let f=u[1],h=u[3],_=i(f);c[_]=h;}let s=Object.keys(c);if(s.length===0)return p;let C=typeof c.timestamps=="string"&&c.timestamps.length>0,d=s.filter(f=>f.startsWith("start_page")),l=[];c.attachment_id&&l.push("attachment_id"),C?(c.full_phrase&&l.push("full_phrase"),c.key_span&&l.push("key_span"),l.push("timestamps")):(d.includes("start_page_key")&&l.push("start_page_key"),d.filter(f=>f!=="start_page_key").sort().forEach(f=>l.push(f)),c.full_phrase&&l.push("full_phrase"),c.key_span&&l.push("key_span"),c.line_ids&&l.push("line_ids")),c.reasoning&&l.push("reasoning"),c.value&&l.push("value");let y=new Set(l);return s.filter(f=>!y.has(f)).sort().forEach(f=>l.push(f)),`<cite ${l.map(f=>`${f}='${c[f]}'`).join(" ")} />`};return e=e.replace(/<cite\b[\s\S]*?\/>/gm,p=>o(p)),e};exports.a=H;exports.b=dt;exports.c=mt;exports.d=ht;exports.e=v;exports.f=$;exports.g=P;exports.h=Y;exports.i=U;exports.j=A;exports.k=j;exports.l=Q;exports.m=tt;exports.n=et;exports.o=nt;exports.p=it;exports.q=rt;exports.r=st;exports.s=R;exports.t=B;exports.u=lt;exports.v=ut;exports.w=pt;
@@ -1,2 +1,2 @@
1
- import {j,u}from'./chunk-UC6YB63U.js';import {a}from'./chunk-O2XFH626.js';var C="https://api.deepcitation.com";function F(p,t){if(typeof Buffer<"u"&&Buffer.isBuffer(p)){let e=Uint8Array.from(p);return {blob:new Blob([e]),name:t||"document"}}if(p instanceof Blob)return {blob:p,name:t||(p instanceof File?p.name:"document")};throw new Error("Invalid file type. Expected File, Blob, or Buffer.")}async function c(p,t){return (await p.json().catch(()=>({})))?.error?.message||`${t} failed with status ${p.status}`}var y=class{constructor(t){a(this,"apiKey");a(this,"apiUrl");if(!t.apiKey)throw new Error("DeepCitation API key is required. Get one at https://deepcitation.com/dashboard");this.apiKey=t.apiKey,this.apiUrl=t.apiUrl?.replace(/\/$/,"")||C;}async uploadFile(t,e){let{blob:l,name:a}=F(t,e?.filename),o=new FormData;o.append("file",l,a),e?.attachmentId&&o.append("attachmentId",e.attachmentId),e?.filename&&o.append("filename",e.filename);let i=await fetch(`${this.apiUrl}/prepareFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:o});if(!i.ok)throw new Error(await c(i,"Upload"));return await i.json()}async convertToPdf(t){let e=typeof t=="string"?{url:t}:t,{url:l,file:a,filename:o,attachmentId:i}=e;if(!l&&!a)throw new Error("Either url or file must be provided");let r;if(l)r=await fetch(`${this.apiUrl}/convertFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({url:l,filename:o,attachmentId:i})});else {let{blob:f,name:n}=F(a,o),s=new FormData;s.append("file",f,n),i&&s.append("attachmentId",i),o&&s.append("filename",o),r=await fetch(`${this.apiUrl}/convertFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s});}if(!r.ok)throw new Error(await c(r,"Conversion"));return await r.json()}async prepareConvertedFile(t){let e=await fetch(`${this.apiUrl}/prepareFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({attachmentId:t.attachmentId})});if(!e.ok)throw new Error(await c(e,"Prepare"));return await e.json()}async prepareFiles(t){if(t.length===0)return {fileDataParts:[],deepTextPromptPortion:[]};let e=t.map(({file:i,filename:r,attachmentId:f})=>this.uploadFile(i,{filename:r,attachmentId:f}).then(n=>({result:n,filename:r}))),a=(await Promise.all(e)).map(({result:i,filename:r})=>({attachmentId:i.attachmentId,deepTextPromptPortion:i.deepTextPromptPortion,filename:r||i.metadata?.filename})),o=a.map(i=>i.deepTextPromptPortion);return {fileDataParts:a,deepTextPromptPortion:o}}async verify(t,e,l){let a={};if(Array.isArray(e))for(let n of e){let s=j(n);a[s]=n;}else if(typeof e=="object"&&e!==null)if("fullPhrase"in e||"value"in e){let n=j(e);a[n]=e;}else Object.assign(a,e);else throw new Error("Invalid citations format");if(Object.keys(a).length===0)return {verifications:{}};let o=`${this.apiUrl}/verifyCitations`,i={data:{attachmentId:t,citations:a,outputImageFormat:l?.outputImageFormat||"avif"}},r=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(i)});if(!r.ok)throw new Error(await c(r,"Verification"));return await r.json()}async verifyAll(t,e){let{llmOutput:l,outputImageFormat:a="avif"}=t;if(e||(e=u(l)),Object.keys(e).length===0)return {verifications:{}};let o=new Map;for(let[n,s]of Object.entries(e)){let m=s.attachmentId||"";o.has(m)||o.set(m,{}),o.get(m)[n]=s;}let i=[];for(let[n,s]of o)n&&i.push(this.verify(n,s,{outputImageFormat:a}));let r=await Promise.all(i),f={};for(let n of r)Object.assign(f,n.verifications);return {verifications:f}}};
2
- export{y as a};
1
+ import {j,u}from'./chunk-3PE4VRVE.js';import {a}from'./chunk-O2XFH626.js';var C="https://api.deepcitation.com";function F(p,t){if(typeof Buffer<"u"&&Buffer.isBuffer(p)){let e=Uint8Array.from(p);return {blob:new Blob([e]),name:t||"document"}}if(p instanceof Blob)return {blob:p,name:t||(p instanceof File?p.name:"document")};throw new Error("Invalid file type. Expected File, Blob, or Buffer.")}async function c(p,t){return (await p.json().catch(()=>({})))?.error?.message||`${t} failed with status ${p.status}`}var h=class{constructor(t){a(this,"apiKey");a(this,"apiUrl");if(!t.apiKey)throw new Error("DeepCitation API key is required. Get one at https://deepcitation.com/dashboard");this.apiKey=t.apiKey,this.apiUrl=t.apiUrl?.replace(/\/$/,"")||C;}async uploadFile(t,e){let{blob:l,name:a}=F(t,e?.filename),o=new FormData;o.append("file",l,a),e?.attachmentId&&o.append("attachmentId",e.attachmentId),e?.filename&&o.append("filename",e.filename);let i=await fetch(`${this.apiUrl}/prepareFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:o});if(!i.ok)throw new Error(await c(i,"Upload"));return await i.json()}async convertToPdf(t){let e=typeof t=="string"?{url:t}:t,{url:l,file:a,filename:o,attachmentId:i}=e;if(!l&&!a)throw new Error("Either url or file must be provided");let r;if(l)r=await fetch(`${this.apiUrl}/convertFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({url:l,filename:o,attachmentId:i})});else {let{blob:f,name:n}=F(a,o),s=new FormData;s.append("file",f,n),i&&s.append("attachmentId",i),o&&s.append("filename",o),r=await fetch(`${this.apiUrl}/convertFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s});}if(!r.ok)throw new Error(await c(r,"Conversion"));return await r.json()}async prepareConvertedFile(t){let e=await fetch(`${this.apiUrl}/prepareFile`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({attachmentId:t.attachmentId})});if(!e.ok)throw new Error(await c(e,"Prepare"));return await e.json()}async prepareFiles(t){if(t.length===0)return {fileDataParts:[],deepTextPromptPortion:[]};let e=t.map(({file:i,filename:r,attachmentId:f})=>this.uploadFile(i,{filename:r,attachmentId:f}).then(n=>({result:n,filename:r}))),a=(await Promise.all(e)).map(({result:i,filename:r})=>({attachmentId:i.attachmentId,deepTextPromptPortion:i.deepTextPromptPortion,filename:r||i.metadata?.filename})),o=a.map(i=>i.deepTextPromptPortion);return {fileDataParts:a,deepTextPromptPortion:o}}async verifyAttachment(t,e,l){let a={};if(Array.isArray(e))for(let n of e){let s=j(n);a[s]=n;}else if(typeof e=="object"&&e!==null)if("fullPhrase"in e||"value"in e){let n=j(e);a[n]=e;}else Object.assign(a,e);else throw new Error("Invalid citations format");if(Object.keys(a).length===0)return {verifications:{}};let o=`${this.apiUrl}/verifyCitations`,i={data:{attachmentId:t,citations:a,outputImageFormat:l?.outputImageFormat||"avif"}},r=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(i)});if(!r.ok)throw new Error(await c(r,"Verification"));return await r.json()}async verify(t,e){let{llmOutput:l,outputImageFormat:a="avif"}=t;if(e||(e=u(l)),Object.keys(e).length===0)return {verifications:{}};let o=new Map;for(let[n,s]of Object.entries(e)){let m=s.attachmentId||"";o.has(m)||o.set(m,{}),o.get(m)[n]=s;}let i=[];for(let[n,s]of o)n&&i.push(this.verifyAttachment(n,s,{outputImageFormat:a}));let r=await Promise.all(i),f={};for(let n of r)Object.assign(f,n.verifications);return {verifications:f}}};
2
+ export{h as a};
@@ -1 +1 @@
1
- 'use strict';var chunkGWKSW26H_cjs=require('../chunk-GWKSW26H.cjs');require('../chunk-6VPT3IIK.cjs'),require('../chunk-F2MMVEVC.cjs');Object.defineProperty(exports,"DeepCitation",{enumerable:true,get:function(){return chunkGWKSW26H_cjs.a}});
1
+ 'use strict';var chunkCGNTWQHJ_cjs=require('../chunk-CGNTWQHJ.cjs');require('../chunk-SPCFZGGU.cjs'),require('../chunk-F2MMVEVC.cjs');Object.defineProperty(exports,"DeepCitation",{enumerable:true,get:function(){return chunkCGNTWQHJ_cjs.a}});
@@ -101,9 +101,9 @@ interface PrepareFilesResult {
101
101
  deepTextPromptPortion: string[];
102
102
  }
103
103
  /**
104
- * Input for verifyCitationsFromLlmOutput
104
+ * Input for verify method
105
105
  */
106
- interface VerifyCitationsFromLlmOutput {
106
+ interface VerifyInput {
107
107
  /** The LLM response containing citations */
108
108
  llmOutput: string;
109
109
  /** Optional file references (required for Zero Data Retention or after storage expires) */
@@ -111,6 +111,10 @@ interface VerifyCitationsFromLlmOutput {
111
111
  /** Output image format for verification screenshots */
112
112
  outputImageFormat?: "jpeg" | "png" | "avif";
113
113
  }
114
+ /**
115
+ * @deprecated Use VerifyInput instead. This alias is kept for backwards compatibility.
116
+ */
117
+ type verifyAll = VerifyInput;
114
118
  /**
115
119
  * Input for convertFile - convert URL or Office file to PDF
116
120
  */
@@ -164,7 +168,7 @@ interface PrepareConvertedFileOptions {
164
168
  * const dc = new DeepCitation({ apiKey: process.env.DEEPCITATION_API_KEY });
165
169
  *
166
170
  * // Upload a file
167
- * const { attachmentId, promptContent } = await dc.uploadFile(file);
171
+ * const { attachmentId, promptContent } = await deepcitation.uploadFile(file);
168
172
  *
169
173
  * // Include promptContent in your LLM messages
170
174
  * const response = await llm.chat({
@@ -176,7 +180,7 @@ interface PrepareConvertedFileOptions {
176
180
  *
177
181
  * // Verify citations in the LLM output
178
182
  * const citations = getAllCitationsFromLlmOutput(response);
179
- * const verified = await dc.verifyCitations(attachmentId, citations);
183
+ * const verified = await deepcitation.verifyCitations(attachmentId, citations);
180
184
  * ```
181
185
  */
182
186
  declare class DeepCitation {
@@ -205,11 +209,11 @@ declare class DeepCitation {
205
209
  * ```typescript
206
210
  * // Browser with File object
207
211
  * const file = document.querySelector('input[type="file"]').files[0];
208
- * const result = await dc.uploadFile(file);
212
+ * const result = await deepcitation.uploadFile(file);
209
213
  *
210
214
  * // Node.js with Buffer
211
215
  * const buffer = fs.readFileSync('document.pdf');
212
- * const result = await dc.uploadFile(buffer, { filename: 'document.pdf' });
216
+ * const result = await deepcitation.uploadFile(buffer, { filename: 'document.pdf' });
213
217
  * ```
214
218
  */
215
219
  uploadFile(file: File | Blob | Buffer, options?: UploadFileOptions): Promise<UploadFileResponse>;
@@ -231,16 +235,16 @@ declare class DeepCitation {
231
235
  * @example
232
236
  * ```typescript
233
237
  * // Convert a URL to PDF
234
- * const result = await dc.convertToPdf({ url: "https://example.com/article" });
238
+ * const result = await deepcitation.convertToPdf({ url: "https://example.com/article" });
235
239
  *
236
240
  * // Convert an Office document
237
- * const result = await dc.convertToPdf({
241
+ * const result = await deepcitation.convertToPdf({
238
242
  * file: docxBuffer,
239
243
  * filename: "report.docx"
240
244
  * });
241
245
  *
242
246
  * // Then prepare the file for verification
243
- * const { deepTextPromptPortion, attachmentId } = await dc.prepareConvertedFile({
247
+ * const { deepTextPromptPortion, attachmentId } = await deepcitation.prepareConvertedFile({
244
248
  * attachmentId: result.attachmentId
245
249
  * });
246
250
  * ```
@@ -256,10 +260,10 @@ declare class DeepCitation {
256
260
  * @example
257
261
  * ```typescript
258
262
  * // First convert the file
259
- * const converted = await dc.convertToPdf({ url: "https://example.com/article" });
263
+ * const converted = await deepcitation.convertToPdf({ url: "https://example.com/article" });
260
264
  *
261
265
  * // Then prepare it for verification
262
- * const { deepTextPromptPortion, attachmentId } = await dc.prepareConvertedFile({
266
+ * const { deepTextPromptPortion, attachmentId } = await deepcitation.prepareConvertedFile({
263
267
  * attachmentId: converted.attachmentId
264
268
  * });
265
269
  *
@@ -276,7 +280,7 @@ declare class DeepCitation {
276
280
  *
277
281
  * @example
278
282
  * ```typescript
279
- * const { fileDataParts, deepTextPromptPortion } = await dc.prepareFiles([
283
+ * const { fileDataParts, deepTextPromptPortion } = await deepcitation.prepareFiles([
280
284
  * { file: pdfBuffer, filename: "report.pdf" },
281
285
  * { file: invoiceBuffer, filename: "invoice.pdf" },
282
286
  * ]);
@@ -289,12 +293,16 @@ declare class DeepCitation {
289
293
  * });
290
294
  *
291
295
  * // Use fileDataParts later for verification
292
- * const result = await dc.verifyCitationsFromLlmOutput({ llmOutput, fileDataParts });
296
+ * const result = await deepcitation.verifyAll({ llmOutput, fileDataParts });
293
297
  * ```
294
298
  */
295
299
  prepareFiles(files: FileInput[]): Promise<PrepareFilesResult>;
296
300
  /**
297
- * Verify citations against a previously uploaded file.
301
+ * Verify citations against a single attachment/file.
302
+ *
303
+ * For most use cases, prefer `verify()` which automatically parses citations
304
+ * from LLM output and handles multiple attachments. Use this method when you
305
+ * need fine-grained control over per-attachment verification.
298
306
  *
299
307
  * @param attachmentId - The attachment ID returned from uploadFile
300
308
  * @param citations - Citations to verify (from getAllCitationsFromLlmOutput)
@@ -306,7 +314,7 @@ declare class DeepCitation {
306
314
  * import { getAllCitationsFromLlmOutput } from '@deepcitation/deepcitation-js';
307
315
  *
308
316
  * const citations = getAllCitationsFromLlmOutput(llmResponse);
309
- * const verified = await dc.verify(attachmentId, citations);
317
+ * const verified = await deepcitation.verifyAttachment(attachmentId, citations);
310
318
  *
311
319
  * for (const [key, result] of Object.entries(verified.verifications)) {
312
320
  * console.log(key, result.status);
@@ -314,17 +322,26 @@ declare class DeepCitation {
314
322
  * }
315
323
  * ```
316
324
  */
317
- verify(attachmentId: string, citations: CitationInput, options?: VerifyCitationsOptions): Promise<VerifyCitationsResponse>;
325
+ verifyAttachment(attachmentId: string, citations: CitationInput, options?: VerifyCitationsOptions): Promise<VerifyCitationsResponse>;
318
326
  /**
319
327
  * Parse and verify all citations from LLM output.
320
- * This is the recommended way to verify citations for new integrations.
328
+ *
329
+ * This is the recommended method for citation verification. It automatically:
330
+ * 1. Parses citations from LLM output (no raw content sent to our servers)
331
+ * 2. Groups citations by attachment ID
332
+ * 3. Verifies each attachment in parallel
333
+ *
334
+ * For privacy-conscious users: we only receive the parsed citation metadata,
335
+ * not your raw LLM output. This method is a convenience wrapper that parses
336
+ * locally and makes per-attachment verification calls.
321
337
  *
322
338
  * @param input - Object containing llmOutput and optional outputImageFormat
339
+ * @param citations - Optional pre-parsed citations (skips parsing if provided)
323
340
  * @returns Verification results with status and proof images
324
341
  *
325
342
  * @example
326
343
  * ```typescript
327
- * const result = await dc.verifyAll({
344
+ * const result = await deepcitation.verify({
328
345
  * llmOutput: response.content,
329
346
  * });
330
347
  *
@@ -333,9 +350,9 @@ declare class DeepCitation {
333
350
  * }
334
351
  * ```
335
352
  */
336
- verifyAll(input: VerifyCitationsFromLlmOutput, citations?: {
353
+ verify(input: VerifyInput, citations?: {
337
354
  [key: string]: Citation;
338
355
  }): Promise<VerifyCitationsResponse>;
339
356
  }
340
357
 
341
- export { type CitationInput, type ConvertFileInput, type ConvertFileResponse, DeepCitation, type DeepCitationConfig, type FileDataPart, type FileInput, type PrepareConvertedFileOptions, type PrepareFilesResult, type UploadFileOptions, type UploadFileResponse, type VerifyCitationsFromLlmOutput, type VerifyCitationsOptions, type VerifyCitationsResponse };
358
+ export { type CitationInput, type ConvertFileInput, type ConvertFileResponse, DeepCitation, type DeepCitationConfig, type FileDataPart, type FileInput, type PrepareConvertedFileOptions, type PrepareFilesResult, type UploadFileOptions, type UploadFileResponse, type VerifyCitationsOptions, type VerifyCitationsResponse, type VerifyInput, type verifyAll };