wiki-graph 0.8.2 → 0.8.4
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/dist/cli.js +786 -553
- package/dist/cli.js.map +1 -1
- package/dist/gc-worker.js +136 -54
- package/dist/gc-worker.js.map +1 -1
- package/dist/index.cjs +38 -33
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +38 -33
- package/dist/index.js.map +1 -1
- package/dist/queue-worker.js +779 -546
- package/dist/queue-worker.js.map +1 -1
- package/package.json +2 -2
package/dist/gc-worker.js
CHANGED
|
@@ -3,28 +3,28 @@ import { fileURLToPath as __WIKIGRAPH_FILE_URL_TO_PATH__ } from "url";
|
|
|
3
3
|
import { resolve as __WIKIGRAPH_RESOLVE__ } from "path";
|
|
4
4
|
globalThis.__WIKIGRAPH_CLI_DIST_DIR__ ??= __WIKIGRAPH_RESOLVE__(__WIKIGRAPH_FILE_URL_TO_PATH__(new URL(".", import.meta.url)));
|
|
5
5
|
globalThis.__WIKIGRAPH_DATA_DIR__ ??= __WIKIGRAPH_RESOLVE__(__WIKIGRAPH_FILE_URL_TO_PATH__(new URL("./data", import.meta.url)));
|
|
6
|
-
var ak=Object.defineProperty;var i=(t,e)=>()=>(t&&(e=t(t=0)),e);var ok=(t,e)=>{for(var n in e)ak(t,n,{get:e[n],enumerable:!0})};async function ui(t){let e=await t.openReader();try{return e.size}finally{await e.close()}}async function wt(t){return await ui(t)===0}async function ae(t){return new TextDecoder().decode(await Vt(t))}async function Vt(t){let e=await t.openReader();try{let n=new Uint8Array(e.size);for(let r=0;r<e.size;){let a=await e.read(r,Math.min(65536,e.size-r));n.set(a,r),r+=a.byteLength}return n}finally{await e.close()}}async function me(t,e){let n=await t.openWriter();try{await n.write(e),await n.commit()}catch(r){throw await n.abort().catch(()=>{}),r}}async function Ie(t){if(U(t)){let e=0;for(let n of await t.list())e+=await Ie(n);return e}return await ui(t)}async function Ye(t){return await t.getLastModified?.()}function U(t){return t.kind==="directory"}var Uu=i(()=>{"use strict"});function Yt(t){Zt().installedPlatform=t}function _(){let{installedPlatform:t}=Zt();if(t===void 0)throw new Error("No WikiGraph runtime platform has been installed. Provide a runtime adapter before using wiki-graph-core.");return t}async function kt(t){if(typeof t!="string")return t;let e=await _().resources.getFile(t);if(e===void 0)throw new Error("Host file is unavailable");return e}async function J(t,e){let n=e.replaceAll("\\","/").split("/").filter(Boolean);if(n.some(o=>o==="."||o===".."))throw new TypeError(`Directory path must remain relative: ${e}`);let r=n.pop();if(!r)return;let a=t;for(let o of n){let s=await a.getDirectory(o);if(!s)return;a=s}return await a.getFile(r)}async function We(t,e){let n=yo(e),r=t;for(let a of n){let o=await r.getDirectory(a);if(!o)return;r=o}return r}async function z(t,e){let n=yo(e),r=t;for(let a of n){let o=await r.getDirectory(a);if(o!==void 0){r=o;continue}try{r=await r.createDirectory(a)}catch(s){let d=await r.getDirectory(a);if(d===void 0)throw s;r=d}}return r}async function H(t,e){let n=yo(e),r=n.pop();if(!r)throw new TypeError("File name must remain relative");let a=await z(t,n.join("/")),o=await a.getFile(r);if(o!==void 0)return o;try{return await a.createFile(r)}catch(s){let d=await a.getFile(r);if(d!==void 0)return d;throw s}}function yo(t){let e=t.replaceAll("\\","/");if(e.startsWith("/"))throw new TypeError(`Directory path must remain relative: ${t}`);let n=e.split("/").filter(Boolean);if(n.some(r=>r==="."||r===".."))throw new TypeError(`Directory path must remain relative: ${t}`);return n}function Zt(){let t=globalThis,e=t[qu];if(e!==void 0)return e;let n={storageContext:new fo};return Object.defineProperty(t,qu,{configurable:!1,enumerable:!1,value:n,writable:!1}),n}function mi(t){Zt().installedStorage=t}async function en(t,e){return t===void 0?await e():await Zt().storageContext.run(t,e)}function R(){let{installedStorage:t,storageContext:e}=Zt(),n=e.getStore()??t;if(n===void 0)throw new Error("No WikiGraph storage roots have been configured. Pass storage to WikiGraph or install process-default storage.");return n}var qu,fo,y=i(()=>{"use strict";Uu();qu=Symbol.for("wiki-graph-core.runtime.v1");fo=class{#e;#t;run(e,n){let r=this.#n();if(r!==void 0)return r.run(e,n);let a=this.#t;this.#t=e;try{return n()}finally{this.#t=a}}enterWith(e){let n=this.#n();n!==void 0?n.enterWith(e):this.#t=e}getStore(){return this.#n()?.getStore()??this.#t}#n(){if(this.#e!==void 0)return this.#e;let{installedPlatform:e}=Zt();if(e!==void 0)return this.#e=e.asyncContext.create(),this.#t!==void 0&&(this.#e.enterWith(this.#t),this.#t=void 0),this.#e}}});function pi(t){if(dk.test(t))throw new Error(`invalid template name ${t}`);let n=t.replace(ck,"").replace(sk,"");if(n.split("/").includes(".."))throw new Error(`invalid template name ${t}`);return`${n}.jinja`}var sk,dk,ck,Gn=i(()=>{"use strict";y();sk=/\.jinja$/iu,dk=/^\.+\//u,ck=/^\/+/u});var go=i(()=>{"use strict";y();Gn()});import*as $u from"async_hooks";import*as Ju from"crypto";import*as fi from"fs";import*as q from"fs/promises";import*as Ku from"os";import*as O from"path";import*as xo from"process";import{Readable as zu,Writable as uk}from"stream";import{pipeline as lk}from"stream/promises";import*as Io from"sqlite3";import*as Qu from"yauzl";import*as Xu from"yazl";import{Environment as mk,Loader as pk}from"nunjucks";async function Hu(t,e,n){let r=Buffer.from(e),a=0;for(;a<r.byteLength;){let o=await t.write(r,a,r.byteLength-a,n===void 0?null:n+a);if(o.bytesWritten===0)throw new Error("File writer made no progress");a+=o.bytesWritten}}function Vu(t,e,n){if(Yu(t),!Number.isSafeInteger(e)||e<0)throw new RangeError("File read length must be a non-negative safe integer");if(t>n||e>n-t)throw new RangeError("File read range exceeds the file size")}function Yu(t){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("File offset must be a non-negative safe integer")}function Zu(t,e){return`node-${t}:${Buffer.from(O.resolve(e),"utf8").toString("base64url")}`}function bo(t,e){let n=`node-${e}:`;if(!t.startsWith(n))return O.isAbsolute(t)?t:void 0;try{return Buffer.from(t.slice(n.length),"base64url").toString("utf8")}catch{return}}function jn(t){if(t.length===0||t==="."||t===".."||O.isAbsolute(t)||t.includes("/")||t.includes("\\"))throw new TypeError(`Directory child must be a relative name: ${t}`)}async function hk(t,e){let n=(e.mode==="readonly"?Un.OPEN_READONLY:Un.OPEN_READWRITE|(e.create?Un.OPEN_CREATE:0))|Un.OPEN_FULLMUTEX;return new wo(await fk(t,n))}async function fk(t,e){let n=el(t,"file");if(n===void 0)throw new TypeError("The Node database adapter requires a NodeFile");return await new Promise((r,a)=>{let o=new Un.Database(n,e,s=>{s?a(s):r(o)})})}async function yk(t){let e=el(t,"file");if(e===void 0)throw new TypeError("The Node ZIP adapter requires a NodeFile");let n=await new Promise((o,s)=>{Qu.open(e,{autoClose:!1,lazyEntries:!0},(d,c)=>{d||c===void 0?s(d??new Error("Cannot open ZIP")):o(c)})}),r=await new Promise((o,s)=>{let d=new Map,c=m=>{n.close(),s(m instanceof Error?m:new Error("Cannot scan ZIP central directory"))},u=()=>{n.off("error",c),o(d)};n.on("entry",m=>{m.fileName.endsWith("/")||d.set(m.fileName,m),n.readEntry()}),n.once("error",c),n.once("end",u),n.readEntry()}),a=!1;return{close:()=>(a||n.close(),a=!0,Promise.resolve()),copyEntry:async(o,s)=>{if(a)throw new Error("Cannot read a closed ZIP archive");let d=r.get(o);return d===void 0?!1:(await gk(n,d,s),!0)},getEntrySize:o=>{if(a)throw new Error("Cannot read a closed ZIP archive");return Promise.resolve(r.get(o)?.uncompressedSize)},listEntries:()=>Promise.resolve([...r.keys()]),readEntryRange:async(o,s,d)=>{if(a)throw new Error("Cannot read a closed ZIP archive");let c=r.get(o);if(c!==void 0)return await Sk(n,c,s,d)},readEntry:async o=>{if(a)throw new Error("Cannot read a closed ZIP archive");let s=r.get(o);if(s!==void 0)return await bk(n,s)}}}async function gk(t,e,n){let r=await n.openWriter();try{let a=await hi(t,e);await tl(a,r),await r.commit()}catch(a){throw await r.abort().catch(()=>{}),a}}async function bk(t,e){return await nl(await hi(t,e))}async function Sk(t,e,n,r){if(Vu(n,r,e.uncompressedSize),r===0)return new Uint8Array;if(e.compressionMethod!==0){let o=await wk(await hi(t,e),n,r);return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}let a=await nl(await hi(t,e,{decompress:null,decrypt:null,end:n+r,start:n}));return new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}async function wk(t,e,n){let r=[],a=e+n,o=0,s=0;for await(let d of t){let c=Buffer.isBuffer(d)?d:Buffer.from(d),u=o+c.byteLength;if(u>e&&o<a){let m=c.subarray(Math.max(0,e-o),Math.min(c.byteLength,a-o));r.push(m),s+=m.byteLength}if(o=u,o>=a)break}if(s!==n)throw new Error("ZIP entry changed while reading its byte range");return Buffer.concat(r,s)}async function hi(t,e,n){return await new Promise((r,a)=>{let o=(s,d)=>{s||d===void 0?a(s??new Error(`Cannot read ZIP entry: ${e.fileName}`)):r(d)};n===void 0?t.openReadStream(e,o):t.openReadStream(e,n,o)})}async function kk(t,e){let n=new Xu.ZipFile,r=await t.openWriter(),a=n.outputStream,o=tl(a,r),s={cancelled:!1,complete:!1},d;try{d=vk(e);let c=xk(n,d,s);if(await Promise.race([c,o]),!s.complete)throw new Error("ZIP output ended before entry production completed");n.end(),await o,await r.commit()}catch(c){throw s.cancelled=!0,!s.complete&&d!==void 0&&Rk(d),a.destroyed||a.destroy(c instanceof Error?c:new Error("Cannot write ZIP archive")),await o.catch(()=>{}),await r.abort().catch(()=>{}),c}}async function xk(t,e,n){for(;!n.cancelled;){let r=await e.next();if(n.cancelled)return;if(r.done){n.complete=!0;return}"file"in r.value?t.addReadStream(Ik(r.value.file),r.value.name,{compress:!1}):"data"in r.value?t.addBuffer(Buffer.from(r.value.data),r.value.name,{compress:!1}):t.addReadStream(Ek(r.value),r.value.name,{compress:!1,size:r.value.size})}}function Ik(t){return zu.from((async function*(){let e=await t.openReader();try{for(let n=0;n<e.size;){let r=await e.read(n,Math.min(65536,e.size-n));n+=r.byteLength,yield r}}finally{await e.close()}})())}function el(t,e){if(typeof t!="object"||t===null)return;let n=t;return n[Eo]===e&&typeof n.path=="string"?n.path:void 0}function Ek(t){return zu.from((async function*(){for(let e=0;e<t.size;){let n=await t.read(e,Math.min(65536,t.size-e));e+=n.byteLength,yield n}})())}function vk(t){let e=t[Symbol.asyncIterator];return e===void 0?t[Symbol.iterator]():e.call(t)}function Rk(t){if(t.return!==void 0)try{Promise.resolve(t.return()).catch(()=>{})}catch{}}async function tl(t,e){await lk(t,new uk({write:(n,r,a)=>{e.write(n).then(()=>a(),o=>a(o instanceof Error?o:new Error("Cannot stream ZIP archive")))}}))}async function nl(t){return await new Promise((e,n)=>{let r=[];t.on("data",a=>r.push(a)),t.once("error",n),t.once("end",()=>e(Buffer.concat(r)))})}function Ck(){let t=globalThis.__WIKIGRAPH_DATA_DIR__;if(typeof t=="string"&&t!=="")return t;let e=So.cwd();for(;;){for(let r of[O.join(e,"data"),O.join(e,"packages","core","data")])try{if(fi.statSync(r).isDirectory())return r}catch{}let n=O.dirname(e);if(n===e)throw new Error("Could not locate data directory");e=n}}function vo(t=O.join(Ku.homedir(),".wikigraph")){let e=typeof t=="string"?t:t.libraryRoot,n=typeof t=="string"?O.join(t,"documents"):t.documentStoreRoot;return{library:new De(e),documentStore:new De(n)}}function il(t){Yt(rl),mi(vo(t))}function al(){try{_()}catch{Yt(rl)}try{R()}catch{mi(vo())}}async function yi(t,e){return await en(t===void 0?void 0:vo(t),e)}var So,Un,Eo,se,De,wo,rl,ko,ce=i(()=>{"use strict";go();So=xo.default??xo,Un=Io.default??Io,Eo=Symbol.for("wiki-graph-sdk.node-resource.v1"),se=class{constructor(e,n=O.basename(e)){this.path=e;this.identity=Zu("file",e),this.name=n}path;kind="file";[Eo]="file";identity;name;async openReader(){let e=await q.open(this.path,"r"),n=!1;try{let r=await e.stat();if(!r.isFile())throw new Error("File reader requires a regular file");let{size:a}=r;return{size:a,close:async()=>{n||await e.close(),n=!0},read:async(o,s)=>{if(n)throw new Error("Cannot read from a closed FileReader");Vu(o,s,a);let d=Buffer.allocUnsafe(s),c=0;for(;c<s;){let u=await e.read(d,c,s-c,o+c);if(u.bytesRead===0)throw new Error("File changed while reading its byte range");c+=u.bytesRead}return new Uint8Array(d.buffer,d.byteOffset,c)}}}catch(r){throw await e.close(),r}}async getLastModified(){try{return(await q.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async openWriter(){await q.mkdir(O.dirname(this.path),{recursive:!0});let e=`${this.path}.tmp-${Ju.randomUUID()}`,n=await q.open(e,"wx"),r=!1;return{write:async a=>{if(r)throw new Error("Cannot write to a closed FileWriter");await Hu(n,a)},writeAt:async(a,o)=>{if(r)throw new Error("Cannot write to a closed FileWriter");Yu(a),await Hu(n,o,a)},commit:async()=>{r||(await n.close(),await q.rename(e,this.path)),r=!0},abort:async()=>{r||(await n.close(),await q.rm(e,{force:!0})),r=!0}}}};De=class t{constructor(e){this.path=e;this.identity=Zu("directory",e),this.name=O.basename(e)}path;kind="directory";[Eo]="directory";identity;name;async getFile(e){jn(e);let n=new se(O.join(this.path,e));try{return(await q.stat(n.path)).isFile()?n:void 0}catch{return}}async getLastModified(){try{return(await q.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async getDirectory(e){jn(e);let n=new t(O.join(this.path,e));try{return(await q.stat(n.path)).isDirectory()?n:void 0}catch{return}}async list(){return(await q.readdir(this.path,{withFileTypes:!0})).map(n=>n.isDirectory()?new t(O.join(this.path,n.name)):new se(O.join(this.path,n.name),n.name))}async createFile(e){jn(e),await q.mkdir(this.path,{recursive:!0});let n=new se(O.join(this.path,e));return await q.writeFile(n.path,"",{flag:"wx"}),n}async createDirectory(e){jn(e),await q.mkdir(this.path,{recursive:!0});let n=new t(O.join(this.path,e));return await q.mkdir(n.path),n}async remove(e,n){jn(e),await q.rm(O.join(this.path,e),{force:!0,recursive:n?.recursive===!0})}};wo=class{constructor(e){this.database=e}database;async close(){await new Promise((e,n)=>{this.database.close(r=>{r?n(r):e()})})}async execute(e){await new Promise((n,r)=>{this.database.exec(e,a=>{a?r(a):n()})})}async queryAll(e,n=[]){return await new Promise((r,a)=>{this.database.all(e,[...n],(o,s)=>{o?a(o):r(s)})})}async queryOne(e,n=[]){return await new Promise((r,a)=>{this.database.get(e,[...n],(o,s)=>{o?a(o):r(s)})})}async run(e,n=[]){await new Promise((r,a)=>{this.database.run(e,[...n],o=>{o?a(o):r()})})}};rl={asyncContext:{create:()=>new $u.AsyncLocalStorage},database:{open:hk},lifecycle:{instanceId:`node-process:${So.pid}`,isInstanceAlive:t=>{let e=/^node-process:(\d+)$/u.exec(t);if(e===null)return Promise.resolve(void 0);try{return So.kill(Number(e[1]),0),Promise.resolve(!0)}catch(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="ESRCH"?Promise.resolve(!1):Promise.resolve(!0)}}},resources:{getDirectory:t=>{let e=bo(t,"directory");return Promise.resolve(e===void 0?void 0:new De(e))},getFile:t=>{let e=bo(t,"file");return Promise.resolve(e===void 0?void 0:new se(e))},resolveLegacyDirectory:t=>{let e=bo(t,"directory");return Promise.resolve(e===void 0?void 0:new De(e))}},templates:{createEnvironment:t=>new mk(new ko,t)},zip:{open:yk,write:kk}},ko=class extends pk{#e;constructor(e){super(),this.#e=e}getSource(e){let n=pi(e),r=O.join(this.#e??Ck(),n);return{noCache:!1,path:n,src:fi.readFileSync(r,"utf8")}}}});var Me=i(()=>{"use strict"});function ol(t){return new TextEncoder().encode(t)}function xt(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}var Ee=i(()=>{"use strict"});import{sha1 as Tk}from"@noble/hashes/legacy.js";import{sha256 as _k,sha512 as Pk}from"@noble/hashes/sha2.js";function oe(t){let e=Ak(t);return{update(n){return e.update(typeof n=="string"?ol(n):n),this},digest(n){let r=e.digest();return n==="hex"?xt(r):r}}}function qn(t){let e=new Uint8Array(t);return globalThis.crypto.getRandomValues(e),e}function Ze(){if(typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();let t=qn(16);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=xt(t);return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function Ak(t){switch(t){case"sha1":return Tk.create();case"sha256":return _k.create();case"sha512":return Pk.create()}}var F=i(()=>{"use strict";Ee()});var gi=i(()=>{"use strict";F()});var dl=i(()=>{"use strict";y()});var cl=i(()=>{"use strict";dl()});var ul=i(()=>{"use strict"});function Fe(t){return t instanceof Error}function tn(t){let e=[],n=new Set,r=t;for(;r!==void 0&&!n.has(r);){if(n.add(r),r instanceof Error){ll(e,Mk(r)),r=r.cause;continue}ll(e,String(r));break}return e.join(": ")}function Mk(t){let e=t,n=t.message.trim(),r=typeof e.code=="string"&&e.code!==""?e.code:void 0;return r==="ENOENT"?"File not found (ENOENT)":r==="EACCES"||r==="EPERM"?`Permission denied (${r})`:r!==void 0&&Fk(n)?`${t.name} (${r})`:n===""?t.name:r===void 0?n:`${n} (${r})`}function Fk(t){return/(?:^|[\s:'"(=])\/(?:[^\s/]+\/)*[^\s/]+/u.test(t)||/(?:^|[\s:'"(=])[A-Za-z]:[\\/]/u.test(t)||/\bfile:\/\//iu.test(t)}function ll(t,e){let n=e.trim();if(n==="")return;let r=t.at(-1);if(r===void 0){t.push(n);return}if(!(r===n||r.includes(n))){if(n.includes(r)){t[t.length-1]=n;return}t.push(n)}}var pe=i(()=>{"use strict";y()});var ml=i(()=>{"use strict";pe()});var pl=i(()=>{"use strict"});import{APICallError as oA}from"ai";var hl=i(()=>{"use strict";y()});var et=i(()=>{"use strict";y()});var It,Hn=i(()=>{"use strict";It=class{#e=0;#t;#n=[];constructor(e){if(!Number.isInteger(e)||e<1)throw new RangeError("concurrency must be a positive integer");this.#t=e}async use(e){await this.#r();try{return await e()}finally{this.#i()}}async#r(){if(this.#e<this.#t){this.#e+=1;return}await new Promise(e=>{this.#n.push(()=>{this.#e+=1,e()})})}#i(){this.#e-=1,this.#n.shift()?.()}}});var Co=i(()=>{"use strict";et()});var To=i(()=>{"use strict"});var fl=i(()=>{"use strict";y()});var _o=i(()=>{"use strict"});import{generateText as OA,streamText as NA}from"ai";var gl=i(()=>{"use strict";cl();ul();ml();pl();hl();et();Gn();Hn();gi();pe();Co();To();fl();_o()});var bl=i(()=>{"use strict";gl()});var Ao=i(()=>{"use strict";bl();Co();To();_o()});var qk,Lo,Sl,nn=i(()=>{"use strict";qk=Object.freeze(["serial-generation/editor-compress","serial-generation/editor-review","serial-generation/editor-review-guide","serial-generation/reader-choice","serial-generation/reader-extraction"]),Lo=Object.freeze({compress:"serial-generation/editor-compress",review:"serial-generation/editor-review",reviewGuide:"serial-generation/editor-review-guide"}),Sl=Object.freeze({choice:"serial-generation/reader-choice",extraction:"serial-generation/reader-extraction"})});var Q,Z=i(()=>{"use strict";Q=class extends Error{code;details;constructor(e,n,r={},a={}){super(n,a),this.name="WikiGraphError",this.code=e,this.details=r}}});var Oo=i(()=>{"use strict"});async function Hk(t){try{return await wt(t)}catch(e){if(Fe(e)&&e.code==="ENOENT")return!0;throw e}}function S(t,e){let n=t[e];if(typeof n!="number")throw new TypeError(`Expected ${e} to be a number`);return n}function E(t,e){let n=t[e];if(typeof n!="string")throw new TypeError(`Expected ${e} to be a string`);return n}var Bk,N,No,w=i(()=>{"use strict";y();pe();Bk=900*1e3;N=class t{#e;#t;#n;#r;#i=!1;#u=Promise.resolve();#d=0;constructor(e,n={}){this.#e=e,this.#t=n.onWrite,this.#n=_().asyncContext.create()}static async open(e,n,r){let a=await kt(e),o=r.mode==="readwrite"&&r.create&&n.trim()!==""&&await Hk(a),s=r.mode==="readonly"?await _().database.open(a,{mode:"readonly"}):await _().database.open(a,{create:r.create,mode:"readwrite"}),d;try{return d=new t(new No(s),r),await d.#o(`PRAGMA busy_timeout = ${Bk}`),r.mode==="readwrite"&&n.trim()!==""&&(await d.#o(n),o&&d.#c()),d}catch(c){throw d===void 0?await s.close().catch(()=>{}):await d.close().catch(()=>{}),c}}static async initialize(e,n){let r=await t.open(e,"",{create:!0,mode:"readwrite"});try{n.trim()!==""&&await r.#o(n)}finally{await r.close()}}async queryAll(e,n,r){return await this.#a(async()=>(this.#s(),(await this.#m(e,n)).map(r)))}async queryOne(e,n,r){return await this.#a(async()=>{this.#s();let a=await this.#p(e,n);return a===void 0?void 0:r(a)})}async run(e,n){await this.#a(async()=>{this.#s(),await this.#h(e,n),this.#c()})}async execute(e){await this.#a(async()=>{this.#s(),await this.#o(e),this.#c()})}async transaction(e){return await this.#a(async()=>{this.#s();let n=this.#d===0,r=this.#r??Symbol("database transaction scope");n&&(await this.#o("BEGIN IMMEDIATE"),this.#r=r),this.#d+=1;try{let a=await this.#n.run(r,e);return n&&await this.#o("COMMIT"),a}catch(a){throw n&&await this.#o("ROLLBACK"),a}finally{this.#d-=1,n&&(this.#r=void 0)}})}async flush(){await this.#a(()=>{this.#s()})}async close(){await this.#a(async()=>{this.#i||(await this.#l(),this.#i=!0)})}async getLastInsertRowId(){let e=await this.queryOne("SELECT last_insert_rowid() AS row_id",void 0,n=>S(n,"row_id"));if(e===void 0)throw new Error("Could not read last_insert_rowid()");return e}#s(){if(this.#i)throw new Error("Database is already closed")}async#a(e){let n=this.#n.getStore();if(n!==void 0&&n===this.#r)return await e();let r=this.#u.then(e);return this.#u=r.then(()=>{},()=>{}),await r}#c(){this.#t?.()}async#l(){await this.#e.close()}async#o(e){await this.#e.execute(e)}async#m(e,n){return await this.#e.queryAll(e,n)}async#p(e,n){return await this.#e.queryOne(e,n)}async#h(e,n){await this.#e.run(e,n)}};No=class{#e;constructor(e){this.#e=e}async close(){await this.#e.close()}async execute(e){await this.#e.execute(e)}async queryAll(e,n){return[...await this.#e.queryAll(e,n)]}async queryOne(e,n){return await this.#e.queryOne(e,n)}async run(e,n){await this.#e.run(e,n)}}});async function Et(){let t=R().library,e=Si.get(t.identity);if(e!==void 0){await e;return}let n=Jk(t);Si.set(t.identity,n);try{await n}finally{Si.get(t.identity)===n&&Si.delete(t.identity)}}async function Ei(){let t=await J(R().library,"core.sqlite");if(t===void 0||await vi(t))return 0;let e=await N.open(t,"",{mode:"readonly"});try{return await rn(e,"schema_versions")?await e.queryOne("SELECT version FROM schema_versions WHERE scope = ?",["home"],n=>S(n,"version"))??1:1}finally{await e.close()}}async function Jk(t){let e=await Ei();if(e>Wo)throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`);let n=await H(t,"core.sqlite");if(e===0){await wi(n,Wo);return}for(;e<Wo;)switch(e){case 1:await wl(t),await wi(n,2),e=2;break;case 2:await wl(t),await wi(n,3),e=3;break;case 3:await Kk(n),await wi(n,4),e=4;break;default:throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`)}}async function wl(t){await vl(t),await El(t)}async function Kk(t){let e=R().library;await vl(e),await zk(t),await El(e)}async function zk(t){let e=await N.open(t,"",{create:!1,mode:"readwrite"});try{if(!await rn(e,"libraries"))return;let n=await xi(e,"libraries"),r=n.has("folder_identity")?"folder_identity":n.has("folder_path")?"folder_path":void 0;if(r===void 0)throw new Error("Cannot migrate library registry without a folder reference.");let a=await e.queryAll(`SELECT id, ${r} AS folder_reference FROM libraries ORDER BY id`,void 0,s=>({id:S(s,"id"),reference:E(s,"folder_reference")})),o=[];for(let s of a){let d=_().resources,c=r==="folder_identity"||d.resolveLegacyDirectory===void 0?await d.getDirectory(s.reference):await d.resolveLegacyDirectory(s.reference);if(c===void 0)throw new Error(`Cannot migrate unavailable library Directory for registry id ${s.id}.`);o.push({id:s.id,identity:c.identity})}await e.transaction(async()=>{n.has("folder_identity")||await e.run("ALTER TABLE libraries RENAME COLUMN folder_path TO folder_identity");for(let s of o)await e.run("UPDATE libraries SET folder_identity = ? WHERE id = ?",[s.identity,s.id])})}finally{await e.close()}}async function wi(t,e){let n=await N.open(t,"",{create:!0,mode:"readwrite"});try{await n.execute($k),await n.run(`INSERT INTO schema_versions (scope, version, updated_at)
|
|
6
|
+
var bk=Object.defineProperty;var i=(t,e)=>()=>(t&&(e=t(t=0)),e);var Sk=(t,e)=>{for(var n in e)bk(t,n,{get:e[n],enumerable:!0})};async function pi(t){let e=await t.openReader();try{return e.size}finally{await e.close()}}async function kt(t){return await pi(t)===0}async function ae(t){return new TextDecoder().decode(await Yt(t))}async function Yt(t){let e=await t.openReader();try{let n=new Uint8Array(e.size);for(let r=0;r<e.size;){let a=await e.read(r,Math.min(65536,e.size-r));n.set(a,r),r+=a.byteLength}return n}finally{await e.close()}}async function pe(t,e){let n=await t.openWriter();try{await n.write(e),await n.commit()}catch(r){throw await n.abort().catch(()=>{}),r}}async function Ie(t){if(U(t)){let e=0;for(let n of await t.list())e+=await Ie(n);return e}return await pi(t)}async function Ze(t){return await t.getLastModified?.()}function U(t){return t.kind==="directory"}var Ku=i(()=>{"use strict"});function Zt(t){en().installedPlatform=t}function _(){let{installedPlatform:t}=en();if(t===void 0)throw new Error("No WikiGraph runtime platform has been installed. Provide a runtime adapter before using wiki-graph-core.");return t}async function xt(t){if(typeof t!="string")return t;let e=await _().resources.getFile(t);if(e===void 0)throw new Error("Host file is unavailable");return e}async function J(t,e){let n=e.replaceAll("\\","/").split("/").filter(Boolean);if(n.some(o=>o==="."||o===".."))throw new TypeError(`Directory path must remain relative: ${e}`);let r=n.pop();if(!r)return;let a=t;for(let o of n){let s=await a.getDirectory(o);if(!s)return;a=s}return await a.getFile(r)}async function De(t,e){let n=wo(e),r=t;for(let a of n){let o=await r.getDirectory(a);if(!o)return;r=o}return r}async function Q(t,e){let n=wo(e),r=t;for(let a of n){let o=await r.getDirectory(a);if(o!==void 0){r=o;continue}try{r=await r.createDirectory(a)}catch(s){let d=await r.getDirectory(a);if(d===void 0)throw s;r=d}}return r}async function H(t,e){let n=wo(e),r=n.pop();if(!r)throw new TypeError("File name must remain relative");let a=await Q(t,n.join("/")),o=await a.getFile(r);if(o!==void 0)return o;try{return await a.createFile(r)}catch(s){let d=await a.getFile(r);if(d!==void 0)return d;throw s}}function wo(t){let e=t.replaceAll("\\","/");if(e.startsWith("/"))throw new TypeError(`Directory path must remain relative: ${t}`);let n=e.split("/").filter(Boolean);if(n.some(r=>r==="."||r===".."))throw new TypeError(`Directory path must remain relative: ${t}`);return n}function en(){let t=globalThis,e=t[zu];if(e!==void 0)return e;let n={storageContext:new So};return Object.defineProperty(t,zu,{configurable:!1,enumerable:!1,value:n,writable:!1}),n}function fi(t){en().installedStorage=t}async function tn(t,e){return t===void 0?await e():await en().storageContext.run(t,e)}function R(){let{installedStorage:t,storageContext:e}=en(),n=e.getStore()??t;if(n===void 0)throw new Error("No WikiGraph storage roots have been configured. Pass storage to WikiGraph or install process-default storage.");return n}var zu,So,y=i(()=>{"use strict";Ku();zu=Symbol.for("wiki-graph-core.runtime.v1");So=class{#e;#t;run(e,n){let r=this.#n();if(r!==void 0)return r.run(e,n);let a=this.#t;this.#t=e;try{return n()}finally{this.#t=a}}enterWith(e){let n=this.#n();n!==void 0?n.enterWith(e):this.#t=e}getStore(){return this.#n()?.getStore()??this.#t}#n(){if(this.#e!==void 0)return this.#e;let{installedPlatform:e}=en();if(e!==void 0)return this.#e=e.asyncContext.create(),this.#t!==void 0&&(this.#e.enterWith(this.#t),this.#t=void 0),this.#e}}});function yi(t){if(kk.test(t))throw new Error(`invalid template name ${t}`);let n=t.replace(xk,"").replace(wk,"");if(n.split("/").includes(".."))throw new Error(`invalid template name ${t}`);return`${n}.jinja`}var wk,kk,xk,jn=i(()=>{"use strict";y();wk=/\.jinja$/iu,kk=/^\.+\//u,xk=/^\/+/u});var ko=i(()=>{"use strict";y();jn()});import*as Vu from"async_hooks";import*as Yu from"crypto";import*as bi from"fs";import*as q from"fs/promises";import*as Zu from"os";import*as O from"path";import*as Ro from"process";import{Readable as el,Writable as Ek}from"stream";import{pipeline as Ik}from"stream/promises";import*as Co from"sqlite3";import*as tl from"yauzl";import*as nl from"yazl";import{Environment as vk,Loader as Rk}from"nunjucks";async function Xu(t,e,n){let r=Buffer.from(e),a=0;for(;a<r.byteLength;){let o=await t.write(r,a,r.byteLength-a,n===void 0?null:n+a);if(o.bytesWritten===0)throw new Error("File writer made no progress");a+=o.bytesWritten}}function rl(t,e,n){if(il(t),!Number.isSafeInteger(e)||e<0)throw new RangeError("File read length must be a non-negative safe integer");if(t>n||e>n-t)throw new RangeError("File read range exceeds the file size")}function il(t){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("File offset must be a non-negative safe integer")}function al(t,e){return`node-${t}:${Buffer.from(O.resolve(e),"utf8").toString("base64url")}`}function xo(t,e){let n=`node-${e}:`;if(!t.startsWith(n))return O.isAbsolute(t)?t:void 0;try{return Buffer.from(t.slice(n.length),"base64url").toString("utf8")}catch{return}}function Un(t){if(t.length===0||t==="."||t===".."||O.isAbsolute(t)||t.includes("/")||t.includes("\\"))throw new TypeError(`Directory child must be a relative name: ${t}`)}async function Ck(t,e){let n=(e.mode==="readonly"?qn.OPEN_READONLY:qn.OPEN_READWRITE|(e.create?qn.OPEN_CREATE:0))|qn.OPEN_FULLMUTEX;return new Io(await Tk(t,n))}async function Tk(t,e){let n=ol(t,"file");if(n===void 0)throw new TypeError("The Node database adapter requires a NodeFile");return await new Promise((r,a)=>{let o=new qn.Database(n,e,s=>{s?a(s):r(o)})})}async function _k(t){let e=ol(t,"file");if(e===void 0)throw new TypeError("The Node ZIP adapter requires a NodeFile");let n=await new Promise((o,s)=>{tl.open(e,{autoClose:!1,lazyEntries:!0},(d,c)=>{d||c===void 0?s(d??new Error("Cannot open ZIP")):o(c)})}),r=await new Promise((o,s)=>{let d=new Map,c=m=>{n.close(),s(m instanceof Error?m:new Error("Cannot scan ZIP central directory"))},u=()=>{n.off("error",c),o(d)};n.on("entry",m=>{m.fileName.endsWith("/")||d.set(m.fileName,m),n.readEntry()}),n.once("error",c),n.once("end",u),n.readEntry()}),a=!1;return{close:()=>(a||n.close(),a=!0,Promise.resolve()),copyEntry:async(o,s)=>{if(a)throw new Error("Cannot read a closed ZIP archive");let d=r.get(o);return d===void 0?!1:(await Pk(n,d,s),!0)},getEntrySize:o=>{if(a)throw new Error("Cannot read a closed ZIP archive");return Promise.resolve(r.get(o)?.uncompressedSize)},listEntries:()=>Promise.resolve([...r.keys()]),readEntryRange:async(o,s,d)=>{if(a)throw new Error("Cannot read a closed ZIP archive");let c=r.get(o);if(c!==void 0)return await Lk(n,c,s,d)},readEntry:async o=>{if(a)throw new Error("Cannot read a closed ZIP archive");let s=r.get(o);if(s!==void 0)return await Ak(n,s)}}}async function Pk(t,e,n){let r=await n.openWriter();try{let a=await gi(t,e);await sl(a,r),await r.commit()}catch(a){throw await r.abort().catch(()=>{}),a}}async function Ak(t,e){return await dl(await gi(t,e))}async function Lk(t,e,n,r){if(rl(n,r,e.uncompressedSize),r===0)return new Uint8Array;if(e.compressionMethod!==0){let o=await Ok(await gi(t,e),n,r);return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}let a=await dl(await gi(t,e,{decompress:null,decrypt:null,end:n+r,start:n}));return new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}async function Ok(t,e,n){let r=[],a=e+n,o=0,s=0;for await(let d of t){let c=Buffer.isBuffer(d)?d:Buffer.from(d),u=o+c.byteLength;if(u>e&&o<a){let m=c.subarray(Math.max(0,e-o),Math.min(c.byteLength,a-o));r.push(m),s+=m.byteLength}if(o=u,o>=a)break}if(s!==n)throw new Error("ZIP entry changed while reading its byte range");return Buffer.concat(r,s)}async function gi(t,e,n){return await new Promise((r,a)=>{let o=(s,d)=>{s||d===void 0?a(s??new Error(`Cannot read ZIP entry: ${e.fileName}`)):r(d)};n===void 0?t.openReadStream(e,o):t.openReadStream(e,n,o)})}async function Nk(t,e){let n=new nl.ZipFile,r=await t.openWriter(),a=n.outputStream,o=sl(a,r),s={cancelled:!1,complete:!1},d;try{d=Fk(e);let c=Wk(n,d,s);if(await Promise.race([c,o]),!s.complete)throw new Error("ZIP output ended before entry production completed");n.end(),await o,await r.commit()}catch(c){throw s.cancelled=!0,!s.complete&&d!==void 0&&Gk(d),a.destroyed||a.destroy(c instanceof Error?c:new Error("Cannot write ZIP archive")),await o.catch(()=>{}),await r.abort().catch(()=>{}),c}}async function Wk(t,e,n){for(;!n.cancelled;){let r=await e.next();if(n.cancelled)return;if(r.done){n.complete=!0;return}"file"in r.value?t.addReadStream(Dk(r.value.file),r.value.name,{compress:!1}):"data"in r.value?t.addBuffer(Buffer.from(r.value.data),r.value.name,{compress:!1}):t.addReadStream(Mk(r.value),r.value.name,{compress:!1,size:r.value.size})}}function Dk(t){return el.from((async function*(){let e=await t.openReader();try{for(let n=0;n<e.size;){let r=await e.read(n,Math.min(65536,e.size-n));n+=r.byteLength,yield r}}finally{await e.close()}})())}function ol(t,e){if(typeof t!="object"||t===null)return;let n=t;return n[To]===e&&typeof n.path=="string"?n.path:void 0}function Mk(t){return el.from((async function*(){for(let e=0;e<t.size;){let n=await t.read(e,Math.min(65536,t.size-e));e+=n.byteLength,yield n}})())}function Fk(t){let e=t[Symbol.asyncIterator];return e===void 0?t[Symbol.iterator]():e.call(t)}function Gk(t){if(t.return!==void 0)try{Promise.resolve(t.return()).catch(()=>{})}catch{}}async function sl(t,e){await Ik(t,new Ek({write:(n,r,a)=>{e.write(n).then(()=>a(),o=>a(o instanceof Error?o:new Error("Cannot stream ZIP archive")))}}))}async function dl(t){return await new Promise((e,n)=>{let r=[];t.on("data",a=>r.push(a)),t.once("error",n),t.once("end",()=>e(Buffer.concat(r)))})}function jk(){let t=globalThis.__WIKIGRAPH_DATA_DIR__;if(typeof t=="string"&&t!=="")return t;let e=Eo.cwd();for(;;){for(let r of[O.join(e,"data"),O.join(e,"packages","core","data")])try{if(bi.statSync(r).isDirectory())return r}catch{}let n=O.dirname(e);if(n===e)throw new Error("Could not locate data directory");e=n}}function _o(t=O.join(Zu.homedir(),".wikigraph")){let e=typeof t=="string"?t:t.libraryRoot,n=typeof t=="string"?O.join(t,"documents"):t.documentStoreRoot;return{library:new Me(e),documentStore:new Me(n)}}function ul(t){Zt(cl),fi(_o(t))}function ll(){try{_()}catch{Zt(cl)}try{R()}catch{fi(_o())}}async function Si(t,e){return await tn(t===void 0?void 0:_o(t),e)}var Eo,qn,To,se,Me,Io,cl,vo,ce=i(()=>{"use strict";ko();Eo=Ro.default??Ro,qn=Co.default??Co,To=Symbol.for("wiki-graph-sdk.node-resource.v1"),se=class{constructor(e,n=O.basename(e)){this.path=e;this.identity=al("file",e),this.name=n}path;kind="file";[To]="file";identity;name;async openReader(){let e=await q.open(this.path,"r"),n=!1;try{let r=await e.stat();if(!r.isFile())throw new Error("File reader requires a regular file");let{size:a}=r;return{size:a,close:async()=>{n||await e.close(),n=!0},read:async(o,s)=>{if(n)throw new Error("Cannot read from a closed FileReader");rl(o,s,a);let d=Buffer.allocUnsafe(s),c=0;for(;c<s;){let u=await e.read(d,c,s-c,o+c);if(u.bytesRead===0)throw new Error("File changed while reading its byte range");c+=u.bytesRead}return new Uint8Array(d.buffer,d.byteOffset,c)}}}catch(r){throw await e.close(),r}}async getLastModified(){try{return(await q.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async openWriter(){await q.mkdir(O.dirname(this.path),{recursive:!0});let e=`${this.path}.tmp-${Yu.randomUUID()}`,n=await q.open(e,"wx"),r=!1;return{write:async a=>{if(r)throw new Error("Cannot write to a closed FileWriter");await Xu(n,a)},writeAt:async(a,o)=>{if(r)throw new Error("Cannot write to a closed FileWriter");il(a),await Xu(n,o,a)},commit:async()=>{r||(await n.close(),await q.rename(e,this.path)),r=!0},abort:async()=>{r||(await n.close(),await q.rm(e,{force:!0})),r=!0}}}};Me=class t{constructor(e){this.path=e;this.identity=al("directory",e),this.name=O.basename(e)}path;kind="directory";[To]="directory";identity;name;async getFile(e){Un(e);let n=new se(O.join(this.path,e));try{return(await q.stat(n.path)).isFile()?n:void 0}catch{return}}async getLastModified(){try{return(await q.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async getDirectory(e){Un(e);let n=new t(O.join(this.path,e));try{return(await q.stat(n.path)).isDirectory()?n:void 0}catch{return}}async list(){return(await q.readdir(this.path,{withFileTypes:!0})).map(n=>n.isDirectory()?new t(O.join(this.path,n.name)):new se(O.join(this.path,n.name),n.name))}async createFile(e){Un(e),await q.mkdir(this.path,{recursive:!0});let n=new se(O.join(this.path,e));return await q.writeFile(n.path,"",{flag:"wx"}),n}async createDirectory(e){Un(e),await q.mkdir(this.path,{recursive:!0});let n=new t(O.join(this.path,e));return await q.mkdir(n.path),n}async remove(e,n){Un(e),await q.rm(O.join(this.path,e),{force:!0,recursive:n?.recursive===!0})}};Io=class{constructor(e){this.database=e}database;async close(){await new Promise((e,n)=>{this.database.close(r=>{r?n(r):e()})})}async execute(e){await new Promise((n,r)=>{this.database.exec(e,a=>{a?r(a):n()})})}async queryAll(e,n=[]){return await new Promise((r,a)=>{this.database.all(e,[...n],(o,s)=>{o?a(o):r(s)})})}async queryOne(e,n=[]){return await new Promise((r,a)=>{this.database.get(e,[...n],(o,s)=>{o?a(o):r(s)})})}async run(e,n=[]){await new Promise((r,a)=>{this.database.run(e,[...n],o=>{o?a(o):r()})})}};cl={asyncContext:{create:()=>new Vu.AsyncLocalStorage},database:{open:Ck},lifecycle:{instanceId:`node-process:${Eo.pid}`,isInstanceAlive:t=>{let e=/^node-process:(\d+)$/u.exec(t);if(e===null)return Promise.resolve(void 0);try{return Eo.kill(Number(e[1]),0),Promise.resolve(!0)}catch(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="ESRCH"?Promise.resolve(!1):Promise.resolve(!0)}}},resources:{getDirectory:t=>{let e=xo(t,"directory");return Promise.resolve(e===void 0?void 0:new Me(e))},getFile:t=>{let e=xo(t,"file");return Promise.resolve(e===void 0?void 0:new se(e))},resolveLegacyDirectory:t=>{let e=xo(t,"directory");return Promise.resolve(e===void 0?void 0:new Me(e))}},templates:{createEnvironment:t=>new vk(new vo,t)},zip:{open:_k,write:Nk}},vo=class extends Rk{#e;constructor(e){super(),this.#e=e}getSource(e){let n=yi(e),r=O.join(this.#e??jk(),n);return{noCache:!1,path:n,src:bi.readFileSync(r,"utf8")}}}});var Fe=i(()=>{"use strict"});function ml(t){return new TextEncoder().encode(t)}function Et(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}var ve=i(()=>{"use strict"});import{sha1 as Uk}from"@noble/hashes/legacy.js";import{sha256 as qk,sha512 as Bk}from"@noble/hashes/sha2.js";function oe(t){let e=Hk(t);return{update(n){return e.update(typeof n=="string"?ml(n):n),this},digest(n){let r=e.digest();return n==="hex"?Et(r):r}}}function Bn(t){let e=new Uint8Array(t);return globalThis.crypto.getRandomValues(e),e}function et(){if(typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();let t=Bn(16);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=Et(t);return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function Hk(t){switch(t){case"sha1":return Uk.create();case"sha256":return qk.create();case"sha512":return Bk.create()}}var F=i(()=>{"use strict";ve()});var wi=i(()=>{"use strict";F()});var hl=i(()=>{"use strict";y()});var fl=i(()=>{"use strict";hl()});var yl=i(()=>{"use strict"});function Ge(t){return t instanceof Error}function nn(t){let e=[],n=new Set,r=t;for(;r!==void 0&&!n.has(r);){if(n.add(r),r instanceof Error){gl(e,Xk(r)),r=r.cause;continue}gl(e,String(r));break}return e.join(": ")}function Xk(t){let e=t,n=t.message.trim(),r=typeof e.code=="string"&&e.code!==""?e.code:void 0;return r==="ENOENT"?"File not found (ENOENT)":r==="EACCES"||r==="EPERM"?`Permission denied (${r})`:r!==void 0&&Vk(n)?`${t.name} (${r})`:n===""?t.name:r===void 0?n:`${n} (${r})`}function Vk(t){return/(?:^|[\s:'"(=])\/(?:[^\s/]+\/)*[^\s/]+/u.test(t)||/(?:^|[\s:'"(=])[A-Za-z]:[\\/]/u.test(t)||/\bfile:\/\//iu.test(t)}function gl(t,e){let n=e.trim();if(n==="")return;let r=t.at(-1);if(r===void 0){t.push(n);return}if(!(r===n||r.includes(n))){if(n.includes(r)){t[t.length-1]=n;return}t.push(n)}}var he=i(()=>{"use strict";y()});var bl=i(()=>{"use strict";he()});var Sl=i(()=>{"use strict"});import{APICallError as PA}from"ai";var wl=i(()=>{"use strict";y()});var tt=i(()=>{"use strict";y()});var It,$n=i(()=>{"use strict";It=class{#e=0;#t;#n=[];constructor(e){if(!Number.isInteger(e)||e<1)throw new RangeError("concurrency must be a positive integer");this.#t=e}async use(e){await this.#r();try{return await e()}finally{this.#i()}}async#r(){if(this.#e<this.#t){this.#e+=1;return}await new Promise(e=>{this.#n.push(()=>{this.#e+=1,e()})})}#i(){this.#e-=1,this.#n.shift()?.()}}});var Ao=i(()=>{"use strict";tt()});var Lo=i(()=>{"use strict"});var kl=i(()=>{"use strict";y()});var Oo=i(()=>{"use strict"});import{generateText as rL,streamText as iL}from"ai";var El=i(()=>{"use strict";fl();yl();bl();Sl();wl();tt();jn();$n();wi();he();Ao();Lo();kl();Oo()});var Il=i(()=>{"use strict";El()});var Wo=i(()=>{"use strict";Il();Ao();Lo();Oo()});var tx,Do,vl,rn=i(()=>{"use strict";tx=Object.freeze(["serial-generation/editor-compress","serial-generation/editor-review","serial-generation/editor-review-guide","serial-generation/reader-choice","serial-generation/reader-extraction"]),Do=Object.freeze({compress:"serial-generation/editor-compress",review:"serial-generation/editor-review",reviewGuide:"serial-generation/editor-review-guide"}),vl=Object.freeze({choice:"serial-generation/reader-choice",extraction:"serial-generation/reader-extraction"})});var X,Z=i(()=>{"use strict";X=class extends Error{code;details;constructor(e,n,r={},a={}){super(n,a),this.name="WikiGraphError",this.code=e,this.details=r}}});var Mo=i(()=>{"use strict"});async function rx(t){try{return await kt(t)}catch(e){if(Ge(e)&&e.code==="ENOENT")return!0;throw e}}function S(t,e){let n=t[e];if(typeof n!="number")throw new TypeError(`Expected ${e} to be a number`);return n}function I(t,e){let n=t[e];if(typeof n!="string")throw new TypeError(`Expected ${e} to be a string`);return n}var nx,N,Fo,w=i(()=>{"use strict";y();he();nx=900*1e3;N=class t{#e;#t;#n;#r;#i=!1;#u=Promise.resolve();#d=0;constructor(e,n={}){this.#e=e,this.#t=n.onWrite,this.#n=_().asyncContext.create()}static async open(e,n,r){let a=await xt(e),o=r.mode==="readwrite"&&r.create&&n.trim()!==""&&await rx(a),s=r.mode==="readonly"?await _().database.open(a,{mode:"readonly"}):await _().database.open(a,{create:r.create,mode:"readwrite"}),d;try{return d=new t(new Fo(s),r),await d.#o(`PRAGMA busy_timeout = ${nx}`),r.mode==="readwrite"&&n.trim()!==""&&(await d.#o(n),o&&d.#c()),d}catch(c){throw d===void 0?await s.close().catch(()=>{}):await d.close().catch(()=>{}),c}}static async initialize(e,n){let r=await t.open(e,"",{create:!0,mode:"readwrite"});try{n.trim()!==""&&await r.#o(n)}finally{await r.close()}}async queryAll(e,n,r){return await this.#a(async()=>(this.#s(),(await this.#m(e,n)).map(r)))}async queryOne(e,n,r){return await this.#a(async()=>{this.#s();let a=await this.#p(e,n);return a===void 0?void 0:r(a)})}async run(e,n){await this.#a(async()=>{this.#s(),await this.#h(e,n),this.#c()})}async execute(e){await this.#a(async()=>{this.#s(),await this.#o(e),this.#c()})}async transaction(e){return await this.#a(async()=>{this.#s();let n=this.#d===0,r=this.#r??Symbol("database transaction scope");n&&(await this.#o("BEGIN IMMEDIATE"),this.#r=r),this.#d+=1;try{let a=await this.#n.run(r,e);return n&&await this.#o("COMMIT"),a}catch(a){throw n&&await this.#o("ROLLBACK"),a}finally{this.#d-=1,n&&(this.#r=void 0)}})}async flush(){await this.#a(()=>{this.#s()})}async close(){await this.#a(async()=>{this.#i||(await this.#l(),this.#i=!0)})}async getLastInsertRowId(){let e=await this.queryOne("SELECT last_insert_rowid() AS row_id",void 0,n=>S(n,"row_id"));if(e===void 0)throw new Error("Could not read last_insert_rowid()");return e}#s(){if(this.#i)throw new Error("Database is already closed")}async#a(e){let n=this.#n.getStore();if(n!==void 0&&n===this.#r)return await e();let r=this.#u.then(e);return this.#u=r.then(()=>{},()=>{}),await r}#c(){this.#t?.()}async#l(){await this.#e.close()}async#o(e){await this.#e.execute(e)}async#m(e,n){return await this.#e.queryAll(e,n)}async#p(e,n){return await this.#e.queryOne(e,n)}async#h(e,n){await this.#e.run(e,n)}};Fo=class{#e;constructor(e){this.#e=e}async close(){await this.#e.close()}async execute(e){await this.#e.execute(e)}async queryAll(e,n){return[...await this.#e.queryAll(e,n)]}async queryOne(e,n){return await this.#e.queryOne(e,n)}async run(e,n){await this.#e.run(e,n)}}});async function vt(){let t=R().library,e=xi.get(t.identity);if(e!==void 0){await e;return}let n=ax(t);xi.set(t.identity,n);try{await n}finally{xi.get(t.identity)===n&&xi.delete(t.identity)}}async function Ci(){let t=await J(R().library,"core.sqlite");if(t===void 0||await Ti(t))return 0;let e=await N.open(t,"",{mode:"readonly"});try{return await an(e,"schema_versions")?await e.queryOne("SELECT version FROM schema_versions WHERE scope = ?",["home"],n=>S(n,"version"))??1:1}finally{await e.close()}}async function ax(t){let e=await Ci();if(e>Go)throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`);let n=await H(t,"core.sqlite");if(e===0){await Ei(n,Go);return}for(;e<Go;)switch(e){case 1:await Rl(t),await Ei(n,2),e=2;break;case 2:await Rl(t),await Ei(n,3),e=3;break;case 3:await ox(n),await Ei(n,4),e=4;break;default:throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`)}}async function Rl(t){await Al(t),await Pl(t)}async function ox(t){let e=R().library;await Al(e),await sx(t),await Pl(e)}async function sx(t){let e=await N.open(t,"",{create:!1,mode:"readwrite"});try{if(!await an(e,"libraries"))return;let n=await vi(e,"libraries"),r=n.has("folder_identity")?"folder_identity":n.has("folder_path")?"folder_path":void 0;if(r===void 0)throw new Error("Cannot migrate library registry without a folder reference.");let a=await e.queryAll(`SELECT id, ${r} AS folder_reference FROM libraries ORDER BY id`,void 0,s=>({id:S(s,"id"),reference:I(s,"folder_reference")})),o=[];for(let s of a){let d=_().resources,c=r==="folder_identity"||d.resolveLegacyDirectory===void 0?await d.getDirectory(s.reference):await d.resolveLegacyDirectory(s.reference);if(c===void 0)throw new Error(`Cannot migrate unavailable library Directory for registry id ${s.id}.`);o.push({id:s.id,identity:c.identity})}await e.transaction(async()=>{n.has("folder_identity")||await e.run("ALTER TABLE libraries RENAME COLUMN folder_path TO folder_identity");for(let s of o)await e.run("UPDATE libraries SET folder_identity = ? WHERE id = ?",[s.identity,s.id])})}finally{await e.close()}}async function Ei(t,e){let n=await N.open(t,"",{create:!0,mode:"readwrite"});try{await n.execute(ix),await n.run(`INSERT INTO schema_versions (scope, version, updated_at)
|
|
7
7
|
VALUES (?, ?, ?)
|
|
8
8
|
ON CONFLICT(scope) DO UPDATE SET
|
|
9
9
|
version = excluded.version,
|
|
10
|
-
updated_at = excluded.updated_at`,["home",e,new Date().toISOString()])}finally{await n.close()}}async function
|
|
10
|
+
updated_at = excluded.updated_at`,["home",e,new Date().toISOString()])}finally{await n.close()}}async function Pl(t){await Jn(await t.getDirectory("cache"),["search-sessions.sqlite","continuation-cursors.sqlite","cache.sqlite"]);let e=await t.getDirectory("staging");await Jn(e,["library","work"]),await Ii(e,"staging.sqlite");let n=await t.getDirectory("tmp");await Ii(n,"gc.sqlite"),await Ii(n,"wikg-coordinator.sqlite"),await Jn(n,["gc.last-run"]);let r=await t.getDirectory("jobs");await Jn(r,["cache","work"]),await Ii(r,"job.sqlite");let a=R().documentStore,o;try{o=await a.list()}catch(s){if(Ge(s)&&s.code==="ENOENT")return;throw s}for(let s of o)(s.name===".wikg-work"||s.name===".wikg-cache"||s.name.startsWith(".wikg-session-")||s.name.startsWith(".wikg-upgrade-"))&&await a.remove(s.name,{recursive:U(s)})}async function Ii(t,e){await Jn(t,[e,`${e}-wal`,`${e}-shm`])}async function Jn(t,e){if(t===void 0)return;let n=new Map((await t.list()).map(r=>[r.name,r]));for(let r of e){let a=n.get(r);a!==void 0&&await t.remove(r,{recursive:U(a)})}}async function Al(t){await Tl(await J(t,"core.sqlite"),[["library_locks","Cannot upgrade home with active library locks."],["state_locks","Cannot upgrade home with active state locks."]]),await Tl(await J(t,"tmp/gc.sqlite"),[["gc_locks","Cannot upgrade home with an active GC lock."]]),await dx(await J(t,"jobs/job.sqlite")),await Cl(await J(t,"staging/staging.sqlite"),"legacy coordinator"),await Cl(await J(t,"tmp/wikg-coordinator.sqlite"),"coordinator")}async function dx(t){if(t===void 0||await Ti(t))return;let e=await N.open(t,"",{mode:"readonly"});try{if(await an(e,"build_worker_lease")){let n=await vi(e,"build_worker_lease"),a=["owner_id","owner_pid"].filter(s=>n.has(s)).map(s=>`${s} IS NOT NULL`).join(" OR ");if(await e.queryOne(`SELECT 1 AS active FROM build_worker_lease
|
|
11
11
|
WHERE heartbeat_at IS NOT NULL
|
|
12
12
|
AND heartbeat_at >= ?
|
|
13
13
|
${a===""?"":`AND (${a})`}
|
|
14
|
-
LIMIT 1`,[Date.now()-
|
|
15
|
-
FROM archive_owners`,void 0,o=>({heartbeatAt:S(o,"heartbeat_at"),hostInstanceId:typeof o.host_instance_id=="string"?o.host_instance_id:void 0}));for(let o of a){if(o.hostInstanceId===void 0){if(
|
|
14
|
+
LIMIT 1`,[Date.now()-Ri],()=>!0)===!0)throw Kn("Cannot upgrade home with an active build worker.")}}finally{await e.close()}}async function Cl(t,e){if(t===void 0||await Ti(t))return;let n=await N.open(t,"",{mode:"readonly"});try{if(await an(n,"archive_owners")){let r=await vi(n,"archive_owners"),a=await n.queryAll(`SELECT heartbeat_at${r.has("host_instance_id")?", host_instance_id":""}
|
|
15
|
+
FROM archive_owners`,void 0,o=>({heartbeatAt:S(o,"heartbeat_at"),hostInstanceId:typeof o.host_instance_id=="string"?o.host_instance_id:void 0}));for(let o of a){if(o.hostInstanceId===void 0){if(_l(o.heartbeatAt))throw Kn(`Cannot upgrade home with active ${e} state.`);continue}let s=await _().lifecycle.isInstanceAlive(o.hostInstanceId);if(s===!0||s===void 0&&_l(o.heartbeatAt))throw Kn(`Cannot upgrade home with active ${e} state.`)}}for(let r of["entry_locks","entry_sqlite_leases","archive_commit_locks"]){if(!await an(n,r)||!(await vi(n,r)).has("heartbeat_at"))continue;if(await n.queryOne(`SELECT 1 AS active FROM ${r} WHERE heartbeat_at >= ? LIMIT 1`,[Date.now()-Ri],()=>!0)===!0)throw Kn(`Cannot upgrade home with active ${e} state.`)}}finally{await n.close()}}async function Tl(t,e){if(t===void 0||await Ti(t))return;let n=await N.open(t,"",{mode:"readonly"});try{for(let[r,a]of e){if(!await an(n,r))continue;if(await n.queryOne(`SELECT 1 AS active FROM ${r} WHERE heartbeat_at >= ? LIMIT 1`,[Date.now()-Ri],()=>!0)===!0)throw Kn(a)}}finally{await n.close()}}function Kn(t){return new X("home_upgrade_blocked",t)}function _l(t){return t!==void 0&&Date.now()-t<=Ri}async function Ti(t){return await kt(t)}async function vi(t,e){return new Set(await t.queryAll(`PRAGMA table_info(${e})`,void 0,n=>I(n,"name")))}async function an(t,e){return await t.queryOne("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ?",[e],()=>!0)===!0}var Go,Ri,ix,xi,_i=i(()=>{"use strict";y();he();Z();w();Go=4,Ri=300*1e3,ix=`
|
|
16
16
|
CREATE TABLE IF NOT EXISTS schema_versions (
|
|
17
17
|
scope TEXT PRIMARY KEY,
|
|
18
18
|
version INTEGER NOT NULL,
|
|
19
19
|
updated_at TEXT NOT NULL
|
|
20
20
|
);
|
|
21
|
-
`,
|
|
22
|
-
`,
|
|
21
|
+
`,xi=new Map});async function K(t,e,n={create:!0,mode:"readwrite"}){await vt();let r=await H(R().library,t);return n.mode==="readonly"?await zn(r,e,n):await zn(r,e,n)}async function zn(t,e,n={create:!0,mode:"readwrite"}){let r=await xt(t);return n.mode==="readonly"?await N.open(r,e,n):await N.open(r,e,n)}var Ll=i(()=>{"use strict";y();_i();w()});function Ai(...t){let e=[];for(let n of t)for(let r of n.replaceAll("\\","/").split("/"))if(!(r===""||r==="."))if(r===".."){if(e.length===0)throw new TypeError("Relative path escapes its root");e.pop()}else e.push(r);return e.join("/")}function jo(t){return Ai(t).split("/").at(-1)??""}var Rt=i(()=>{"use strict"});var Qn=i(()=>{"use strict";Rt()});var Ol=i(()=>{"use strict"});function on(t){let e=new Set(Object.values(t));return n=>e.has(n)}function Xn(t,e){let n=on(t);return r=>{if(n(r))return r;throw new Error(`Unknown ${e}: ${r}`)}}var Uo=i(()=>{"use strict"});var fe,Nl,qo,Re,Wl,Li,Ce=i(()=>{"use strict";Uo();fe=(a=>(a.Verbatim="verbatim",a.Detailed="detailed",a.Focused="focused",a.Relevant="relevant",a))(fe||{}),Nl=on(fe),qo=Xn(fe,"chunk retention"),Re=(r=>(r.Critical="critical",r.Important="important",r.Helpful="helpful",r))(Re||{}),Wl=on(Re),Li=Xn(Re,"chunk importance")});var Bo=i(()=>{"use strict";Ce()});function nt(t){let e=0,n=!1;for(let r of t.trim()){if(cx.test(r)){e+=1,n=!1;continue}if(ux.test(r)){n||(e+=1),n=!0;continue}n&&lx.test(r)||(n=!1)}return e}var cx,ux,lx,rt=i(()=>{"use strict";cx=new RegExp("\\p{Script=Han}","u"),ux=/[\p{Letter}\p{Number}]/u,lx=new RegExp("\\p{Mark}","u")});var Ml=i(()=>{"use strict";rt();Ce()});var Oi=i(()=>{"use strict"});var $o=i(()=>{"use strict";Qn();Ce();Bo();Ml();Oi()});var Fl=i(()=>{"use strict";Qn();Ol();$o()});var Jo=i(()=>{"use strict";Fl();Bo();$o();Oi()});var Ni=i(()=>{"use strict";y();Rt()});var Ko=i(()=>{"use strict"});var jl=i(()=>{"use strict";Rt();Ni()});var Ul=i(()=>{"use strict";rt()});var zo=i(()=>{"use strict"});var Qo=i(()=>{"use strict";Rt();he();Ko();Ni();jl();Ul();zo()});var ql=i(()=>{"use strict";Rt();Ni();Qo()});var Xo=i(()=>{"use strict";ql();Ko();Qo();zo()});import{z as ye}from"zod";var Vo,je,Bl,Yo,Vn=i(()=>{"use strict";Vo=["epub","pdf","txt","markdown"],je=1,Bl=ye.enum(Vo),Yo=ye.object({version:ye.literal(je),sourceFormat:Bl,title:ye.string().min(1).nullable().default(null),authors:ye.array(ye.string().min(1)),language:ye.string().min(1).nullable(),identifier:ye.string().min(1).nullable(),publisher:ye.string().min(1).nullable(),publishedAt:ye.string().min(1).nullable(),description:ye.string().min(1).nullable()})});function Hl(t,e="chapter key"){if(t===""||t==="."||t===".."||t.includes("/"))throw new Error(`Invalid ${e}: chapter paths do not support empty, '.', '..', or relative segments.`);if(!/^[a-z0-9][a-z0-9-]*$/u.test(t))throw new Error(`Invalid ${e}: ${t}. Use lowercase letters, numbers, and hyphens.`);if(/^\d+$/u.test(t))throw new Error(`Invalid ${e}: numeric chapter keys are not accepted.`);if(Sx.has(t))throw new Error(`Invalid ${e}: ${t} is reserved.`);return t}var Sx,ge=i(()=>{"use strict";ve();F();Sx=new Set(["tree","source","summary","title","state","chunk","entity","triple","cover","meta","job","help"])});import{z as Ue}from"zod";var it,Zo,$l,es=i(()=>{"use strict";ge();it=1,Zo=Ue.object({key:Ue.string().min(1).transform(t=>Hl(t)).optional(),title:Ue.string().min(1).nullable().optional(),serialId:Ue.number().int().nonnegative().optional(),children:Ue.lazy(()=>Ue.array(Zo))}),$l=Ue.object({version:Ue.literal(it),items:Ue.array(Zo)})});function Te(t){let e=[];for(let n of t.replaceAll("\\","/").trim().split("/"))n===""||n==="."||(n===".."?e.pop():e.push(n));return e.join("/")}function wx(t){let[e]=t.split("#",1);return Te(e??"")}function ts(t){if(t===void 0)return;let e=t.startsWith("#")?t.slice(1):t;return e===""?void 0:e}function Yn(t){let[e,n]=t.split("#",2);return{path:Te(e??""),fragment:ts(n)}}function kx(t){return t.split("/").slice(0,-1).join("/")}function xx(...t){return t.filter(Boolean).join("/")}var Wi,Zn=i(()=>{"use strict";y();F();Wi=class t{#e;#t;#n;#r;constructor(e,n,r,a){this.#e=e,this.#n=n,this.#t=r,this.#r=a}static async open(e){let n=await e.openReader(),r=oe("sha256");try{for(let s=0;s<n.size;){let d=await n.read(s,Math.min(65536,n.size-s));r.update(d),s+=d.byteLength}}finally{await n.close()}let a=r.digest("hex"),o=await _().zip.open(e);try{let s=new Map;for(let d of await o.listEntries()){let c=Te(d);c!==""&&s.set(c,d)}return new t(e,o,s,a)}catch(s){throw await o.close(),s}}close(){return this.#n.close()}hasEntry(e){return this.#t.has(Te(e))}listEntries(){return[...this.#t.keys()]}async readText(e){return new TextDecoder().decode(await this.readBuffer(e))}async readBuffer(e){let n=this.#i(e),r=await this.#n.readEntry(n);if(r===void 0)throw new Error(`EPUB entry does not exist: ${Te(e)}`);return r}resolveRelativePath(e,n){let r=wx(n);if(r==="")throw new Error(`Invalid EPUB href: ${n}`);return Te(xx(kx(Te(e)),r))}createSectionId(e,n){let r=Te(e);return n===void 0||n===""?r:`${r}#${n}`}createSyntheticSectionId(e,n){let r=Te(e);return`toc:${oe("sha1").update(`${r}:${n??""}`).digest("hex").slice(0,10)}`}get name(){return this.#e.name}get digest(){return this.#r}#i(e){let n=Te(e),r=this.#t.get(n);if(r===void 0)throw new Error(`EPUB entry does not exist: ${n}`);return r}}});import{parseDocument as Ex}from"htmlparser2";async function Vl(t,e){let n=new Map;for(let[r,a]of e.entries()){let o=await Yl(t,r),s=Zl(o,a);for(let d of a){let c=s.get(d.id)??"";n.set(d.id,{hasContent:c.trim()!=="",wordsCount:nt(c)})}}return n}function Rx(t){let e=new Map;for(let[n,r]of t.entries())for(let a of r)e.set(a.id,{path:n,targets:r});return e}async function Yl(t,e){return await t.readText(e)}function Zl(t,e){let n=em(t,e,!1);return new Map([...n.entries()].map(([r,a])=>[e[r].id,a.text]))}function Cx(t,e,n){let r=em(t,e,!0),a=e.findIndex(s=>s.id===n),o=r.get(a);if(o===void 0)throw new Error("EPUB section content could not be parsed.");return o}function em(t,e,n){let r=new Map,a=new Map,o=[...e],d=o[0]?.fragment===void 0&&o[0]!==void 0?0:-1;o.forEach((g,C)=>{a.set(C,[]),g.fragment!==void 0&&!r.has(g.fragment)&&r.set(g.fragment,C)});let c=Ex(t,{decodeEntities:!0}),u=(c.children??[]).find(zl);if(u===void 0){if(n)throw new Error("EPUB XHTML document has no root element for CFI.");m(c,"")}else m(u,"");return new Map([...a.entries()].map(([g,C])=>{let L=_x(C);return[g,{segments:L.segments,text:L.text}]}));function m(g,C){if(Kl(g)){if(d<0||d>=o.length)return;let j=g.data??"";if(j==="")return;let ie=o[d],wt=ie?.spineIndex;if(n&&wt===void 0)throw new Error(`EPUB section ${ie?.id??"unknown"} cannot produce a CFI locator.`);let mi=n&&wt!==void 0?Xl(wt,C,0,j.length):ns;f(d,j,mi,n?0:void 0,n?j.length:void 0);return}let L=Lx(g);if(L===void 0){b(g,C);return}if(vx.has(L))return;let z=C,B=g.attribs?.id??g.attribs?.["xml:id"];if(B!==void 0){let j=r.get(B);j!==void 0&&j>d&&(d=j)}L==="br"&&k(d,`
|
|
22
|
+
`,z),b(g,z),Ix.has(L)&&k(d,`
|
|
23
23
|
|
|
24
|
-
`,
|
|
24
|
+
`,z)}function b(g,C){let L=0,z=new Map;for(let B of g.children??[]){if(Kl(B)){if(d<0||d>=o.length)continue;let ie=B.data??"";if(ie==="")continue;let wt=L*2+1,mi=z.get(wt)??0;z.set(wt,mi+ie.length);let gk=Ql(C,wt,!0);v(B,gk,mi,ie.length);continue}if(!zl(B))continue;let j=Ql(C,L,!1,B.attribs?.id??B.attribs?.["xml:id"]);L+=1,m(B,j)}}function v(g,C,L,z){if(d<0||d>=o.length)return;let B=g.data??"",j=o[d],ie=j?.spineIndex;if(n&&ie===void 0)throw new Error(`EPUB section ${j?.id??"unknown"} cannot produce a CFI locator.`);f(d,B,n&&ie!==void 0?Xl(ie,C,L,L+z):ns,n?L:void 0,n?L+z:void 0)}function f(g,C,L,z,B){let j=a.get(g);j!==void 0&&j.push({locator:L,...B===void 0?{}:{locatorEnd:B},...z===void 0?{}:{locatorStart:z},text:C})}function k(g,C,L){if(g<0||g>=o.length)return;let z=o[g],B=z?.spineIndex;if(n&&B===void 0)throw new Error(`EPUB section ${z?.id??"unknown"} cannot produce a CFI locator.`);f(g,C,n&&B!==void 0?Nx(B,L):ns)}}function Tx(t,e){let n=[],r=0;for(let a of t){let o=r;r+=Array.from(a.text).length,o!==r&&n.push({artifactDigest:e,locator:a.locator,sourceEnd:r,sourceStart:o})}return n}function _x(t){let e=[];for(let c of t){let u=Array.from(c.text),m=0;for(let b=0;b<u.length;b+=1){let v=u[b],f=c.locatorStart===void 0?void 0:c.locatorStart+m;m+=v.length;let k=c.locatorEnd===void 0||c.locatorStart===void 0?void 0:c.locatorStart+m;v==="\r"&&u[b+1]===`
|
|
25
25
|
`?(m+=1,k=c.locatorStart===void 0?void 0:c.locatorStart+m,e.push({baseLocator:c.locator,char:`
|
|
26
|
-
`,locator:
|
|
27
|
-
`){if(r+=1,r>2)continue}else r=0;n.push(c)}let a=0;for(;a<n.length&&n[a].char.trim()==="";)a+=1;let o=n.length;for(;o>a&&n[o-1].char.trim()==="";)o-=1;let s=n.slice(a,o),d=[];for(let c of s){let u=d.at(-1);u!==void 0&&u.locatorBase===c.baseLocator&&u.locatorEnd===c.locatorStart&&u.locatorStart!==void 0&&c.locatorEnd!==void 0?d[d.length-1]={locatorBase:u.locatorBase,locator:Zo(u.locatorBase??u.locator,u.locatorStart,c.locatorEnd),locatorEnd:c.locatorEnd,locatorStart:u.locatorStart,text:u.text+c.char}:u!==void 0&&u.locatorBase===c.baseLocator&&u.locatorStart===void 0&&c.locatorStart===void 0?d[d.length-1]={locatorBase:u.locatorBase,locator:u.locator,text:u.text+c.char}:d.push({locatorBase:c.baseLocator,locator:c.locator,...c.locatorEnd===void 0?{}:{locatorEnd:c.locatorEnd},...c.locatorStart===void 0?{}:{locatorStart:c.locatorStart},text:c.char})}return{segments:d,text:s.map(c=>c.char).join("")}}function Zo(t,e,n){if(e===void 0||n===void 0)return t;let r=t.cfi;if(typeof r!="string")throw new Error("EPUB text mapping is missing a CFI locator.");let a=gx(r);if(a===void 0)throw new Error("EPUB text mapping has an invalid CFI range locator.");return{...t,cfi:`epubcfi(${a.parentPath},${jl(a.startPath,e)},${jl(a.endPath,n)})`}}function gx(t){if(!t.startsWith("epubcfi(")||!t.endsWith(")"))return;let e=bx(t.slice(8,-1));if(e.length!==3||e.some(o=>o===""))return;let[n,r,a]=e;if(!(n===void 0||r===void 0||a===void 0))return{endPath:a,parentPath:n,startPath:r}}function bx(t){let e=[],n=0,r=0,a=!1;for(let o=0;o<t.length;o+=1){let s=t[o];if(a){a=!1;continue}if(s==="^"){a=!0;continue}if(s==="["){r+=1;continue}if(s==="]"){r-=1;continue}s===","&&r===0&&(e.push(t.slice(n,o)),n=o+1)}return e.push(t.slice(n)),e}function jl(t,e){if(!/:\d+$/u.test(t))throw new Error("EPUB text mapping has an invalid CFI offset.");return t.replace(/:\d+$/u,`:${e}`)}function Sx(t){return t.name?.toLowerCase()}function Ul(t){return t.type==="text"}function ql(t){return t.name!==void 0&&t.type!=="directive"}function Bl(t,e,n,r){let a=n?e:(e+1)*2,o=n||r===void 0?"":`[${Ix(r)}]`;return`${t}/${a}${o}`}function Hl(t,e,n,r){let a=Ql(t),{parentPath:o,textPath:s}=wx(e),d=o===""?a:`${a}!${o}`,c=o===""?`!${s}:${n}`:`${s}:${n}`,u=o===""?`!${s}:${r}`:`${s}:${r}`;return{cfi:`epubcfi(${d},${c},${u})`}}function wx(t){let e=t.lastIndexOf("/");if(e<0||e===t.length-1)throw new Error(`EPUB text mapping has an invalid CFI path: ${t}`);return{parentPath:t.slice(0,e),textPath:t.slice(e)}}function kx(t,e){return{cfi:`epubcfi(${xx(t)}${e})`}}function xx(t){return`${Ql(t)}!`}function Ql(t){return`/6/${(t+1)*2}`}function Ix(t){return[...t].map(e=>"[]^(),;=".includes(e)?`^${e}`:e).join("")}var lx,mx,Yo,Oi,Xl=i(()=>{"use strict";nt();lx=new Set(["address","article","aside","blockquote","br","dd","div","dl","dt","figcaption","figure","footer","h1","h2","h3","h4","h5","h6","header","hr","li","main","nav","ol","p","pre","section","table","td","th","tr","ul"]),mx=new Set(["script","style"]),Yo={},Oi=class{#e;#t;constructor(e,n){this.#e=e,this.#t=px(n)}async openSection(e){let n=this.#t.get(e);return n===void 0?[]:[(await this.#n(n.path,n.targets)).get(e)??""]}async openSectionWithProvenance(e,n){let r=this.#t.get(e);if(r===void 0)return{stream:[]};if(r.targets.find(c=>c.id===e)?.spineIndex===void 0)throw new Error(`EPUB section ${e} is not associated with a spine item.`);let o=await this.#e.readText(r.path),s=hx(o,r.targets,e),d=fx(s.segments,n.digest);if(s.text.length>0&&d.length===0)throw new Error(`EPUB section ${e} produced text without provenance mappings.`);return{provenance:{artifacts:[n],mappings:d},stream:[s.text]}}async#n(e,n){let r=await Jl(this.#e,e);return Kl(r,n)}}});import{SaxesParser as Ex}from"saxes";function on(t){let e=new Ex({xmlns:!1}),n=[],r;if(e.on("opentag",a=>{let o={name:a.name,attributes:Object.fromEntries(Object.entries(a.attributes).map(([d,c])=>[d,String(c)])),children:[],text:""},s=n[n.length-1];s===void 0?r=o:s.children.push(o),n.push(o)}),e.on("text",a=>{let o=n[n.length-1];o!==void 0&&(o.text+=a)}),e.on("cdata",a=>{let o=n[n.length-1];o!==void 0&&(o.text+=a)}),e.on("closetag",()=>{n.pop()}),e.write(t).close(),r===void 0)throw new Error("XML document is empty");return Vl(r)}function ge(t,e){return t.children.find(n=>er(n.name)===e)}function Ue(t,e){return t.children.filter(n=>er(n.name)===e)}function ee(t,e){return t.attributes[e]}function Zn(t){let e=t.text;for(let n of t.children)e+=Zn(n);return e}function er(t){let e=t.indexOf(":");return e===-1?t:t.slice(e+1)}function Vl(t){return{name:t.name,attributes:Object.freeze({...t.attributes}),children:Object.freeze(t.children.map(Vl)),text:t.text}}var Ni=i(()=>{"use strict"});async function Zl(t){let e=await Cx(t),n=on(await t.readText(e)),r=Tx(ee(n,"version")),a=ge(n,"metadata"),o=ge(n,"manifest"),s=ge(n,"spine"),d=ge(n,"guide"),c=Px(t,e,o),u=new Map([...c.values()].map(C=>[C.path,C])),m=Ax(s,c),b=Lx(t,e,d),v=_x(a),f=Ox(c),k=Nx(c,s),g=Wx(c,a);return{version:r,opfPath:e,metadata:{...v,version:Ge,sourceFormat:"epub"},manifest:c,manifestByPath:u,spine:m,navPath:f,ncxPath:k,coverPath:g?.path,coverMediaType:g?.mediaType,guideNonContentPaths:b}}async function Cx(t){let e=on(await t.readText("META-INF/container.xml")),r=ge(e,"rootfiles")?.children.find(o=>er(o.name)==="rootfile"),a=r===void 0?void 0:ee(r,"full-path");if(a===void 0||a.trim()==="")throw new Error("EPUB container.xml does not contain an OPF rootfile");return a}function Tx(t){return t?.trim().startsWith("3")===!0?3:2}function _x(t){if(t===void 0)return Yl();let e=Rt(t,"title"),n=Rt(t,"creator"),r=Rt(t,"language"),a=Rt(t,"identifier"),o=Rt(t,"publisher"),s=Rt(t,"date"),d=Rt(t,"description");return{...Yl(),title:e[0]??null,authors:[...n],language:r[0]??null,identifier:a[0]??null,publisher:o[0]??null,publishedAt:s[0]??null,description:d[0]??null}}function Yl(){return{version:Ge,sourceFormat:"epub",title:null,authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null}}function Rt(t,e){return t.children.filter(n=>er(n.name)===e).map(n=>Mx(Zn(n))).filter(n=>n!==void 0)}function Px(t,e,n){let r=new Map;if(n===void 0)return r;for(let a of Ue(n,"item")){let o=ee(a,"id"),s=ee(a,"href"),d=ee(a,"media-type")??"";o===void 0||s===void 0||r.set(o,{id:o,path:t.resolveRelativePath(e,s),mediaType:d,properties:new Set((ee(a,"properties")??"").split(/\s+/u).map(c=>c.trim().toLowerCase()).filter(c=>c!==""))})}return r}function Ax(t,e){return t===void 0?[]:Ue(t,"itemref").map((n,r)=>{let a=ee(n,"idref");if(a===void 0)return;let o=e.get(a);if(!(o===void 0||o.mediaType!=="application/xhtml+xml"&&o.mediaType!=="text/html"))return{idref:a,path:o.path,mediaType:o.mediaType,spineIndex:r}}).filter(n=>n!==void 0)}function Lx(t,e,n){let r=new Set;if(n===void 0)return r;for(let a of Ue(n,"reference")){let o=(ee(a,"type")??"").trim().toLowerCase();if(!Rx.has(o))continue;let s=ee(a,"href");s===void 0||s.trim()===""||r.add(t.resolveRelativePath(e,Vn(s).path))}return r}function Ox(t){for(let e of t.values())if(e.properties.has("nav"))return e.path}function Nx(t,e){let n=e===void 0?void 0:ee(e,"toc");if(n!==void 0)return t.get(n)?.path;for(let r of t.values())if(r.mediaType==="application/x-dtbncx+xml")return r.path}function Wx(t,e){for(let r of t.values())if(r.properties.has("cover-image")&&r.mediaType.startsWith("image/"))return r;let n=Dx(e);if(n!==void 0){let r=t.get(n);if(r?.mediaType.startsWith("image/")===!0)return r}for(let r of vx){let a=t.get(r);if(a?.mediaType.startsWith("image/")===!0)return a}for(let r of t.values())if(r.mediaType.startsWith("image/")&&Do(r.path).toLowerCase().includes("cover"))return r}function Dx(t){if(t!==void 0)for(let e of Ue(t,"meta")){if((ee(e,"name")??"").trim().toLowerCase()!=="cover")continue;let r=ee(e,"content");if(r!==void 0&&r.trim()!=="")return r.trim()}}function Mx(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var vx,Rx,es=i(()=>{"use strict";vt();Xn();Yn();Ni();vx=["cover-image","coverimg","cover-img","cover"],Rx=new Set(["cover","titlepage","other.titlepage"])});import{parseDocument as Fx}from"htmlparser2";async function tm(t,e){let n=await jx(t,e)??await Ux(t,e)??[];if(n.length===0)return em(e,new Set);let r=im(n),a=em(e,r);return a.length===0?n:[...n,...a]}async function jx(t,e){if(e.navPath===void 0)return;let n=Fx(await t.readText(e.navPath),{decodeEntities:!0}),r=ts(n,s=>it(s)!=="nav"?!1:(s.attribs?.["epub:type"]??s.attribs?.type??"").split(/\s+/u).map(c=>c.trim().toLowerCase()).includes("toc"));if(r===void 0)return;let a=ts(r,s=>it(s)==="ol");if(a===void 0)return;let o=tr(a).filter(s=>it(s)==="li").map(s=>nm(t,e.navPath,s)).filter(s=>s!==void 0);return o.length===0?void 0:o}async function Ux(t,e){if(e.ncxPath===void 0)return;let n=on(await t.readText(e.ncxPath)),r=ge(n,"navMap");if(r===void 0)return;let a=Ue(r,"navPoint").map(o=>rm(t,e.ncxPath,o)).filter(o=>o!==void 0);return a.length===0?void 0:a}function nm(t,e,n){let r=am(n),a=r===void 0?void 0:dm(om(r)),o=r!==void 0&&it(r)==="a"?r.attribs?.href:void 0,s=Bx(t,e,o),d=tr(n).filter(c=>it(c)==="ol").flatMap(c=>tr(c)).filter(c=>it(c)==="li").map(c=>nm(t,e,c)).filter(c=>c!==void 0);if(!(a===void 0&&s.path===void 0&&d.length===0))return{title:a,path:s.path,fragment:s.fragment,children:d}}function rm(t,e,n){let r=ge(n,"navLabel"),a=r===void 0?void 0:ge(r,"text"),o=a===void 0?void 0:dm(Zn(a)),s=ge(n,"content"),d=Hx(t,e,ee(s??n,"src")),c=Ue(n,"navPoint").map(u=>rm(t,e,u)).filter(u=>u!==void 0);if(!(o===void 0&&d.path===void 0&&c.length===0))return{title:o,path:d.path,fragment:d.fragment,children:c}}function em(t,e){return t.spine.filter(n=>!qx(t,n.path,e)).filter(n=>!e.has(n.path)).map(n=>({title:$x(n.path),path:n.path,fragment:void 0,children:[]}))}function qx(t,e,n){if(t.guideNonContentPaths.has(e))return!0;let r=ns(e).toLowerCase();return t.navPath===e?!0:Gx.has(r)&&!n.has(e)}function im(t){let e=new Set;for(let n of t){n.path!==void 0&&e.add(n.path);for(let r of im(n.children))e.add(r)}return e}function Bx(t,e,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Vn(n);return{path:r===""?void 0:t.resolveRelativePath(e,r),fragment:a}}function Hx(t,e,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Vn(n);return{path:r===""?void 0:t.resolveRelativePath(e,r),fragment:a}}function ts(t,e){if(sm(t)&&e(t))return t;for(let n of t.children??[]){let r=ts(n,e);if(r!==void 0)return r}}function am(t){for(let e of tr(t)){let n=it(e);if(n==="a"||n==="span")return e}for(let e of tr(t)){if(it(e)==="ol")continue;let n=am(e);if(n!==void 0)return n}}function om(t){return t.type==="text"?t.data??"":(t.children??[]).map(om).join("")}function tr(t){return(t.children??[]).filter(sm)}function sm(t){return t.type==="tag"||t.type==="script"||t.type==="style"}function it(t){return t.name?.toLowerCase()}function $x(t){let e=Jx(t),n=ns(t).slice(0,-e.length||void 0).trim();return n===""?void 0:n}function ns(t){return t.replaceAll("\\","/").split("/").at(-1)??""}function Jx(t){let e=ns(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n)}function dm(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var Gx,cm=i(()=>{"use strict";Yn();es();Ni();Gx=new Set(["toc.xhtml","nav.xhtml","contents.xhtml","tableofcontents.xhtml","cover.xhtml","titlepage.xhtml"])});function Kx(t){if(t.hasEntry("META-INF/encryption.xml"))throw new Error("Encrypted EPUB is not supported: found META-INF/encryption.xml.")}async function zx(t,e){if(!(e.coverPath===void 0||e.coverMediaType===void 0))return{path:e.coverPath,mediaType:e.coverMediaType,data:await t.readBuffer(e.coverPath)}}function Qx(t,e){let n=new Map;return e.map((r,a)=>um(t,r,[a],n))}function um(t,e,n,r){let a=Vo(e.fragment),o=e.path===void 0?`toc:${n.join(".")}`:t.createSectionId(e.path,a),s=Xx(o,r);return{hasContent:e.path!==void 0,id:s,title:e.title,path:e.path,fragment:a,wordsCount:0,children:e.children.map((d,c)=>um(t,d,[...n,c],r))}}function lm(t,e){return t.map(n=>{let r=e.get(n.id);return{...n,hasContent:r?.hasContent??!1,wordsCount:r?.wordsCount??0,children:lm(n.children,e)}})}function Xx(t,e){let n=e.get(t)??0;return e.set(t,n+1),n===0?t:`${t}~${n+1}`}function Vx(t,e){let n=new Map,r=new Map(e.spine.map(a=>[a.path,a.spineIndex]));for(let a of mm(t)){if(a.path===void 0)continue;let o=n.get(a.path)??[];o.push({id:a.id,path:a.path,fragment:a.fragment,spineIndex:r.get(a.path)}),n.set(a.path,o)}return n}function mm(t){let e=[];for(let n of t)e.push(n),e.push(...mm(n.children));return e}var rs,is,nr,as,pm=i(()=>{"use strict";Yn();Yn();Xl();cm();es();rs=class t{#e;#t;constructor(e,n){this.#e=e,this.#t=n}get id(){return this.#t.id}get hasContent(){return this.#t.hasContent}get title(){return this.#t.title}get wordsCount(){return this.#t.wordsCount}get children(){return this.#t.children.map(e=>new t(this.#e,e))}async open(){return await this.#e.openSection(this.#t.id)}async openWithProvenance(){return await this.#e.openSectionWithProvenance(this.#t.id)}},is=class t{#e;#t;#n;#r;#i;constructor(e,n,r,a,o){this.#e=e,this.#t=n,this.#n=r,this.#r=a,this.#i=o}static async open(e){Kx(e);let n=await Zl(e),r={digest:e.digest,mediaType:"application/epub+zip",name:e.name,...n.metadata.identifier===null?{}:{identifier:n.metadata.identifier}},a=await tm(e,n),o=Qx(e,a),s=Vx(o,n),d=await $l(e,s),c=lm(o,d),u=await zx(e,n);return new t(r,n,u,c,new Oi(e,s))}readMeta(){return Promise.resolve(this.#t.metadata)}readCover(){return Promise.resolve(this.#n)}readSections(){return Promise.resolve(this.#r.map(e=>new rs(this,e)))}async openSection(e){return await this.#i.openSection(e)}async openSectionWithProvenance(e){return await this.#i.openSectionWithProvenance(e,this.#e)}},nr=class{get format(){return"epub"}async openSession(e,n){let r=await Li.open(e);try{let a=await is.open(r);return await n(a)}finally{await r.close()}}},as=new nr});var hm=i(()=>{"use strict";pm()});var fm=i(()=>{"use strict";y()});import{SaxesParser as bN}from"saxes";var ym=i(()=>{"use strict";nt();Ni();fm()});var bm=i(()=>{"use strict";ym()});async function*Zx(t){let e=await t.openReader(),n=new TextDecoder,r="";try{for(let a=0;a<e.size;){let o=await e.read(a,Math.min(65536,e.size-a));a+=o.byteLength,r+=n.decode(o,{stream:a<e.size});let s=r.split(/(?<=\n)/u);r=s.pop()??"";for(let d of s)d!==""&&(yield d)}r+=n.decode(),r!==""&&(yield r)}finally{await e.close()}}function eI(t){let e=t.lastIndexOf("."),n=(e<=0?t:t.slice(0,e)).trim();return n===""?null:n}var Yx,os,ss,rr,Sm,wm,km=i(()=>{"use strict";Xn();Yx="root",os=class{#e;#t;constructor(e,n=Yx){this.#e=e,this.#t=n}get id(){return this.#t}get hasContent(){return!0}get title(){}get children(){return[]}open(){return Promise.resolve(Zx(this.#e))}},ss=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,this.#e=new os(e)}readMeta(){return Promise.resolve({version:Ge,sourceFormat:this.#n,title:eI(this.#t.name),authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null})}readCover(){return Promise.resolve(void 0)}readSections(){return Promise.resolve([this.#e])}},rr=class{#e;constructor(e){this.#e=e}get format(){return this.#e}async openSession(e,n){return await(await e.openReader()).close(),await n(new ss(e,this.#e))}},Sm=new rr("txt"),wm=new rr("markdown")});var ir=i(()=>{"use strict"});import{z as ue}from"zod";var PN,AN,xm=i(()=>{"use strict";ir();PN=ue.object({type:ue.literal("artifact"),digest:ue.string().regex(/^[0-9a-f]{64}$/iu),mediaType:ue.string().min(1),name:ue.string().optional(),identifier:ue.string().max(1024).optional()}),AN=ue.object({type:ue.literal("text"),text:ue.string(),locator:ue.record(ue.string(),ue.unknown())})});var at=i(()=>{"use strict";Xn();hm();bm();km();xm();Xo()});var ds=i(()=>{"use strict"});var ar=i(()=>{"use strict";at();ye();ds();Z()});var tI,Em,vm,Rm,or=i(()=>{"use strict";w();ir();tI=`
|
|
26
|
+
`,locator:rs(c.locator,f,k),locatorEnd:k,locatorStart:f}),b+=1):e.push({baseLocator:c.locator,char:v,locator:rs(c.locator,f,k),locatorEnd:k,locatorStart:f})}}let n=[],r=0;for(let c of e){if(c.char===`
|
|
27
|
+
`){if(r+=1,r>2)continue}else r=0;n.push(c)}let a=0;for(;a<n.length&&n[a].char.trim()==="";)a+=1;let o=n.length;for(;o>a&&n[o-1].char.trim()==="";)o-=1;let s=n.slice(a,o),d=[];for(let c of s){let u=d.at(-1);u!==void 0&&u.locatorBase===c.baseLocator&&u.locatorEnd===c.locatorStart&&u.locatorStart!==void 0&&c.locatorEnd!==void 0?d[d.length-1]={locatorBase:u.locatorBase,locator:rs(u.locatorBase??u.locator,u.locatorStart,c.locatorEnd),locatorEnd:c.locatorEnd,locatorStart:u.locatorStart,text:u.text+c.char}:u!==void 0&&u.locatorBase===c.baseLocator&&u.locatorStart===void 0&&c.locatorStart===void 0?d[d.length-1]={locatorBase:u.locatorBase,locator:u.locator,text:u.text+c.char}:d.push({locatorBase:c.baseLocator,locator:c.locator,...c.locatorEnd===void 0?{}:{locatorEnd:c.locatorEnd},...c.locatorStart===void 0?{}:{locatorStart:c.locatorStart},text:c.char})}return{segments:d,text:s.map(c=>c.char).join("")}}function rs(t,e,n){if(e===void 0||n===void 0)return t;let r=t.cfi;if(typeof r!="string")throw new Error("EPUB text mapping is missing a CFI locator.");let a=Px(r);if(a===void 0)throw new Error("EPUB text mapping has an invalid CFI range locator.");return{...t,cfi:`epubcfi(${a.parentPath},${Jl(a.startPath,e)},${Jl(a.endPath,n)})`}}function Px(t){if(!t.startsWith("epubcfi(")||!t.endsWith(")"))return;let e=Ax(t.slice(8,-1));if(e.length!==3||e.some(o=>o===""))return;let[n,r,a]=e;if(!(n===void 0||r===void 0||a===void 0))return{endPath:a,parentPath:n,startPath:r}}function Ax(t){let e=[],n=0,r=0,a=!1;for(let o=0;o<t.length;o+=1){let s=t[o];if(a){a=!1;continue}if(s==="^"){a=!0;continue}if(s==="["){r+=1;continue}if(s==="]"){r-=1;continue}s===","&&r===0&&(e.push(t.slice(n,o)),n=o+1)}return e.push(t.slice(n)),e}function Jl(t,e){if(!/:\d+$/u.test(t))throw new Error("EPUB text mapping has an invalid CFI offset.");return t.replace(/:\d+$/u,`:${e}`)}function Lx(t){return t.name?.toLowerCase()}function Kl(t){return t.type==="text"}function zl(t){return t.name!==void 0&&t.type!=="directive"}function Ql(t,e,n,r){let a=n?e:(e+1)*2,o=n||r===void 0?"":`[${Dx(r)}]`;return`${t}/${a}${o}`}function Xl(t,e,n,r){let a=tm(t),{parentPath:o,textPath:s}=Ox(e),d=o===""?a:`${a}!${o}`,c=o===""?`!${s}:${n}`:`${s}:${n}`,u=o===""?`!${s}:${r}`:`${s}:${r}`;return{cfi:`epubcfi(${d},${c},${u})`}}function Ox(t){let e=t.lastIndexOf("/");if(e<0||e===t.length-1)throw new Error(`EPUB text mapping has an invalid CFI path: ${t}`);return{parentPath:t.slice(0,e),textPath:t.slice(e)}}function Nx(t,e){return{cfi:`epubcfi(${Wx(t)}${e})`}}function Wx(t){return`${tm(t)}!`}function tm(t){return`/6/${(t+1)*2}`}function Dx(t){return[...t].map(e=>"[]^(),;=".includes(e)?`^${e}`:e).join("")}var Ix,vx,ns,Di,nm=i(()=>{"use strict";rt();Ix=new Set(["address","article","aside","blockquote","br","dd","div","dl","dt","figcaption","figure","footer","h1","h2","h3","h4","h5","h6","header","hr","li","main","nav","ol","p","pre","section","table","td","th","tr","ul"]),vx=new Set(["script","style"]),ns={},Di=class{#e;#t;constructor(e,n){this.#e=e,this.#t=Rx(n)}async openSection(e){let n=this.#t.get(e);return n===void 0?[]:[(await this.#n(n.path,n.targets)).get(e)??""]}async openSectionWithProvenance(e,n){let r=this.#t.get(e);if(r===void 0)return{stream:[]};if(r.targets.find(c=>c.id===e)?.spineIndex===void 0)throw new Error(`EPUB section ${e} is not associated with a spine item.`);let o=await this.#e.readText(r.path),s=Cx(o,r.targets,e),d=Tx(s.segments,n.digest);if(s.text.length>0&&d.length===0)throw new Error(`EPUB section ${e} produced text without provenance mappings.`);return{provenance:{artifacts:[n],mappings:d},stream:[s.text]}}async#n(e,n){let r=await Yl(this.#e,e);return Zl(r,n)}}});import{SaxesParser as Mx}from"saxes";function sn(t){let e=new Mx({xmlns:!1}),n=[],r;if(e.on("opentag",a=>{let o={name:a.name,attributes:Object.fromEntries(Object.entries(a.attributes).map(([d,c])=>[d,String(c)])),children:[],text:""},s=n[n.length-1];s===void 0?r=o:s.children.push(o),n.push(o)}),e.on("text",a=>{let o=n[n.length-1];o!==void 0&&(o.text+=a)}),e.on("cdata",a=>{let o=n[n.length-1];o!==void 0&&(o.text+=a)}),e.on("closetag",()=>{n.pop()}),e.write(t).close(),r===void 0)throw new Error("XML document is empty");return rm(r)}function be(t,e){return t.children.find(n=>tr(n.name)===e)}function qe(t,e){return t.children.filter(n=>tr(n.name)===e)}function ee(t,e){return t.attributes[e]}function er(t){let e=t.text;for(let n of t.children)e+=er(n);return e}function tr(t){let e=t.indexOf(":");return e===-1?t:t.slice(e+1)}function rm(t){return{name:t.name,attributes:Object.freeze({...t.attributes}),children:Object.freeze(t.children.map(rm)),text:t.text}}var Mi=i(()=>{"use strict"});async function am(t){let e=await jx(t),n=sn(await t.readText(e)),r=Ux(ee(n,"version")),a=be(n,"metadata"),o=be(n,"manifest"),s=be(n,"spine"),d=be(n,"guide"),c=Bx(t,e,o),u=new Map([...c.values()].map(C=>[C.path,C])),m=Hx(s,c),b=$x(t,e,d),v=qx(a),f=Jx(c),k=Kx(c,s),g=zx(c,a);return{version:r,opfPath:e,metadata:{...v,version:je,sourceFormat:"epub"},manifest:c,manifestByPath:u,spine:m,navPath:f,ncxPath:k,coverPath:g?.path,coverMediaType:g?.mediaType,guideNonContentPaths:b}}async function jx(t){let e=sn(await t.readText("META-INF/container.xml")),r=be(e,"rootfiles")?.children.find(o=>tr(o.name)==="rootfile"),a=r===void 0?void 0:ee(r,"full-path");if(a===void 0||a.trim()==="")throw new Error("EPUB container.xml does not contain an OPF rootfile");return a}function Ux(t){return t?.trim().startsWith("3")===!0?3:2}function qx(t){if(t===void 0)return im();let e=Ct(t,"title"),n=Ct(t,"creator"),r=Ct(t,"language"),a=Ct(t,"identifier"),o=Ct(t,"publisher"),s=Ct(t,"date"),d=Ct(t,"description");return{...im(),title:e[0]??null,authors:[...n],language:r[0]??null,identifier:a[0]??null,publisher:o[0]??null,publishedAt:s[0]??null,description:d[0]??null}}function im(){return{version:je,sourceFormat:"epub",title:null,authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null}}function Ct(t,e){return t.children.filter(n=>tr(n.name)===e).map(n=>Xx(er(n))).filter(n=>n!==void 0)}function Bx(t,e,n){let r=new Map;if(n===void 0)return r;for(let a of qe(n,"item")){let o=ee(a,"id"),s=ee(a,"href"),d=ee(a,"media-type")??"";o===void 0||s===void 0||r.set(o,{id:o,path:t.resolveRelativePath(e,s),mediaType:d,properties:new Set((ee(a,"properties")??"").split(/\s+/u).map(c=>c.trim().toLowerCase()).filter(c=>c!==""))})}return r}function Hx(t,e){return t===void 0?[]:qe(t,"itemref").map((n,r)=>{let a=ee(n,"idref");if(a===void 0)return;let o=e.get(a);if(!(o===void 0||o.mediaType!=="application/xhtml+xml"&&o.mediaType!=="text/html"))return{idref:a,path:o.path,mediaType:o.mediaType,spineIndex:r}}).filter(n=>n!==void 0)}function $x(t,e,n){let r=new Set;if(n===void 0)return r;for(let a of qe(n,"reference")){let o=(ee(a,"type")??"").trim().toLowerCase();if(!Gx.has(o))continue;let s=ee(a,"href");s===void 0||s.trim()===""||r.add(t.resolveRelativePath(e,Yn(s).path))}return r}function Jx(t){for(let e of t.values())if(e.properties.has("nav"))return e.path}function Kx(t,e){let n=e===void 0?void 0:ee(e,"toc");if(n!==void 0)return t.get(n)?.path;for(let r of t.values())if(r.mediaType==="application/x-dtbncx+xml")return r.path}function zx(t,e){for(let r of t.values())if(r.properties.has("cover-image")&&r.mediaType.startsWith("image/"))return r;let n=Qx(e);if(n!==void 0){let r=t.get(n);if(r?.mediaType.startsWith("image/")===!0)return r}for(let r of Fx){let a=t.get(r);if(a?.mediaType.startsWith("image/")===!0)return a}for(let r of t.values())if(r.mediaType.startsWith("image/")&&jo(r.path).toLowerCase().includes("cover"))return r}function Qx(t){if(t!==void 0)for(let e of qe(t,"meta")){if((ee(e,"name")??"").trim().toLowerCase()!=="cover")continue;let r=ee(e,"content");if(r!==void 0&&r.trim()!=="")return r.trim()}}function Xx(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var Fx,Gx,is=i(()=>{"use strict";Rt();Vn();Zn();Mi();Fx=["cover-image","coverimg","cover-img","cover"],Gx=new Set(["cover","titlepage","other.titlepage"])});import{parseDocument as Vx}from"htmlparser2";async function sm(t,e){let n=await Zx(t,e)??await eE(t,e)??[];if(n.length===0)return om(e,new Set);let r=um(n),a=om(e,r);return a.length===0?n:[...n,...a]}async function Zx(t,e){if(e.navPath===void 0)return;let n=Vx(await t.readText(e.navPath),{decodeEntities:!0}),r=as(n,s=>at(s)!=="nav"?!1:(s.attribs?.["epub:type"]??s.attribs?.type??"").split(/\s+/u).map(c=>c.trim().toLowerCase()).includes("toc"));if(r===void 0)return;let a=as(r,s=>at(s)==="ol");if(a===void 0)return;let o=nr(a).filter(s=>at(s)==="li").map(s=>dm(t,e.navPath,s)).filter(s=>s!==void 0);return o.length===0?void 0:o}async function eE(t,e){if(e.ncxPath===void 0)return;let n=sn(await t.readText(e.ncxPath)),r=be(n,"navMap");if(r===void 0)return;let a=qe(r,"navPoint").map(o=>cm(t,e.ncxPath,o)).filter(o=>o!==void 0);return a.length===0?void 0:a}function dm(t,e,n){let r=lm(n),a=r===void 0?void 0:hm(mm(r)),o=r!==void 0&&at(r)==="a"?r.attribs?.href:void 0,s=nE(t,e,o),d=nr(n).filter(c=>at(c)==="ol").flatMap(c=>nr(c)).filter(c=>at(c)==="li").map(c=>dm(t,e,c)).filter(c=>c!==void 0);if(!(a===void 0&&s.path===void 0&&d.length===0))return{title:a,path:s.path,fragment:s.fragment,children:d}}function cm(t,e,n){let r=be(n,"navLabel"),a=r===void 0?void 0:be(r,"text"),o=a===void 0?void 0:hm(er(a)),s=be(n,"content"),d=rE(t,e,ee(s??n,"src")),c=qe(n,"navPoint").map(u=>cm(t,e,u)).filter(u=>u!==void 0);if(!(o===void 0&&d.path===void 0&&c.length===0))return{title:o,path:d.path,fragment:d.fragment,children:c}}function om(t,e){return t.spine.filter(n=>!tE(t,n.path,e)).filter(n=>!e.has(n.path)).map(n=>({title:iE(n.path),path:n.path,fragment:void 0,children:[]}))}function tE(t,e,n){if(t.guideNonContentPaths.has(e))return!0;let r=os(e).toLowerCase();return t.navPath===e?!0:Yx.has(r)&&!n.has(e)}function um(t){let e=new Set;for(let n of t){n.path!==void 0&&e.add(n.path);for(let r of um(n.children))e.add(r)}return e}function nE(t,e,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Yn(n);return{path:r===""?void 0:t.resolveRelativePath(e,r),fragment:a}}function rE(t,e,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Yn(n);return{path:r===""?void 0:t.resolveRelativePath(e,r),fragment:a}}function as(t,e){if(pm(t)&&e(t))return t;for(let n of t.children??[]){let r=as(n,e);if(r!==void 0)return r}}function lm(t){for(let e of nr(t)){let n=at(e);if(n==="a"||n==="span")return e}for(let e of nr(t)){if(at(e)==="ol")continue;let n=lm(e);if(n!==void 0)return n}}function mm(t){return t.type==="text"?t.data??"":(t.children??[]).map(mm).join("")}function nr(t){return(t.children??[]).filter(pm)}function pm(t){return t.type==="tag"||t.type==="script"||t.type==="style"}function at(t){return t.name?.toLowerCase()}function iE(t){let e=aE(t),n=os(t).slice(0,-e.length||void 0).trim();return n===""?void 0:n}function os(t){return t.replaceAll("\\","/").split("/").at(-1)??""}function aE(t){let e=os(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n)}function hm(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var Yx,fm=i(()=>{"use strict";Zn();is();Mi();Yx=new Set(["toc.xhtml","nav.xhtml","contents.xhtml","tableofcontents.xhtml","cover.xhtml","titlepage.xhtml"])});function oE(t){if(t.hasEntry("META-INF/encryption.xml"))throw new Error("Encrypted EPUB is not supported: found META-INF/encryption.xml.")}async function sE(t,e){if(!(e.coverPath===void 0||e.coverMediaType===void 0))return{path:e.coverPath,mediaType:e.coverMediaType,data:await t.readBuffer(e.coverPath)}}function dE(t,e){let n=new Map;return e.map((r,a)=>ym(t,r,[a],n))}function ym(t,e,n,r){let a=ts(e.fragment),o=e.path===void 0?`toc:${n.join(".")}`:t.createSectionId(e.path,a),s=cE(o,r);return{hasContent:e.path!==void 0,id:s,title:e.title,path:e.path,fragment:a,wordsCount:0,children:e.children.map((d,c)=>ym(t,d,[...n,c],r))}}function gm(t,e){return t.map(n=>{let r=e.get(n.id);return{...n,hasContent:r?.hasContent??!1,wordsCount:r?.wordsCount??0,children:gm(n.children,e)}})}function cE(t,e){let n=e.get(t)??0;return e.set(t,n+1),n===0?t:`${t}~${n+1}`}function uE(t,e){let n=new Map,r=new Map(e.spine.map(a=>[a.path,a.spineIndex]));for(let a of bm(t)){if(a.path===void 0)continue;let o=n.get(a.path)??[];o.push({id:a.id,path:a.path,fragment:a.fragment,spineIndex:r.get(a.path)}),n.set(a.path,o)}return n}function bm(t){let e=[];for(let n of t)e.push(n),e.push(...bm(n.children));return e}var ss,ds,rr,cs,Sm=i(()=>{"use strict";Zn();Zn();nm();fm();is();ss=class t{#e;#t;constructor(e,n){this.#e=e,this.#t=n}get id(){return this.#t.id}get hasContent(){return this.#t.hasContent}get title(){return this.#t.title}get wordsCount(){return this.#t.wordsCount}get children(){return this.#t.children.map(e=>new t(this.#e,e))}async open(){return await this.#e.openSection(this.#t.id)}async openWithProvenance(){return await this.#e.openSectionWithProvenance(this.#t.id)}},ds=class t{#e;#t;#n;#r;#i;constructor(e,n,r,a,o){this.#e=e,this.#t=n,this.#n=r,this.#r=a,this.#i=o}static async open(e){oE(e);let n=await am(e),r={digest:e.digest,mediaType:"application/epub+zip",name:e.name,...n.metadata.identifier===null?{}:{identifier:n.metadata.identifier}},a=await sm(e,n),o=dE(e,a),s=uE(o,n),d=await Vl(e,s),c=gm(o,d),u=await sE(e,n);return new t(r,n,u,c,new Di(e,s))}readMeta(){return Promise.resolve(this.#t.metadata)}readCover(){return Promise.resolve(this.#n)}readSections(){return Promise.resolve(this.#r.map(e=>new ss(this,e)))}async openSection(e){return await this.#i.openSection(e)}async openSectionWithProvenance(e){return await this.#i.openSectionWithProvenance(e,this.#e)}},rr=class{get format(){return"epub"}async openSession(e,n){let r=await Wi.open(e);try{let a=await ds.open(r);return await n(a)}finally{await r.close()}}},cs=new rr});var wm=i(()=>{"use strict";Sm()});var km=i(()=>{"use strict";y()});import{SaxesParser as qN}from"saxes";var xm=i(()=>{"use strict";rt();Mi();km()});var Im=i(()=>{"use strict";xm()});async function*mE(t){let e=await t.openReader(),n=new TextDecoder,r="";try{for(let a=0;a<e.size;){let o=await e.read(a,Math.min(65536,e.size-a));a+=o.byteLength,r+=n.decode(o,{stream:a<e.size});let s=r.split(/(?<=\n)/u);r=s.pop()??"";for(let d of s)d!==""&&(yield d)}r+=n.decode(),r!==""&&(yield r)}finally{await e.close()}}function pE(t){let e=t.lastIndexOf("."),n=(e<=0?t:t.slice(0,e)).trim();return n===""?null:n}var lE,us,ls,ir,vm,Rm,Cm=i(()=>{"use strict";Vn();lE="root",us=class{#e;#t;constructor(e,n=lE){this.#e=e,this.#t=n}get id(){return this.#t}get hasContent(){return!0}get title(){}get children(){return[]}open(){return Promise.resolve(mE(this.#e))}},ls=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,this.#e=new us(e)}readMeta(){return Promise.resolve({version:je,sourceFormat:this.#n,title:pE(this.#t.name),authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null})}readCover(){return Promise.resolve(void 0)}readSections(){return Promise.resolve([this.#e])}},ir=class{#e;constructor(e){this.#e=e}get format(){return this.#e}async openSession(e,n){return await(await e.openReader()).close(),await n(new ls(e,this.#e))}},vm=new ir("txt"),Rm=new ir("markdown")});var ar=i(()=>{"use strict"});import{z as ue}from"zod";var eW,tW,Tm=i(()=>{"use strict";ar();eW=ue.object({type:ue.literal("artifact"),digest:ue.string().regex(/^[0-9a-f]{64}$/iu),mediaType:ue.string().min(1),name:ue.string().optional(),identifier:ue.string().max(1024).optional()}),tW=ue.object({type:ue.literal("text"),text:ue.string(),locator:ue.record(ue.string(),ue.unknown())})});var ot=i(()=>{"use strict";Vn();wm();Im();Cm();Tm();es()});var ms=i(()=>{"use strict"});var or=i(()=>{"use strict";ot();ge();ms();Z()});var hE,Pm,Am,Lm,sr=i(()=>{"use strict";w();ar();hE=`
|
|
28
28
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
29
29
|
digest BLOB NOT NULL UNIQUE,
|
|
30
30
|
short_uid TEXT NOT NULL UNIQUE
|
|
@@ -34,7 +34,7 @@ var ak=Object.defineProperty;var i=(t,e)=>()=>(t&&(e=t(t=0)),e);var ok=(t,e)=>{f
|
|
|
34
34
|
media_type TEXT NOT NULL,
|
|
35
35
|
name TEXT,
|
|
36
36
|
identifier TEXT
|
|
37
|
-
`,
|
|
37
|
+
`,Pm=`
|
|
38
38
|
CREATE TABLE IF NOT EXISTS serials (
|
|
39
39
|
id INTEGER PRIMARY KEY,
|
|
40
40
|
document_order INTEGER NOT NULL DEFAULT 0
|
|
@@ -330,7 +330,7 @@ var ak=Object.defineProperty;var i=(t,e)=>()=>(t&&(e=t(t=0)),e);var ok=(t,e)=>{f
|
|
|
330
330
|
ON text_sentence_records(kind, chapter_id, sentence_index);
|
|
331
331
|
|
|
332
332
|
CREATE TABLE IF NOT EXISTS source_artifacts (
|
|
333
|
-
${
|
|
333
|
+
${hE}
|
|
334
334
|
);
|
|
335
335
|
|
|
336
336
|
CREATE TABLE IF NOT EXISTS source_locators (
|
|
@@ -396,7 +396,7 @@ ${tI}
|
|
|
396
396
|
triple_predicate,
|
|
397
397
|
triple_object_qid
|
|
398
398
|
);
|
|
399
|
-
`,
|
|
399
|
+
`,Am=`
|
|
400
400
|
id INTEGER PRIMARY KEY,
|
|
401
401
|
archive_id INTEGER NOT NULL,
|
|
402
402
|
kind INTEGER NOT NULL,
|
|
@@ -406,14 +406,14 @@ ${tI}
|
|
|
406
406
|
byte_offset INTEGER NOT NULL DEFAULT 0,
|
|
407
407
|
byte_length INTEGER NOT NULL DEFAULT 0,
|
|
408
408
|
UNIQUE(archive_id, kind, chapter_id, sentence_index)
|
|
409
|
-
`,
|
|
409
|
+
`,Lm=`
|
|
410
410
|
CREATE TABLE IF NOT EXISTS search_index_state (
|
|
411
411
|
key TEXT PRIMARY KEY,
|
|
412
412
|
value TEXT NOT NULL
|
|
413
413
|
);
|
|
414
414
|
|
|
415
415
|
CREATE TABLE IF NOT EXISTS text_sentence_records (
|
|
416
|
-
${
|
|
416
|
+
${Am}
|
|
417
417
|
);
|
|
418
418
|
|
|
419
419
|
CREATE INDEX IF NOT EXISTS idx_text_sentence_records_chapter
|
|
@@ -470,22 +470,22 @@ ${vm}
|
|
|
470
470
|
updated_at INTEGER NOT NULL,
|
|
471
471
|
PRIMARY KEY (archive_id, chapter_id)
|
|
472
472
|
);
|
|
473
|
-
`});var
|
|
473
|
+
`});var Tt=i(()=>{"use strict";w();Ce()});var Om=i(()=>{"use strict";w();Tt()});var Nm=i(()=>{"use strict";w()});var Wm=i(()=>{"use strict";w();wi()});var Dm=i(()=>{"use strict";w();Ce()});var Mm=i(()=>{"use strict";w();Tt()});var Fm=i(()=>{"use strict";w();Tt()});var Gm=i(()=>{"use strict";w();Tt()});var jm=i(()=>{"use strict";w();Tt()});var Um=i(()=>{"use strict";w();Tt()});var Hm=i(()=>{"use strict";ve();w();ar()});var $m=i(()=>{"use strict";w()});var Jm=i(()=>{"use strict";w()});var Km=i(()=>{"use strict";w()});var zm=i(()=>{"use strict";$m();Jm();Km()});var ys=i(()=>{"use strict";Om();Nm();Wm();Dm();Mm();Fm();Gm();jm();Um();Hm();zm()});var gs=i(()=>{"use strict"});var dp=i(()=>{"use strict";y()});var cp=i(()=>{"use strict";he();Qn()});var _t=i(()=>{"use strict"});var up=i(()=>{"use strict";y();w();sr();_t()});var lp=i(()=>{"use strict";he();gs()});var mp=i(()=>{"use strict"});import{z as bs}from"zod";var OM,hp=i(()=>{"use strict";y();Vn();es();or();w();Jo();sr();ys();Ce();gs();dp();cp();up();Qn();lp();mp();OM=bs.object({mediaType:bs.string().min(1),path:bs.string()})});var fp=i(()=>{"use strict"});var ws=i(()=>{"use strict";hp();fp()});var gp=i(()=>{"use strict";Xo()});var P=i(()=>{"use strict";w();Ll();Jo();Xo();ws();gp();sr();ar();ys();Ce()});var xs=i(()=>{"use strict"});var He=i(()=>{"use strict";xs()});async function wp(t){let e=await kE(t);try{return await wE(e,t),await e.queryOne(`
|
|
474
474
|
SELECT 1 AS active
|
|
475
475
|
FROM state_locks
|
|
476
476
|
WHERE scope = ? AND resource_key = ?
|
|
477
477
|
LIMIT 1
|
|
478
|
-
`,[t.scope,t.resourceKey],()=>!0)===!0}finally{await e.close()}}async function
|
|
478
|
+
`,[t.scope,t.resourceKey],()=>!0)===!0}finally{await e.close()}}async function wE(t,e){let n=[],r=[];e.scope!==void 0&&(n.push("scope = ?"),r.push(e.scope)),e.resourceKey!==void 0&&(n.push("resource_key = ?"),r.push(e.resourceKey));let a=await t.queryAll(`
|
|
479
479
|
SELECT scope, resource_key, mode, owner_id, owner_pid, heartbeat_at
|
|
480
480
|
FROM state_locks
|
|
481
481
|
${n.length===0?"":`WHERE ${n.join(" AND ")}`}
|
|
482
|
-
`,r,o=>({lock:
|
|
482
|
+
`,r,o=>({lock:xE(o),resourceKey:I(o,"resource_key"),scope:I(o,"scope")}));for(let{lock:o,resourceKey:s,scope:d}of a)IE(o,e.staleMs)&&await t.run(`
|
|
483
483
|
DELETE FROM state_locks
|
|
484
484
|
WHERE scope = ?
|
|
485
485
|
AND resource_key = ?
|
|
486
486
|
AND owner_id = ?
|
|
487
487
|
AND heartbeat_at = ?
|
|
488
|
-
`,[d,s,o.ownerId,o.heartbeatAt])}async function
|
|
488
|
+
`,[d,s,o.ownerId,o.heartbeatAt])}async function kE(t){if(t.databaseFile!==void 0)return await N.open(t.databaseFile,Sp,{create:!0,mode:"readwrite"});if(t.stateDatabaseName!==void 0)return await K(t.stateDatabaseName,Sp);throw new Error("State lock requires a database File or state database name.")}function xE(t){return{heartbeatAt:S(t,"heartbeat_at"),mode:EE(I(t,"mode")),ownerId:I(t,"owner_id")}}function EE(t){return t==="read"||t==="write"?t:"write"}function IE(t,e=SE){return Date.now()-t.heartbeatAt>e}var Sp,SE,ji=i(()=>{"use strict";F();w();P();Sp=`
|
|
489
489
|
CREATE TABLE IF NOT EXISTS state_locks (
|
|
490
490
|
scope TEXT NOT NULL,
|
|
491
491
|
resource_key TEXT NOT NULL,
|
|
@@ -499,7 +499,7 @@ ${vm}
|
|
|
499
499
|
|
|
500
500
|
CREATE INDEX IF NOT EXISTS idx_state_locks_resource
|
|
501
501
|
ON state_locks(scope, resource_key);
|
|
502
|
-
`,
|
|
502
|
+
`,SE=300*1e3});async function Ep(t){return await wp({stateDatabaseName:"core.sqlite",resourceKey:CE(t),scope:RE,staleMs:xp})||await TE(t)}function CE(t){return String(t)}async function TE(t){let e=await _E();try{let n=await e.queryOne("SELECT owner_pid, heartbeat_at FROM library_locks WHERE library_id = ?",[t],r=>({heartbeatAt:S(r,"heartbeat_at"),ownerPid:S(r,"owner_pid")}));return n!==void 0&&AE(n)}finally{await e.close()}}async function _E(){let t=await K("core.sqlite",vE);return await PE(t),t}async function PE(t){new Set(await t.queryAll("PRAGMA table_info(library_locks)",void 0,n=>I(n,"name"))).has("heartbeat_at")||await t.run("ALTER TABLE library_locks ADD COLUMN heartbeat_at INTEGER NOT NULL DEFAULT 0")}function AE(t){return Date.now()-t.heartbeatAt<=xp}var vE,RE,xp,Pt=i(()=>{"use strict";w();P();ji();vE=`
|
|
503
503
|
CREATE TABLE IF NOT EXISTS library_locks (
|
|
504
504
|
library_id INTEGER PRIMARY KEY,
|
|
505
505
|
mode TEXT NOT NULL,
|
|
@@ -508,9 +508,90 @@ ${vm}
|
|
|
508
508
|
heartbeat_at INTEGER NOT NULL,
|
|
509
509
|
created_at INTEGER NOT NULL
|
|
510
510
|
);
|
|
511
|
-
`,
|
|
511
|
+
`,RE="library",xp=300*1e3});var bF,Ot=i(()=>{"use strict";y();w();P();He();ve();F();Pt();xs();bF=Promise.resolve()});var wF,cr=i(()=>{"use strict";wF=new RegExp("\\p{Script=Han}","u")});var Is=i(()=>{"use strict";ve()});var Rp=i(()=>{"use strict"});async function _p(){let t=await K("cache/search-index-query-hits.sqlite",Tp);return vs??=OE(t).catch(e=>{throw vs=void 0,e}),await vs,t}async function OE(t){await t.queryOne("SELECT value FROM query_cache_metadata WHERE key = 'schema_version'",void 0,n=>String(n.value))!==Cp&&await t.execute(`
|
|
512
|
+
DROP TABLE IF EXISTS query_dense_segment_hits;
|
|
513
|
+
DROP TABLE IF EXISTS query_text_hits;
|
|
514
|
+
DROP TABLE IF EXISTS query_object_hits;
|
|
515
|
+
DROP TABLE IF EXISTS query_runs;
|
|
516
|
+
DROP TABLE IF EXISTS query_cache_metadata;
|
|
517
|
+
${Tp}
|
|
518
|
+
`)}async function Pp(t){if(t.length===0)return;let e=await _p();try{await e.transaction(async()=>{for(let n of t)await Ap(e,n)})}finally{await e.close()}}async function Ap(t,e){await NE(t,e),await t.run("DELETE FROM query_runs WHERE query_id = ?",[e])}async function NE(t,e){await t.run("DELETE FROM query_dense_segment_hits WHERE query_id = ?",[e]),await t.run("DELETE FROM query_text_hits WHERE query_id = ?",[e]),await t.run("DELETE FROM query_object_hits WHERE query_id = ?",[e])}var Cp,LE,_F,Tp,vs,Rs=i(()=>{"use strict";w();P();Rp();Cp="3",LE=-1,_F=Date.now(),Tp=`
|
|
519
|
+
CREATE TABLE IF NOT EXISTS query_cache_metadata (
|
|
520
|
+
key TEXT PRIMARY KEY,
|
|
521
|
+
value TEXT NOT NULL
|
|
522
|
+
);
|
|
523
|
+
|
|
524
|
+
INSERT OR IGNORE INTO query_cache_metadata(key, value)
|
|
525
|
+
VALUES ('schema_version', '${Cp}');
|
|
526
|
+
|
|
527
|
+
CREATE TABLE IF NOT EXISTS query_runs (
|
|
528
|
+
query_id TEXT PRIMARY KEY,
|
|
529
|
+
owner_id TEXT NOT NULL,
|
|
530
|
+
complete INTEGER NOT NULL DEFAULT 0,
|
|
531
|
+
created_at INTEGER NOT NULL
|
|
532
|
+
);
|
|
533
|
+
|
|
534
|
+
CREATE TABLE IF NOT EXISTS query_object_hits (
|
|
535
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
536
|
+
query_id TEXT NOT NULL,
|
|
537
|
+
archive_id INTEGER NOT NULL,
|
|
538
|
+
owner_kind INTEGER NOT NULL,
|
|
539
|
+
owner_id TEXT NOT NULL,
|
|
540
|
+
property_kind INTEGER NOT NULL,
|
|
541
|
+
chapter_id INTEGER NOT NULL DEFAULT ${LE},
|
|
542
|
+
match_tier INTEGER NOT NULL,
|
|
543
|
+
raw_score REAL NOT NULL,
|
|
544
|
+
score REAL,
|
|
545
|
+
UNIQUE (
|
|
546
|
+
query_id, archive_id, owner_kind, owner_id, property_kind, chapter_id
|
|
547
|
+
)
|
|
548
|
+
);
|
|
549
|
+
|
|
550
|
+
CREATE INDEX IF NOT EXISTS idx_query_object_hits_score
|
|
551
|
+
ON query_object_hits(query_id, score DESC, archive_id, owner_kind, owner_id, property_kind);
|
|
552
|
+
|
|
553
|
+
CREATE TABLE IF NOT EXISTS query_text_hits (
|
|
554
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
555
|
+
query_id TEXT NOT NULL,
|
|
556
|
+
archive_id INTEGER NOT NULL,
|
|
557
|
+
kind INTEGER NOT NULL,
|
|
558
|
+
chapter_id INTEGER NOT NULL,
|
|
559
|
+
sentence_index INTEGER NOT NULL,
|
|
560
|
+
words_count INTEGER NOT NULL DEFAULT 0,
|
|
561
|
+
match_tier INTEGER,
|
|
562
|
+
raw_score REAL,
|
|
563
|
+
fts_score REAL,
|
|
564
|
+
embedding_score REAL,
|
|
565
|
+
score REAL,
|
|
566
|
+
rank INTEGER,
|
|
567
|
+
UNIQUE (query_id, archive_id, kind, chapter_id, sentence_index)
|
|
568
|
+
);
|
|
569
|
+
|
|
570
|
+
CREATE INDEX IF NOT EXISTS idx_query_text_hits_rank
|
|
571
|
+
ON query_text_hits(query_id, rank, archive_id, chapter_id, sentence_index, kind);
|
|
572
|
+
|
|
573
|
+
CREATE TABLE IF NOT EXISTS query_dense_segment_hits (
|
|
574
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
575
|
+
query_id TEXT NOT NULL,
|
|
576
|
+
archive_id INTEGER NOT NULL,
|
|
577
|
+
kind INTEGER NOT NULL,
|
|
578
|
+
chapter_id INTEGER NOT NULL,
|
|
579
|
+
start_sentence_index INTEGER NOT NULL,
|
|
580
|
+
end_sentence_index INTEGER NOT NULL,
|
|
581
|
+
raw_score REAL NOT NULL,
|
|
582
|
+
score REAL,
|
|
583
|
+
UNIQUE (
|
|
584
|
+
query_id, archive_id, kind, chapter_id,
|
|
585
|
+
start_sentence_index, end_sentence_index
|
|
586
|
+
)
|
|
587
|
+
);
|
|
588
|
+
|
|
589
|
+
CREATE INDEX IF NOT EXISTS idx_query_dense_segment_hits_score
|
|
590
|
+
ON query_dense_segment_hits(query_id, raw_score DESC, archive_id, chapter_id, start_sentence_index, kind);
|
|
591
|
+
`});var Cs,Nt=i(()=>{"use strict";Cs=`
|
|
512
592
|
CREATE TABLE IF NOT EXISTS search_sessions (
|
|
513
593
|
session_id TEXT PRIMARY KEY,
|
|
594
|
+
ranking_version INTEGER NOT NULL,
|
|
514
595
|
archive_key TEXT NOT NULL,
|
|
515
596
|
query TEXT NOT NULL,
|
|
516
597
|
options_json TEXT NOT NULL,
|
|
@@ -612,31 +693,32 @@ ON search_sessions(expires_at);
|
|
|
612
693
|
|
|
613
694
|
CREATE INDEX IF NOT EXISTS idx_search_sessions_prune
|
|
614
695
|
ON search_sessions(accessed_at DESC, created_at DESC, session_id);
|
|
615
|
-
`});async function
|
|
696
|
+
`});async function dn(){let t=await K("cache/search-sessions.sqlite",Cs);return Ts?t:await DE(t)?(Ts=!0,t):(await WE(t),Ts=!0,t)}async function WE(t){await t.execute(`
|
|
616
697
|
DROP TABLE IF EXISTS search_evidence_hit_events;
|
|
617
698
|
DROP TABLE IF EXISTS search_triple_hits;
|
|
618
699
|
DROP TABLE IF EXISTS search_entity_hits;
|
|
619
700
|
DROP TABLE IF EXISTS search_chunk_hits;
|
|
701
|
+
DROP TABLE IF EXISTS search_results;
|
|
620
702
|
DROP TABLE IF EXISTS search_sessions;
|
|
621
|
-
${
|
|
622
|
-
`)}async function
|
|
703
|
+
${Cs}
|
|
704
|
+
`)}async function DE(t){return await ur(t,"search_sessions","ranking_version")&&await ur(t,"search_entity_hits","archive_id")&&await ur(t,"search_chunk_hits","archive_id")&&await ur(t,"search_triple_hits","archive_id")&&await ur(t,"search_evidence_hit_events","archive_id")}async function ur(t,e,n){return(await t.queryAll(`PRAGMA table_info(${e})`,void 0,a=>String(a.name))).includes(n)}var Ts,cn=i(()=>{"use strict";P();Nt();Ts=!1});var Ui=i(()=>{"use strict"});async function Lp(t,e){await Op(t,e),await t.run("DELETE FROM search_sessions WHERE session_id = ?",[e])}async function Op(t,e){await t.run("DELETE FROM search_results WHERE session_id = ?",[e]),await t.run("DELETE FROM search_evidence_hit_events WHERE session_id = ?",[e]),await t.run("DELETE FROM search_entity_hits WHERE session_id = ?",[e]),await t.run("DELETE FROM search_triple_hits WHERE session_id = ?",[e]),await t.run("DELETE FROM search_chunk_hits WHERE session_id = ?",[e])}async function Np(t){await t.run(`
|
|
623
705
|
DELETE FROM predicate_dictionary
|
|
624
706
|
WHERE NOT EXISTS (
|
|
625
707
|
SELECT 1
|
|
626
708
|
FROM search_triple_hits
|
|
627
709
|
WHERE search_triple_hits.predicate_id = predicate_dictionary.id
|
|
628
710
|
)
|
|
629
|
-
`)}var
|
|
711
|
+
`)}var _s=i(()=>{"use strict";w();cn();Ui();Nt()});async function qi(t){let e=await dn();try{let n=await Wp(e),r=await e.queryOne("SELECT COUNT(*) AS count FROM search_sessions",void 0,c=>S(c,"count")),a=t.force?await jE(e):await GE(e,t.now),o=t.force?[]:await UE(e),s=[...new Set([...a,...o])].sort();!t.dryRun&&s.length>0&&(await e.transaction(async()=>{for(let c of s)await Lp(e,c);await Np(e)}),await e.run("VACUUM"),await Pp(s));let d=await Wp(e);return{freedBytes:Math.max(0,n-d),removed:s.length,scanned:r??0}}finally{await e.close()}}async function GE(t,e){return await t.queryAll(`
|
|
630
712
|
SELECT session_id
|
|
631
713
|
FROM search_sessions
|
|
632
714
|
WHERE expires_at < ?
|
|
633
|
-
`,[e],n=>
|
|
715
|
+
`,[e],n=>I(n,"session_id"))}async function jE(t){return await t.queryAll("SELECT session_id FROM search_sessions",void 0,e=>I(e,"session_id"))}async function UE(t){return await t.queryAll(`
|
|
634
716
|
SELECT session_id
|
|
635
717
|
FROM search_sessions
|
|
636
718
|
ORDER BY accessed_at DESC, created_at DESC, session_id
|
|
637
719
|
LIMIT -1 OFFSET ?
|
|
638
|
-
`,[500],e=>
|
|
639
|
-
`,
|
|
720
|
+
`,[500],e=>I(e,"session_id"))}async function Wp(t){let e=await t.queryOne("PRAGMA page_count",void 0,r=>S(r,"page_count"))??0,n=await t.queryOne("PRAGMA page_size",void 0,r=>S(r,"page_size"))??0;return e*n}var Dp=i(()=>{"use strict";w();Rs();cn();Nt();_s()});var Ps=i(()=>{"use strict"});var Mp=i(()=>{"use strict";Nt();Ps()});var As=i(()=>{"use strict"});var Bi=i(()=>{"use strict";w();cn();Ui();Mp();As()});var Gp=i(()=>{"use strict";F();Nt()});var jp=i(()=>{"use strict";w();Is();cn();Bi();Gp();Ui();Nt();_s()});var Up=i(()=>{"use strict";w();cn();Bi()});var Dt=i(()=>{"use strict";Is();Dp();Bi();jp();Up();As()});var Hi=i(()=>{"use strict"});var $i=i(()=>{"use strict";ot()});var Os=i(()=>{"use strict";ve()});var Ji=i(()=>{"use strict"});var Ns=i(()=>{"use strict";Ji()});var Ws=i(()=>{"use strict";Ps();Ji()});var Ki=i(()=>{"use strict";Hi();Os();Ns();Ws()});var Zp=i(()=>{"use strict";He()});var eh=i(()=>{"use strict";Hi();$i();Os();Ji();Ki();Ns();Ws();Zp()});var W=i(()=>{"use strict";eh()});var Fs=i(()=>{"use strict"});var Gs=i(()=>{"use strict";Z();or();ms();Fs()});var th=i(()=>{"use strict";Gs()});var Y=i(()=>{"use strict";Gs();th();Fs()});var Qj,Xj,Mt=i(()=>{"use strict";F();Qj=new RegExp("\\p{Script=Han}+","gu"),Xj=new RegExp("^\\p{Script=Han}+$","u")});var zi=i(()=>{"use strict";F()});var qs=i(()=>{"use strict";_t()});var Qi=i(()=>{"use strict";w();qs()});var ih=i(()=>{"use strict";Mt();zi();Qi();_t()});var oh=i(()=>{"use strict";_t()});var sh=i(()=>{"use strict";Mt()});var dh=i(()=>{"use strict"});var Ks=i(()=>{"use strict";w();dh();zi()});var uh=i(()=>{"use strict";w();Mt();sh();qs();_t();Ks();Qi();Rs()});var lh=i(()=>{"use strict";ih();oh();zi();uh();Ks();_t();Qi()});var Je=i(()=>{"use strict";lh();Mt()});var Ft=i(()=>{"use strict";Y();Je();Mt();$i()});var ne=i(()=>{"use strict";ge();He();W()});var we=i(()=>{"use strict";He();W()});var _e=i(()=>{"use strict";Y();rt();W();ne()});var Ae=i(()=>{"use strict";Y();Je();W();ne();we();_e();W();Ft()});var hn=i(()=>{"use strict";Dt();Je();Ae();we()});var ed=i(()=>{"use strict";Y();cr();W();ne();_e();we()});var yr=i(()=>{"use strict";Z()});var Le=i(()=>{"use strict";Y();yr();W();ne();_e()});var ea=i(()=>{"use strict"});var gr=i(()=>{"use strict"});var br=i(()=>{"use strict";_e();Le()});var td=i(()=>{"use strict";W();Le();gr();br()});var Ih=i(()=>{"use strict";Je();Ft();W();Ae();ea();Le();gr();td();br();br();gr()});var vh=i(()=>{"use strict";Ih();td();gr();br()});var wr=i(()=>{"use strict";vh()});var Ch=i(()=>{"use strict";Dt();W();ne();_e();Le();we();wr()});var kr=i(()=>{"use strict";ne();Le();W();we();wr();Ch()});var id=i(()=>{"use strict";Y();W();ne();_e();Le();kr();xr();we()});var xr=i(()=>{"use strict";W();ne();_e();we();id()});var ia=i(()=>{"use strict";W();Ae();we()});var aa=i(()=>{"use strict";W();Je()});var oa=i(()=>{"use strict";Y();cr();Dt();Je();W();hn();ed();kr();xr();Ae();ia();aa()});var yn=i(()=>{"use strict";Je()});var Wh=i(()=>{"use strict";cr();Dt();W();Ft();hn();ed();kr();xr();oa();Ae();yn()});var Dh=i(()=>{"use strict";Wh();ia();aa();oa();hn();Ae()});var sa=i(()=>{"use strict";Le();wr();ne()});var Er=i(()=>{"use strict";W()});var da=i(()=>{"use strict";W();Ft();ne();Ae();hn();Je();Er()});var sd=i(()=>{"use strict";W();we();sa();da();Er()});var dd=i(()=>{"use strict"});var Gh=i(()=>{"use strict";yr();W();Le();sa();sd();da();Er();dd();ne();ea()});var la=i(()=>{"use strict";Gh();sd();sa();da();Er();dd()});var cd=i(()=>{"use strict";P();He();Y();yr();W();Le();wr();xr();we();la();ne();_e()});var jh=i(()=>{"use strict";P();Y();ge();He();ve();W();_e()});var Uh=i(()=>{"use strict";cd();la();ne()});var fd=i(()=>{"use strict";Dh();cd();la();Ft();ne();id();kr();jh();Uh()});var Hh=i(()=>{"use strict";fd()});var XI,$h=i(()=>{"use strict";ve();F();w();P();XI=10080*60*1e3});var Jh=i(()=>{"use strict"});var Kh=i(()=>{"use strict";w();$h();Jh()});var zh=i(()=>{"use strict"});var Qh=i(()=>{"use strict";Kh();zh()});var ut=i(()=>{"use strict";Hh();Qh();Dt()});var Ke=i(()=>{"use strict"});var lt=i(()=>{"use strict";Ke()});import{z as wd}from"zod";var Pr,ya,kd,hJ,mt=i(()=>{"use strict";Ke();Pr=1,ya=5,kd=`${JSON.stringify({formatVersion:Pr,schemaVersion:ya})}
|
|
721
|
+
`,hJ=wd.object({formatVersion:wd.literal(Pr),schemaVersion:wd.number().int().positive().optional()})});var tf=i(()=>{"use strict";y();lt();Ke();mt()});var ga=i(()=>{"use strict";y();Ke();mt();lt()});var nf=i(()=>{"use strict";Ke()});var af=i(()=>{"use strict";y();Ke();nf();mt();lt()});var cf=i(()=>{"use strict";tf();ga();mt();af()});var lf=i(()=>{"use strict";He()});var mf=i(()=>{"use strict";Z()});var Ea=i(()=>{"use strict"});var Or=i(()=>{"use strict";Mo();jn()});var Ad=i(()=>{"use strict";y();Ea();Or()});var pf=i(()=>{"use strict";Or()});var hf=i(()=>{"use strict";Ea();Or()});var Ld=i(()=>{"use strict";Or()});var ff=i(()=>{"use strict";Ad();pf();hf();Ld();Ea();Z()});var yf=i(()=>{"use strict";Ad();ff();Ld()});var gf=i(()=>{"use strict";mf();yf()});var Ia=i(()=>{"use strict";Z();y();gf();Oe()});var pt=i(()=>{"use strict"});var HK,Nr=i(()=>{"use strict";y();w();$n();pt();HK=new It(1)});var Nd=i(()=>{"use strict";w();F();pt();Nr()});var va=i(()=>{"use strict";y();F()});var Wd=i(()=>{"use strict";F();Nr();va()});var Fd=i(()=>{"use strict";y();mt();Ke();lt();ga();pt();Nd();Wd();Nr()});var xf=i(()=>{"use strict";pt();lt()});var Gd=i(()=>{"use strict";y();F();Nr()});var jd=i(()=>{"use strict";y();F();ga();mt();lt();pt();Fd();xf();Nd();Gd();Wd();va()});var Ef=i(()=>{"use strict";F();jd();Fd();Gd();pt()});async function Ra(t){let e=R().documentStore,n=0,r=0,a=0,o;try{o=await e.list()}catch(d){if(Ge(d)&&d.code==="ENOENT")return{freedBytes:a,removed:r,scanned:n};throw d}for(let d of o){if(!U(d)||!d.name.startsWith(".wikg-session-"))continue;n+=1;let c=await Ze(d);!t.force&&(c===void 0||t.now-c<gv)||(a+=await Ie(d),t.dryRun||await e.remove(d.name,{recursive:!0}),r+=1)}let s=await e.getDirectory(".wikg-cache");if(s!==void 0)for(let d of await s.list())U(d)&&(n+=1,t.force&&(a+=await Ie(d),t.dryRun||await s.remove(d.name,{recursive:!0}),r+=1));return{freedBytes:a,removed:r,scanned:n}}var gv,If=i(()=>{"use strict";y();he();gv=3600*1e3});var vf=i(()=>{"use strict";w();y();F();pt();va()});var qd=i(()=>{"use strict";Ef();jd();If();vf()});var Bd=i(()=>{"use strict";qd()});var Rf=i(()=>{"use strict";P();Ia();ut();Bd()});var Oe=i(()=>{"use strict";cf();lf();Rf();Bd()});var $d,Jd=i(()=>{"use strict";$d=["queued","running","canceling","paused","succeeded","failed","canceled"]});async function Cf(){return await Q(R().library,"jobs/work")}async function Tf(t){let e=await R().library.getDirectory("jobs");if(e!==void 0)for(let[n,r,a]of[["work",t,!0],["cache",t,!0],["logs",t,!0],["events",`${t}.ndjson`,!1]]){let o=await e.getDirectory(n);o!==void 0&&await o.remove(r,{recursive:a})}}var Wr=i(()=>{"use strict";y()});var Dr=i(()=>{"use strict";F()});var Kd=i(()=>{"use strict"});var Mr=i(()=>{"use strict";y()});var _f,Pf=i(()=>{"use strict";_f=`
|
|
640
722
|
CREATE TABLE IF NOT EXISTS build_jobs (
|
|
641
723
|
job_id TEXT PRIMARY KEY,
|
|
642
724
|
archive_key TEXT NOT NULL,
|
|
@@ -695,7 +777,7 @@ CREATE TABLE IF NOT EXISTS build_worker_lease (
|
|
|
695
777
|
|
|
696
778
|
INSERT OR IGNORE INTO build_worker_lease (id)
|
|
697
779
|
VALUES (1);
|
|
698
|
-
`});function
|
|
780
|
+
`});function qt(t){let e=Ev(Ut(t,"current_step"),"current_step"),n=Ut(t,"owner_id"),r=t.owner_pid===null?void 0:de(t,"owner_pid"),a=t.reading_summary_started_at===null?void 0:de(t,"reading_summary_started_at"),o=t.finished_at===null?void 0:de(t,"finished_at"),s=Ut(t,"error_json"),d=t.input_revision===null?void 0:de(t,"input_revision"),c=Ut(t,"llm_json"),u=Ut(t,"prompt");return{archiveKey:Ne(t,"archive_key"),archiveIdentity:Ne(t,"archive_path"),cacheLocator:Ne(t,"cache_path"),chapterId:de(t,"chapter_id"),createdAt:de(t,"created_at"),...e===void 0?{}:{currentStep:e},...s===void 0?{}:{errorJSON:s},eventsLocator:Ne(t,"events_path"),...o===void 0?{}:{finishedAt:o},jobId:Ne(t,"job_id"),...d===void 0?{}:{inputRevision:d},logLocator:Ne(t,"log_path"),...c===void 0?{}:{llmJSON:c},...n===void 0?{}:{ownerId:n},...r===void 0?{}:{ownerPid:r},...u===void 0?{}:{prompt:u},queueRank:de(t,"queue_rank"),state:xv(Ne(t,"state")),...a===void 0?{}:{readingSummaryStartedAt:a},target:Af(Ne(t,"target"),"target"),updatedAt:de(t,"updated_at"),workspaceLocator:Ne(t,"workspace_path")}}async function Gr(t){let e=_().resources,[n,r,a,o,s]=await Promise.all([e.getFile(t.archiveIdentity),zd(t.cacheLocator),kv(t.eventsLocator),zd(t.logLocator),zd(t.workspaceLocator)]);if(n===void 0)throw Fr("archive");if(r===void 0)throw Fr("cache");if(a===void 0)throw Fr("events");if(o===void 0)throw Fr("log");if(s===void 0)throw Fr("workspace");let{archiveIdentity:d,cacheLocator:c,eventsLocator:u,logLocator:m,ownerPid:b,workspaceLocator:v,...f}=t;return{...f,archive:n,cache:r,events:a,log:o,workspace:s}}async function zd(t){return t.startsWith("jobs/")?await De(R().library,t)??wv(t):await _().resources.getDirectory(t)}function wv(t){let e=R().library,n=r=>`${t}/${r}`;return{createDirectory:async r=>await Q(e,n(r)),createFile:async r=>await H(e,n(r)),getDirectory:async r=>await De(e,n(r)),getFile:async r=>await J(e,n(r)),getLastModified:async()=>await(await De(e,t))?.getLastModified?.(),identity:`managed:library:${t}`,kind:"directory",list:async()=>(await De(e,t))?.list()??[],name:t.split("/").at(-1)??t,remove:async(r,a)=>{await(await De(e,t))?.remove(r,a)}}}async function kv(t){return t.startsWith("jobs/")?await J(R().library,t):await _().resources.getFile(t)}function Fr(t){return new Error(`Build job ${t} resource is unavailable`)}function xv(t){if($d.includes(t))return t;throw new Error(`Invalid build job state: ${t}`)}function Af(t,e){if(t==="index-embedding-source"||t==="index-embedding-summary"||t==="index-fts"||t==="reading-graph"||t==="knowledge-graph"||t==="reading-summary")return t;throw new Error(`Invalid ${e}: ${t}`)}function Ev(t,e){return t===void 0?void 0:Af(t,e)}function Ne(t,e){let n=t[e];if(typeof n!="string")throw new TypeError(`Expected ${e} to be a string`);return n}function de(t,e){let n=t[e];if(typeof n!="number")throw new TypeError(`Expected ${e} to be a number`);return n}function Ut(t,e){let n=t[e];if(n!=null){if(typeof n!="string")throw new TypeError(`Expected ${e} to be a string`);return n}}var Bt=i(()=>{"use strict";Jd();y()});async function wn(){let t=await K("jobs/job.sqlite",_f);try{return await t.run(`
|
|
699
781
|
UPDATE build_jobs
|
|
700
782
|
SET workspace_path = 'jobs/work/' || job_id,
|
|
701
783
|
cache_path = 'jobs/cache/' || job_id,
|
|
@@ -705,12 +787,12 @@ VALUES (1);
|
|
|
705
787
|
OR cache_path NOT LIKE 'jobs/cache/%'
|
|
706
788
|
OR log_path NOT LIKE 'jobs/logs/%'
|
|
707
789
|
OR events_path NOT LIKE 'jobs/events/%'
|
|
708
|
-
`),t}catch(e){throw await t.close().catch(()=>{}),e}}var
|
|
790
|
+
`),t}catch(e){throw await t.close().catch(()=>{}),e}}var kn=i(()=>{"use strict";P();y();Pf();Bt()});var Ca=i(()=>{"use strict";Dr();Mr();kn();Wr()});var Ta=i(()=>{"use strict";Bt();Ca();Wr()});var Qd=i(()=>{"use strict";F();Wr();Dr();Kd();Mr();kn();Ta();Ca();ji();Bt()});var Wf=i(()=>{"use strict";Dr();kn();Ta();Bt();ji()});var Df=i(()=>{"use strict";F();Dr();Kd();Mr();kn();Ta();Ca();Qd();Bt()});function Pv(t){return Tv.has(t)}async function Av(t,e){if((await e.list()).some(a=>!Pv(a.name)))return 0;let r=await ht(e);return await t.remove(e.name,{recursive:!0}),r}async function Mf(t){let e=0,n=0,r=0;for(let a of await t.list()){if(!U(a))continue;r+=1;let o=await Ze(a);if(o===void 0||Date.now()-o<_v)continue;let s=await Av(t,a);(s>0||await t.getDirectory(a.name)===void 0)&&(e+=s,n+=1)}return{freedBytes:e,removed:n,scanned:r}}async function ht(t){return await Ie(t)}var Tv,_v,Xd=i(()=>{"use strict";y();Tv=new Set([".DS_Store"]),_v=6e4});async function _a(t){let e=await wn(),n=t.force?t.now:t.now-10080*60*1e3;try{let r=await e.queryOne("SELECT COUNT(*) AS count FROM build_jobs",void 0,c=>de(c,"count")),a=await e.queryAll(`
|
|
709
791
|
SELECT *
|
|
710
792
|
FROM build_jobs
|
|
711
793
|
WHERE state IN ('succeeded', 'failed', 'canceled')
|
|
712
794
|
AND updated_at <= ?
|
|
713
|
-
`,[n],
|
|
795
|
+
`,[n],qt),o=await Promise.all(a.map(Gr)),s=t.dryRun?{freedBytes:0,removed:0,scanned:0}:await Mf(await Cf()),d=0;for(let c of o)d+=await ht(c.workspace),d+=await ht(c.cache),d+=await ht(c.log),d+=await ht(c.events),t.dryRun||(await Tf(c.jobId),await e.run("DELETE FROM build_jobs WHERE job_id = ?",[c.jobId]));return{freedBytes:d+s.freedBytes,removed:o.length+s.removed,scanned:(r??0)+s.scanned}}finally{await e.close()}}var Ff=i(()=>{"use strict";Xd();Wr();kn();Bt()});var uc=i(()=>{"use strict";Jd();Qd();Wf();Df();Mr();Ff()});async function Uf(t){let n=await(await R().library.getDirectory("staging"))?.getDirectory("library");if(n===void 0)return{freedBytes:0,removed:0,scanned:0};let r=await Ov();if(r===void 0)return{freedBytes:0,removed:0,scanned:0};let a=new Set(r.map(u=>String(u))),o=await n.list(),s=0,d=0,c=0;for(let u of o){if(!U(u)||(s+=1,a.has(u.name)))continue;let m=Number(u.name);if(Number.isInteger(m)&&await Ep(m))continue;let b=await Ie(u);t.dryRun||await n.remove(u.name,{recursive:!0}),d+=1,c+=b}return{freedBytes:c,removed:d,scanned:s}}async function Ov(){let t=await K("core.sqlite","");try{return await t.queryAll("SELECT id FROM libraries",void 0,e=>S(e,"id"))}catch{return}finally{await t.close()}}var xn=i(()=>{"use strict";F();y();w();sr();P();Oe();Ft();yn();Mt();En();Ot();Pt();Z()});var qf=i(()=>{"use strict"});var Nv,nY,En=i(()=>{"use strict";y();w();P();He();Oe();Oe();uc();ut();ve();F();Ot();xn();Pt();qf();Nv=`
|
|
714
796
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
715
797
|
library_id INTEGER NOT NULL,
|
|
716
798
|
public_id TEXT NOT NULL,
|
|
@@ -723,9 +805,9 @@ WHERE state IN ('succeeded', 'failed', 'canceled')
|
|
|
723
805
|
created_at TEXT NOT NULL,
|
|
724
806
|
updated_at TEXT NOT NULL,
|
|
725
807
|
UNIQUE(library_id, public_id)
|
|
726
|
-
`,
|
|
808
|
+
`,nY=`
|
|
727
809
|
CREATE TABLE IF NOT EXISTS library_archives (
|
|
728
|
-
${
|
|
810
|
+
${Nv}
|
|
729
811
|
);
|
|
730
812
|
|
|
731
813
|
CREATE INDEX IF NOT EXISTS idx_library_archives_library
|
|
@@ -733,14 +815,14 @@ ${hv}
|
|
|
733
815
|
|
|
734
816
|
CREATE INDEX IF NOT EXISTS idx_library_archives_library_path
|
|
735
817
|
ON library_archives(library_id, relative_path);
|
|
736
|
-
`});var
|
|
737
|
-
prev: ${
|
|
738
|
-
text: ${
|
|
739
|
-
next: ${
|
|
818
|
+
`});var Jf=i(()=>{"use strict";ut();En();Pt();xn();Ot()});var lc=i(()=>{"use strict";Oe();En();Ot()});var Qf=i(()=>{"use strict";Hi();Ki();cr();aa();ia();hn();Ae();oa();Dt();yn();xn();lc()});var Xf=i(()=>{"use strict";fd();ea();Ki();$i();Qf();Ae();En();lc();Ot();xn();Pt()});var Oa=i(()=>{"use strict";Ot();Jf();En();Xf();xn();Pt()});function Na(t){let e=t.trim();return e===""?[]:Array.from(Jv.segment(e)).map(n=>n.segment.trim()).filter(n=>n!=="")}function xe(t){let e=t.replace(/\s+/gu," ").trim(),n=Kv(e),r="";for(let a of n)if(!zv(a)){if(!Ur(a)){r+=a;continue}r+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return r}function Kv(t){let e=[],n=0;for(;n<t.length;){let r=t[n];if(r===void 0)break;if(r!==" "){e.push(r),n+=1;continue}if(e.length>=2&&$v.has(e[e.length-1]??"")&&Ur(e[e.length-2]??"")&&n<t.length-1&&Ur(t[n+1]??"")){e.pop(),n+=1;continue}let a=e[e.length-1]??"",o=t[n+1]??"";a!==""&&o!==""&&Ur(a)&&Ur(o)&&e.push(r),n+=1}return e}function Ur(t){return t!==""&&new RegExp("\\p{Script=Latin}","u").test(t)&&new RegExp("\\p{L}","u").test(t)}function zv(t){return/[\p{P}\p{S}]/u.test(t)}var $v,Jv,qr=i(()=>{"use strict";$v=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),Jv=new Intl.Segmenter(void 0,{granularity:"sentence"})});function pc(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function Yf(t,e){let n=Wa(t,2),r=Wa(e,2),a=Wa(t,3),o=Wa(e,3);return(Vf(n,r)+Vf(a,o))/2}function Wa(t,e){if(t.length<=e)return t===""?new Set:new Set([t]);let n=new Set;for(let r=0;r<=t.length-e;r+=1)n.add(t.slice(r,r+e));return n}function Vf(t,e){if(t.size===0||e.size===0)return 0;let n=0;for(let r of t)e.has(r)&&(n+=1);return 2*n/(t.size+e.size)}function Zf(t,e){if(t===e)return 1;if(t===""||e==="")return 0;let n=Array.from({length:e.length+1},(o,s)=>s),r=new Array(e.length+1).fill(0);for(let[o,s]of[...t].entries()){r[0]=o+1;for(let[d,c]of[...e].entries()){let u=(r[d]??0)+1,m=(n[d+1]??0)+1,b=(n[d]??0)+(s===c?0:1);r[d+1]=Math.min(u,m,b)}[n,r]=[r,n]}return 1-(n[e.length]??Math.max(t.length,e.length))/Math.max(t.length,e.length)}function ey(t,e){return 1-Math.abs(t.length-e.length)/Math.max(t.length,e.length)}function ty(t,e){if(t===e)return 1;let n=t.length,r=e.length;if(n===0||r===0)return 0;let a=Array.from({length:n+1},()=>new Array(r+1).fill(0)),o=0;for(let s=1;s<=n;s+=1)for(let d=1;d<=r;d+=1){if(t[s-1]!==e[d-1])continue;let c=a[s];c!==void 0&&(c[d]=(a[s-1]?.[d-1]??0)+1,o=Math.max(o,c[d]??0))}return 2*o/(n+r)}function ny(t){return` - ${t.occurrenceId} score=${t.score.toFixed(3)}
|
|
819
|
+
prev: ${mc(t.prevText)}
|
|
820
|
+
text: ${mc(t.text,120)}
|
|
821
|
+
next: ${mc(t.nextText)}`}function mc(t,e=80){let n=t.replace(/\s+/gu," ").trim();return n===""?"(none)":n.length<=e?n:`${n.slice(0,e-3)}...`}var hc=i(()=>{"use strict"});var fc=i(()=>{"use strict"});function iy(t,e,n){return t.mode==="head_tail"?Vv(t,e):yc(t.text??"",e,n)}function Vv(t,e){let n=t.head??"",r=t.tail??"",a=xe(e),o=xe(n),s=xe(r);if(o===""||s==="")return pc();let d=a.indexOf(o),c=a.lastIndexOf(s);if(d!==-1&&c!==-1&&d<=c){let v=o.length+s.length,f=Math.min(1,v/Math.max(1,a.length));return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:c+s.length,matchStart:d,score:.82+.18*f}}let u=yc(n,e,"start_anchor"),m=yc(r,e,"end_anchor"),b=u.matchStart<=m.matchStart?1:.85;return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:Math.max(u.matchEnd,m.matchEnd),matchStart:Math.min(u.matchStart,m.matchStart),score:(u.score+m.score)/2*b}}function yc(t,e,n){let r=t.trim(),a=e.trim(),o=xe(r),s=xe(a);if(o===""||s==="")return pc();if(r===a)return{exactNormalized:!0,exactRaw:!0,exactSubstring:!0,matchEnd:s.length,matchStart:0,score:1};if(o===s)return{exactNormalized:!0,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:.995};if(s.includes(o)){let f=s.indexOf(o),k=o.length/Math.max(1,s.length),g=ry({candidateNormalized:s,label:n,matchEnd:f+o.length,matchStart:f,queryNormalized:o});return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:f+o.length,matchStart:f,score:Math.min(1,.75+.25*k+g)}}if(o.includes(s)){let f=s.length/Math.max(1,o.length);return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:Math.min(.92,.78+.14*f)}}let d=0,c=-1,u=-1,m=Math.min(s.length,Math.max(o.length,Math.floor(o.length*1.2))),b=Math.min(m,Math.max(1,Math.floor(o.length*.8))),v=new Set(o);for(let f=b;f<=m;f+=1)for(let k=0;k<=s.length-f;k+=1){let g=s.slice(k,k+f),C=new Set(g),L=new Set([...v,...C]).size,z=[...v].filter(ie=>C.has(ie)).length;if((L===0?0:z/L)<.35)continue;let j=.35*Yf(o,g)+.35*ty(o,g)+.2*Zf(o,g)+.1*ey(o,g)+ry({candidateNormalized:s,label:n,matchEnd:k+f,matchStart:k,queryNormalized:o});j>d&&(d=Math.min(1,j),c=k,u=k+f)}return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:u,matchStart:c,score:d}}function ry(t){if(t.matchStart<0||t.matchEnd<0||t.queryNormalized.length<12||t.label==="start_anchor"&&t.matchStart!==0||t.label==="end_anchor"&&t.matchEnd!==t.candidateNormalized.length)return 0;let e=t.queryNormalized.length/Math.max(1,t.candidateNormalized.length);return .08*(.5+.5*Math.min(1,e))}var ay=i(()=>{"use strict";qr();hc();fc()});function oy(t){if(t==null)return[void 0,"anchor is required"];if(typeof t=="string"){let o=t.trim();if(o==="")return[void 0,"anchor string is empty"];if(o.includes("...")){let s=o.split("...").map(d=>d.trim()).filter(d=>d!=="");if(s.length>=2){let d=s[0],c=s[s.length-1];return d===void 0||c===void 0?[void 0,"anchor string is empty"]:[{head:d,mode:"head_tail",tail:c},void 0]}}return[{mode:"full",text:o},void 0]}if(typeof t!="object")return[void 0,`expected string or object, got ${typeof t}`];let e=t;if((e.mode==="head_tail"||e.head!==void 0?"head_tail":"full")==="full"){let o=typeof e.text=="string"?e.text.trim():"";return o===""?[void 0,"full anchor requires non-empty 'text'"]:[{mode:"full",text:o},void 0]}let r=typeof e.head=="string"?e.head.trim():"",a=typeof e.tail=="string"?e.tail.trim():"";return r!==""&&a===""?[{mode:"full",text:r},void 0]:r===""&&a!==""?[{mode:"full",text:a},void 0]:r===""||a===""?[void 0,"head_tail anchor requires non-empty 'head' and 'tail'"]:[{head:r,mode:"head_tail",tail:a},void 0]}function sy(t,e){if(t===void 0)return;if(t.mode==="head_tail"){let r=e==="end_anchor"?gc(t.tail??"","end_anchor"):gc(t.head??"","start_anchor");return r===""?void 0:{mode:"full",text:r}}return{mode:"full",text:gc(t.text??"",e)}}function bc(t){return t.mode==="head_tail"?xe(t.head??"").length+xe(t.tail??"").length:xe(t.text??"").length}function gc(t,e){let n=Na(t);return n.length<=1?t.trim():e==="end_anchor"?n[n.length-1]??t.trim():n[0]??t.trim()}var dy=i(()=>{"use strict";qr()});var Ht,my=i(()=>{"use strict";ay();dy();hc();fc();Ht=class{resolve(e,n,r){let a=e.start_anchor??e.start,o=e.end_anchor??e.end,[s,d]=this.parseAnchor(a,"start_anchor");if(d!==void 0)return[void 0,d];let c;if(o!==void 0){let[g,C]=this.parseAnchor(o,"end_anchor");if(C!==void 0)return[void 0,C];c=g}let[u,m,b]=this.resolveAnchor({anchor:s,candidateSentenceIds:n,candidateTexts:r,label:"start_anchor"});if(b!==void 0)return[void 0,b];if(u===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(c===void 0)return[{confidence:u.score,sentenceIds:[u.sentenceId],strategy:m},void 0];let[v,f,k]=this.resolveAnchor({anchor:c,candidateSentenceIds:n,candidateTexts:r,label:"end_anchor",minIndex:u.index});return k!==void 0?[void 0,k]:v===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:v.index<u.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${u.occurrenceId} -> ${v.occurrenceId}).`}]:[{confidence:Math.min(u.score,v.score),sentenceIds:n.slice(u.index,v.index+1),strategy:`${m}+${f}`},void 0]}resolveWithOverrides(e){let n=e.evidence.start_anchor??e.evidence.start,r=e.evidence.end_anchor??e.evidence.end,[a,o]=this.parseAnchor(n,"start_anchor");if(o!==void 0)return[void 0,o];let s=e.overrides.start_anchor,[d,c,u]=s===void 0?this.resolveAnchor({anchor:a,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"start_anchor"}):[s,"choice_final",void 0];if(u!==void 0)return[void 0,u];if(d===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(r===void 0)return[{confidence:d.score,sentenceIds:[d.sentenceId],strategy:c},void 0];let[m,b]=this.parseAnchor(r,"end_anchor");if(b!==void 0)return[void 0,b];let v=e.overrides.end_anchor,[f,k,g]=v===void 0?this.resolveAnchor({anchor:m,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"end_anchor",minIndex:d.index}):[v,"choice_final",void 0];return g!==void 0?[void 0,g]:f===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:f.index<d.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${d.occurrenceId} -> ${f.occurrenceId}).`}]:[{confidence:Math.min(d.score,f.score),sentenceIds:e.candidateSentenceIds.slice(d.index,f.index+1),strategy:`${c}+${k}`},void 0]}parseAnchor(e,n){let[r,a]=oy(e);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:n,message:`Invalid evidence.${n}: ${a}`}]:[sy(r,n),void 0]}resolveAnchor(e){if(e.anchor===void 0)return[void 0,"invalid",{candidates:[],code:"invalid",fieldName:e.label,message:`${e.label} is missing`}];let n=this.rankAnchor(e.anchor,e.candidateSentenceIds,e.candidateTexts,e.label),r=e.minIndex;if(r!==void 0&&(n=n.filter(m=>m.index>=r)),n.length===0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let a=n.filter(m=>m.exactRaw);if(a.length===1)return[a[0],"exact_raw",void 0];if(a.length>1)return[void 0,"ambiguous_exact_raw",this.#t(e.label,"ambiguous_exact_raw",a)];let o=n.filter(m=>m.exactSubstring);if(o.length===1&&bc(e.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&bc(e.anchor)>=8){let m=this.#e(o);return m!==void 0?[m,"exact_substring_scored",void 0]:[void 0,"ambiguous_exact_substring",this.#t(e.label,"ambiguous_exact_substring",o)]}let s=n.filter(m=>m.exactNormalized);if(s.length===1)return[s[0],"exact_normalized",void 0];if(s.length>1){let m=this.#e(s);return m!==void 0?[m,"exact_normalized_scored",void 0]:[void 0,"ambiguous_exact_normalized",this.#t(e.label,"ambiguous_exact_normalized",s)]}let d=n[0];if(d===void 0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let c=n[1]?.score??0,u=d.score-c;return d.score<.55?[void 0,"low_confidence",{candidates:n.slice(0,3),code:"low_confidence",fieldName:e.label,message:`${e.label} could not be matched confidently. Best candidate score=${d.score.toFixed(3)}.`}]:n.length===1?[d,"auto_top1_single_candidate",void 0]:d.score>=.97?[d,"auto_top1_very_high",void 0]:d.score>=.9&&u>=.07?[d,"auto_top1",void 0]:[void 0,"ambiguous_ranked",this.#t(e.label,"ambiguous_ranked",n)]}rankAnchor(e,n,r,a){let o=[];for(let[s,d]of n.entries()){let c=r[s]??"",u=s>0?r[s-1]??"":"",m=s<r.length-1?r[s+1]??"":"",b=iy(e,c,a);o.push({exactNormalized:b.exactNormalized,exactRaw:b.exactRaw,exactSubstring:b.exactSubstring,index:s,nextText:m,occurrenceId:`S${s+1}`,prevText:u,score:b.score,sentenceId:d,text:c})}return o.sort((s,d)=>s.score!==d.score?d.score-s.score:s.exactRaw!==d.exactRaw?s.exactRaw?-1:1:s.exactSubstring!==d.exactSubstring?s.exactSubstring?-1:1:s.exactNormalized!==d.exactNormalized?s.exactNormalized?-1:1:s.index-d.index),o}#e(e){if(e.length===0)return;if(e.length===1)return e[0];let n=e[0];if(n===void 0)return;let r=e[1]?.score??0;if(n.score>=.9&&n.score-r>=.07)return n}#t(e,n,r){let a=r.slice(0,3),o=a.map(s=>ny(s)).join(`
|
|
740
822
|
`);return{candidates:a,code:n,fieldName:e,message:`${e} is ambiguous. Top candidates:
|
|
741
823
|
${o}
|
|
742
|
-
Please provide a more specific anchor or surrounding context.`}}}});var
|
|
743
|
-
`)});var
|
|
824
|
+
Please provide a more specific anchor or surrounding context.`}}}});var py=i(()=>{"use strict"});var hy=i(()=>{"use strict";my();py()});var Da,fy=i(()=>{"use strict";Da=["Evidence selection:",'- Return evidence as [{"sentence_id":"S1","quote":"exact short source quote"}].',"- evidence.quote is a locator for the source sentence, not a proof excerpt.","- Choose the shortest exact quote that still uniquely identifies the intended sentence.","- If the quote is too short, it may match multiple sentences; if it is too long, it may include unnecessary text or cross sentence boundaries.","- Do not use a whole sentence by default.","- evidence is an array. Use multiple items when the claim needs multiple source sentences.","- A source sentence means exactly one displayed source line labeled S1, S2, S3, etc.","- Each evidence item must point to exactly one source sentence.","- Each evidence item must quote one continuous span from exactly one labeled source line, for example only from S2.","- Never merge text from two labeled source lines into one evidence quote.","- sentence_id must be one of the sentence IDs shown in the source context.","- quote must be copied from the untagged original source sentence.","- If the source context contains XML-like tags, do not copy the tags into quote; copy only the visible text."].join(`
|
|
825
|
+
`)});var Sc=i(()=>{"use strict"});var yy=i(()=>{"use strict";Sc();qr()});var vn=i(()=>{"use strict";hy();fy();Sc();yy();qr()});import{z as Br}from"zod";var A2,by=i(()=>{"use strict";A2=Br.object({meanings:Br.array(Br.object({information:Br.string(),qid:Br.string().regex(/^Q[1-9][0-9]*$/u)}).strict())}).strict()});var Sy=i(()=>{"use strict"});var Fa=i(()=>{"use strict"});var D2,xy=i(()=>{"use strict";Fa();D2=336*60*60*1e3});var Ey=i(()=>{"use strict";Fa()});var Iy=i(()=>{"use strict";by();Sy();xy();Fa();Ey()});async function kc(t){let e=await Hr.open();try{return await e.gc(t)}finally{await e.close()}}function mR(t){try{let e=JSON.parse(t);if(typeof e!="object"||e===null)return;let n=e;return typeof n.qid!="string"||typeof n.refreshedAt!="string"||!Array.isArray(n.sites)?void 0:{qid:n.qid,refreshedAt:n.refreshedAt,sites:n.sites}}catch{return}}function pR(t){try{let e=JSON.parse(t);return typeof e.qid=="string"&&(e.wiki==="zhwiki"||e.wiki==="enwiki")&&typeof e.pageId=="number"&&typeof e.revisionId=="number"&&typeof e.parsedPage=="object"&&e.parsedPage!==null&&typeof e.profile=="object"&&e.profile!==null?e:void 0}catch{return}}var uR,lR,Hr,vy=i(()=>{"use strict";Iy();P();uR=`
|
|
744
826
|
CREATE TABLE IF NOT EXISTS wikimedia_qid_cache_v2 (
|
|
745
827
|
qid TEXT PRIMARY KEY,
|
|
746
828
|
record_json TEXT NOT NULL,
|
|
@@ -758,39 +840,39 @@ CREATE TABLE IF NOT EXISTS wikimedia_disambiguation_cache_v2 (
|
|
|
758
840
|
record_json TEXT NOT NULL,
|
|
759
841
|
PRIMARY KEY(qid,wiki,page_id,revision_id,normalizer_version,model_id)
|
|
760
842
|
);
|
|
761
|
-
|
|
762
|
-
WHERE qid IN (${e.map(()=>"?").join(",")})`,e,o=>String(o.record_json)),a=new Map;for(let o of r){let s=
|
|
843
|
+
`,lR=336*60*60*1e3,Hr=class t{#e;constructor(e){this.#e=e}static async open(){return new t(await K("cache/cache.sqlite",uR))}async getQids(e,n){if(e.length===0)return new Map;n?.signal?.throwIfAborted();let r=await this.#e.queryAll(`SELECT record_json FROM wikimedia_qid_cache_v2
|
|
844
|
+
WHERE qid IN (${e.map(()=>"?").join(",")})`,e,o=>String(o.record_json)),a=new Map;for(let o of r){let s=mR(o);s!==void 0&&a.set(s.qid,s)}return a}async putQids(e,n){n?.signal?.throwIfAborted(),await this.#e.transaction(async()=>{for(let r of e)n?.signal?.throwIfAborted(),await this.#e.run(`INSERT INTO wikimedia_qid_cache_v2(qid,record_json,refreshed_at)
|
|
763
845
|
VALUES(?,?,?)
|
|
764
846
|
ON CONFLICT(qid) DO UPDATE SET
|
|
765
847
|
record_json=excluded.record_json,
|
|
766
848
|
refreshed_at=excluded.refreshed_at`,[r.qid,JSON.stringify(r),r.refreshedAt])})}async getDisambiguations(e,n,r){if(e.length===0)return[];r?.signal?.throwIfAborted();let a=e.map(()=>"(qid=? AND wiki=? AND page_id=? AND revision_id=?)"),o=e.flatMap(d=>[d.qid,d.wiki,d.pageId,d.revisionId]);return(await this.#e.queryAll(`SELECT record_json FROM wikimedia_disambiguation_cache_v2
|
|
767
849
|
WHERE normalizer_version=? AND model_id=?
|
|
768
|
-
AND (${a.join(" OR ")})`,[n.normalizerVersion,n.modelId,...o],d=>String(d.record_json))).flatMap(d=>{let c=
|
|
850
|
+
AND (${a.join(" OR ")})`,[n.normalizerVersion,n.modelId,...o],d=>String(d.record_json))).flatMap(d=>{let c=pR(d);return c===void 0?[]:[c]})}async putDisambiguations(e,n,r){r?.signal?.throwIfAborted(),await this.#e.transaction(async()=>{for(let a of e)r?.signal?.throwIfAborted(),await this.#e.run(`INSERT INTO wikimedia_disambiguation_cache_v2(
|
|
769
851
|
qid,wiki,page_id,revision_id,normalizer_version,model_id,record_json
|
|
770
852
|
) VALUES(?,?,?,?,?,?,?)
|
|
771
853
|
ON CONFLICT(qid,wiki,page_id,revision_id,normalizer_version,model_id)
|
|
772
|
-
DO UPDATE SET record_json=excluded.record_json`,[a.qid,a.wiki,a.pageId,a.revisionId,n.normalizerVersion,n.modelId,JSON.stringify(a)])})}async close(){await this.#e.close()}async gc(e){let n=new Date(e.now-$v).toISOString(),r=await this.#e.queryOne("SELECT COUNT(*) AS count FROM wikimedia_qid_cache_v2",void 0,o=>Number(o.count))??0,a=await this.#e.queryOne("SELECT COUNT(*) AS count FROM wikimedia_qid_cache_v2 WHERE refreshed_at < ?",[n],o=>Number(o.count))??0;return!e.dryRun&&a>0&&(await this.#e.transaction(async()=>{let o=await this.#e.queryAll("SELECT qid FROM wikimedia_qid_cache_v2 WHERE refreshed_at < ?",[n],s=>String(s.qid));for(let s of o)await this.#e.run("DELETE FROM wikimedia_disambiguation_cache_v2 WHERE qid = ?",[s]);await this.#e.run("DELETE FROM wikimedia_qid_cache_v2 WHERE refreshed_at < ?",[n])}),await this.#e.run("VACUUM")),{freedBytes:0,removed:a,scanned:r}}}});var yc=i(()=>{"use strict";py()});var gc=i(()=>{"use strict"});var bc=i(()=>{"use strict"});import{jsonrepair as c2}from"jsonrepair";var hy=i(()=>{"use strict"});var fy=i(()=>{"use strict";bc();gc();hy()});var Ne=i(()=>{"use strict";gc();bc();fy()});var Br=i(()=>{"use strict"});import{z as ze}from"zod";var Yv,Zv,N2,kc=i(()=>{"use strict";Ne();Br();Yv=ze.object({candidateId:ze.string().min(1),decision:ze.enum(["continue","recall","skip_this_time","never_recall"]),qid:ze.string().nullable().optional()}).strict(),Zv=ze.object({decisions:ze.array(Yv),groupId:ze.string().min(1)}).strict(),N2=ze.object({groups:ze.array(Zv)}).strict()});import{z as Hr}from"zod";var nR,j2,by=i(()=>{"use strict";Ne();Br();kc();nR=Hr.object({decision:Hr.enum(["keep","reject"]),qid:Hr.string().regex(/^Q[1-9][0-9]*$/)}).strict(),j2=Hr.object({qids:Hr.array(nR)}).strict()});var Sy=i(()=>{"use strict"});import{z as $r}from"zod";var rR,$2,wy=i(()=>{"use strict";Ne();rR=$r.object({note:$r.string().max(24).optional(),surfaceId:$r.string().min(1)}).strict(),$2=$r.object({protectedSurfaces:$r.array(rR)}).strict()});var xc=i(()=>{"use strict"});var ky=i(()=>{"use strict";xc()});var xy=i(()=>{"use strict"});var Ic=i(()=>{"use strict"});var Iy=i(()=>{"use strict";Ic();Br()});var ft=i(()=>{"use strict";kc();by();Br();Sy();wy();ky();xc();xy();Iy();Ic()});var x3,vc=i(()=>{"use strict";nn();x3=Object.freeze({"serial-generation/editor-compress":Object.freeze({temperature:.7,topP:.9}),"serial-generation/editor-review":Object.freeze({temperature:[.3,.95],topP:[.4,.8]}),"serial-generation/editor-review-guide":Object.freeze({temperature:.4,topP:.6}),"serial-generation/reader-choice":Object.freeze({temperature:[.3,.95],topP:[.4,.8]}),"serial-generation/reader-extraction":Object.freeze({temperature:[.3,.95],topP:[.4,.8]})})});var Rc=i(()=>{"use strict";et()});var Ty=i(()=>{"use strict";Rc()});var _y=i(()=>{"use strict";Ty();Rc()});var Py=i(()=>{"use strict"});var Ay=i(()=>{"use strict"});var Ly=i(()=>{"use strict";Py();Ay()});var Jr=i(()=>{"use strict";Ne()});var Oy=i(()=>{"use strict";P();Jr()});var Ny=i(()=>{"use strict";Jr()});var Wy=i(()=>{"use strict"});import{z as x}from"zod";var Dy,gR,My,bR,SR,wR,kR,xR,IR,Da=i(()=>{"use strict";P();Dy=x.object({from:x.union([x.number().int(),x.string()]),strength:x.string().optional(),to:x.union([x.number().int(),x.string()])}),gR=x.object({quote:x.string().optional(),sentence_id:x.string().optional()}).passthrough(),My=x.union([x.record(x.string(),x.unknown()),x.array(gR)]),bR=x.object({content:x.string(),evidence:My.nullish(),label:x.string(),retention:x.enum(["verbatim","detailed","focused","relevant"]),temp_id:x.string()}).passthrough(),SR=x.object({chunks:x.array(bR),fragment_summary:x.string(),links:x.array(Dy)}),wR=x.object({content:x.string(),evidence:My.nullish(),importance:x.enum(["critical","important","helpful"]),label:x.string(),temp_id:x.string()}).passthrough(),kR=x.object({chunk_id:x.number().int(),importance:x.enum(["critical","important","helpful"])}),xR=x.object({chunks:x.array(wR),importance_annotations:x.array(kR),links:x.array(Dy)}),IR=x.object({choice:x.string()})});var Fy=i(()=>{"use strict";Ne();En();Wy();Jr();Da()});var Gy=i(()=>{"use strict";Ne();P();Oy();Jr();Ny();Fy();Da()});var jy=i(()=>{"use strict";Gy();Da()});var Ma=i(()=>{"use strict"});import{detect as L8,validateISO2 as O8}from"tinyld";var Cc=i(()=>{"use strict";Me()});var Uy=i(()=>{"use strict";Cc();Me()});var qy=i(()=>{"use strict"});import{z as Kr}from"zod";var TR,t5,Hy=i(()=>{"use strict";Ne();En();jy();Ma();Ma();Uy();qy();TR=Kr.object({content:Kr.string(),id:Kr.number(),label:Kr.string()}),t5=Kr.array(TR)});var Tc=i(()=>{"use strict";Hy()});var $y=i(()=>{"use strict";nt()});var _c=i(()=>{"use strict";$y()});var Jy=i(()=>{"use strict";Ly();Tc();_c()});var Fa=i(()=>{"use strict";Jy();_c()});var Ga=i(()=>{"use strict"});var ja=i(()=>{"use strict";Fa();Ga()});var Ky=i(()=>{"use strict";ja()});var zy=i(()=>{"use strict"});var Ua=i(()=>{"use strict"});var Qy=i(()=>{"use strict";Ua()});var Rn,A5,NR,qa=i(()=>{"use strict";Mo();Rn=(r=>(r.Critical="critical",r.Major="major",r.Minor="minor",r))(Rn||{}),A5=an(Rn),NR=Qn(Rn,"review severity")});var D5,Ac=i(()=>{"use strict";Ua();qa();D5=Object.freeze({critical:9,major:3,minor:1})});var Xy=i(()=>{"use strict";Cc();Me();qa()});var Vy=i(()=>{"use strict";y();et();Ac()});var Lc=i(()=>{"use strict";P()});var Yy=i(()=>{"use strict"});import{z as Cn}from"zod";var WR,DR,o4,Zy=i(()=>{"use strict";et();Ne();Ua();Lc();qa();WR=["critical","major","minor"],DR=Cn.object({problem:Cn.string(),severity:Cn.enum(WR),suggestion:Cn.string().default("")}),o4=Cn.object({issues:Cn.array(DR)})});var eg=i(()=>{"use strict";zy();Qy();Ac();Xy();Vy();Lc();Yy();Zy()});var Oc=i(()=>{"use strict";eg()});var ng=i(()=>{"use strict"});var rg=i(()=>{"use strict"});var ig=i(()=>{"use strict";ng();rg()});var zr=i(()=>{"use strict"});var j4,U4,Tn=i(()=>{"use strict";P();j4={critical:9,helpful:1,important:3},U4={detailed:9,focused:3,relevant:1,verbatim:27}});var _n=i(()=>{"use strict"});var Qr=i(()=>{"use strict"});var Nc=i(()=>{"use strict";_n()});var Wc=i(()=>{"use strict";Tn();_n();zr();Qr();Nc()});var Dc=i(()=>{"use strict";zr();Wc();Qr()});var og=i(()=>{"use strict";Tn();_n();Qr()});var sg=i(()=>{"use strict";Tn();_n();zr();Qr();Nc()});var dg=i(()=>{"use strict";Dc();_n();zr();og();Wc();sg()});var cg=i(()=>{"use strict";dg();Dc()});var ug=i(()=>{"use strict";Tn()});var lg=i(()=>{"use strict";cg();ug()});var mg=i(()=>{"use strict";ig();lg();Tn()});var pg=i(()=>{"use strict";mg()});var Mc=i(()=>{"use strict";Z()});var hg=i(()=>{"use strict"});var Fc=i(()=>{"use strict";ja()});var Ha=i(()=>{"use strict"});var fg=i(()=>{"use strict";Hn();nn();Oc();Fa();pg();ja();Ga();Mc();hg();Fc();Ha()});var yg=i(()=>{"use strict";Mc();Ha();Z()});var gg=i(()=>{"use strict";Ky();fg();Ga();yg();Fc();Ha()});var Pn=i(()=>{"use strict";gg()});var bg=i(()=>{"use strict";ye();Hn();Pn();at()});var Sg=i(()=>{"use strict";at();at();P();ye();_y();Pn();bg();ka();y()});var Uc,yt=i(()=>{"use strict";Uc=["Recall only source mentions that should become stable searchable knowledge graph objects.","Prefer named entities: historical persons, places, organizations, dynasties, political entities, named works, named events, battles, titles, and explicitly named domain concepts.","Recall a non-named common concept only when it is a central recurring topic of the chapter and would be useful as an entity search result across multiple evidence passages.","Do not recall a surface merely because it is useful for summarizing the story or explaining a detail.","Do not recall pure numbers, standalone dates without a named event role, units of measurement, dimensions, ordinal labels, chapter numbers, punctuation fragments, common function words, generic verbs, generic adjectives, generic roles, generic objects, or incidental attributes.","Measurements, quantities, dimensions, tactical details, and descriptive attributes should remain evidence text, not entity mentions.","When uncertain, skip the mention rather than creating a noisy knowledge graph object."].join(" ")});var qc=i(()=>{"use strict";yt()});var xg=i(()=>{"use strict";et();Ao();Sg();vc();Le();qc();y()});var $a=i(()=>{"use strict"});import{z as p}from"zod";var Ig,V,zR,QR,Eg,XR,VR,YR,ZR,eC,tC,nC,rC,iC,aC,oC,sC,dC,cC,T9,An=i(()=>{"use strict";y();Re();$a();Ig=1,V=p.number().int().nonnegative(),zR=p.literal(Ig),QR=p.string().regex(/^Q[1-9][0-9]*$/u),Eg=p.number().min(0).max(1).optional(),XR=p.object({text:p.string(),wordsCount:V}).strict(),VR=p.object({type:p.literal("meta"),schemaVersion:zR,chapterId:p.number().int(),stream:p.enum(["knowledge-graph","reading-graph","summary"])}).strict(),YR=p.object({type:p.literal("parameter"),scope:p.enum(["knowledge-graph","reading-graph","summary"]),language:p.string().optional(),prompt:p.string()}).strict(),ZR=p.object({type:p.literal("source-fragment"),fragmentId:V,summary:p.string(),sentences:p.array(XR)}).strict(),eC=p.object({type:p.literal("reading-chunk"),id:p.string().min(1),generation:p.number().int(),sentenceIndex:V,label:p.string(),content:p.string(),sentenceIndexes:p.array(V).min(1),retention:p.enum(he).optional(),importance:p.enum(ve).optional(),wordsCount:V,weight:p.number()}).strict(),tC=p.object({type:p.literal("reading-edge"),fromChunkId:p.string().min(1),toChunkId:p.string().min(1),strength:p.string().optional(),weight:p.number()}).strict(),nC=p.object({type:p.literal("fragment-group"),groupId:V,startSentenceIndex:V,endSentenceIndex:V}).strict(),rC=p.object({type:p.literal("snake"),id:p.string().min(1),groupId:V,localSnakeId:V,size:V,firstLabel:p.string(),lastLabel:p.string(),wordsCount:V,weight:p.number()}).strict(),iC=p.object({type:p.literal("snake-chunk"),snakeId:p.string().min(1),chunkId:p.string().min(1),position:V}).strict(),aC=p.object({type:p.literal("snake-edge"),fromSnakeId:p.string().min(1),toSnakeId:p.string().min(1),weight:p.number()}).strict(),oC=p.object({type:p.literal("summary"),text:p.string()}).strict(),sC=p.object({type:p.literal("mention"),id:p.string().min(1),fragmentId:V.optional(),sentenceIndex:V.optional(),rangeStart:V,rangeEnd:V,surface:p.string().min(1),qid:QR,confidence:Eg,note:p.string().optional()}).strict(),dC=p.object({type:p.literal("mention-link"),id:p.string().min(1),sourceMentionId:p.string().min(1),targetMentionId:p.string().min(1),predicate:p.string().min(1),evidenceSentenceIndexes:p.array(V).min(1),confidence:Eg,note:p.string().optional()}).strict(),cC=p.object({type:p.literal("end")}).strict(),T9=p.discriminatedUnion("type",[VR,YR,ZR,eC,tC,nC,rC,iC,aC,oC,sC,dC,cC])});var vg=i(()=>{"use strict"});var Rg=i(()=>{"use strict"});import{sha256 as O9}from"@noble/hashes/sha2.js";var N9,W9,Bc=i(()=>{"use strict";N9=new RegExp("\\p{Script=Han}+","gu"),W9=new RegExp("^\\p{Script=Han}+$","u")});var Hc=i(()=>{"use strict";Bc()});import{z as l}from"zod";function Cg(){return l.object({content:l.string(),generation:l.number().int(),id:l.string(),importance:l.enum(["critical","helpful","important"]).optional(),label:l.string(),retention:l.enum(["detailed","focused","relevant","verbatim"]).optional(),sentenceIndex:A,sentenceIndexes:l.array(A),type:l.literal("reading-chunk"),weight:l.number(),wordsCount:A})}function Tg(){return l.object({fromChunkId:l.string(),strength:l.string().optional(),toChunkId:l.string(),type:l.literal("reading-edge"),weight:l.number()})}function _g(){return l.object({endSentenceIndex:A,groupId:A,startSentenceIndex:A,type:l.literal("fragment-group")})}function Pg(){return l.object({firstLabel:l.string(),groupId:A,id:l.string(),lastLabel:l.string(),localSnakeId:A,size:A,type:l.literal("snake"),weight:l.number(),wordsCount:A})}function Ag(){return l.object({chunkId:l.string(),position:A,snakeId:l.string(),type:l.literal("snake-chunk")})}function Lg(){return l.object({fromSnakeId:l.string(),toSnakeId:l.string(),type:l.literal("snake-edge"),weight:l.number()})}function Og(){return l.object({confidence:l.number().optional(),fragmentId:A.optional(),id:l.string(),note:l.string().optional(),qid:l.string(),rangeEnd:A,rangeStart:A,sentenceIndex:A.optional(),surface:l.string(),type:l.literal("mention")})}function uC(){return l.object({confidence:l.number().optional(),evidenceSentenceIndexes:l.array(A),id:l.string(),note:l.string().optional(),predicate:l.string(),sourceMentionId:l.string(),targetMentionId:l.string(),type:l.literal("mention-link")})}var A,$c,U9,q9,$t=i(()=>{"use strict";A=l.number().int().nonnegative(),$c={sentenceIndex:A,text:l.string(),wordsCount:A},U9=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string().optional(),type:l.literal("job-options")}),l.object({...$c,fragmentId:A.optional(),type:l.literal("source-text")}),l.object({fragmentId:A,summary:l.string(),type:l.literal("source-fragment")}),l.object({...$c,fragmentId:A.optional(),type:l.literal("source-sentence")}),l.object({...$c,type:l.literal("summary-sentence")}),l.object({chapterId:l.number().int(),title:l.string(),type:l.literal("chapter-title")}),Cg(),Tg(),_g(),Pg(),Ag(),Lg(),Og()]),q9=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string(),scope:l.enum(["knowledge-graph","reading-graph"]),type:l.literal("job-parameter")}),Cg(),Tg(),_g(),Pg(),Ag(),Lg(),Og(),uC(),l.object({position:A,text:l.string(),type:l.literal("summary-part")}),l.object({metadata:l.record(l.string(),l.unknown()),objectId:l.string(),objectKind:l.string(),rowId:l.string(),sentenceIndex:A.optional(),text:l.string(),tokens:l.array(l.string()),type:l.literal("lexical-row")}),l.object({dimensions:A,identity:l.string().optional(),model:l.string(),source:l.enum(["source","summary"]),type:l.literal("embedding-metadata"),version:l.literal(1)}),l.object({endSentenceIndex:A,segmentIndex:A,startSentenceIndex:A,text:l.string(),type:l.literal("embedding-segment"),vector:l.array(l.number()),wordsCount:A})])});var Jc=i(()=>{"use strict";$t()});var Kc=i(()=>{"use strict"});var Jt,zc=i(()=>{"use strict";Jt=["Classify the raw assistant reply into exactly one label.","Labels:","- malformed_json: the reply is trying to provide JSON, but it is broken or truncated","- natural_language: the reply is plain conversational language, apology, refusal, or explanation instead of JSON","- ambiguous: unclear or mixed","Reply with the label only."].join(`
|
|
773
|
-
`)});import{jsonrepair as
|
|
774
|
-
prev: ${
|
|
775
|
-
text: ${
|
|
776
|
-
next: ${
|
|
854
|
+
DO UPDATE SET record_json=excluded.record_json`,[a.qid,a.wiki,a.pageId,a.revisionId,n.normalizerVersion,n.modelId,JSON.stringify(a)])})}async close(){await this.#e.close()}async gc(e){let n=new Date(e.now-lR).toISOString(),r=await this.#e.queryOne("SELECT COUNT(*) AS count FROM wikimedia_qid_cache_v2",void 0,o=>Number(o.count))??0,a=await this.#e.queryOne("SELECT COUNT(*) AS count FROM wikimedia_qid_cache_v2 WHERE refreshed_at < ?",[n],o=>Number(o.count))??0;return!e.dryRun&&a>0&&(await this.#e.transaction(async()=>{let o=await this.#e.queryAll("SELECT qid FROM wikimedia_qid_cache_v2 WHERE refreshed_at < ?",[n],s=>String(s.qid));for(let s of o)await this.#e.run("DELETE FROM wikimedia_disambiguation_cache_v2 WHERE qid = ?",[s]);await this.#e.run("DELETE FROM wikimedia_qid_cache_v2 WHERE refreshed_at < ?",[n])}),await this.#e.run("VACUUM")),{freedBytes:0,removed:a,scanned:r}}}});var Ec=i(()=>{"use strict";vy()});var Ic=i(()=>{"use strict"});var vc=i(()=>{"use strict"});import{jsonrepair as n3}from"jsonrepair";var Ry=i(()=>{"use strict"});var Cy=i(()=>{"use strict";vc();Ic();Ry()});var We=i(()=>{"use strict";Ic();vc();Cy()});var $r=i(()=>{"use strict"});import{z as Qe}from"zod";var bR,SR,C3,Tc=i(()=>{"use strict";We();$r();bR=Qe.object({candidateId:Qe.string().min(1),decision:Qe.enum(["continue","recall","skip_this_time","never_recall"]),qid:Qe.string().nullable().optional()}).strict(),SR=Qe.object({decisions:Qe.array(bR),groupId:Qe.string().min(1)}).strict(),C3=Qe.object({groups:Qe.array(SR)}).strict()});import{z as Jr}from"zod";var xR,O3,Py=i(()=>{"use strict";We();$r();Tc();xR=Jr.object({decision:Jr.enum(["keep","reject"]),qid:Jr.string().regex(/^Q[1-9][0-9]*$/)}).strict(),O3=Jr.object({qids:Jr.array(xR)}).strict()});var Ay=i(()=>{"use strict"});import{z as Kr}from"zod";var ER,F3,Ly=i(()=>{"use strict";We();ER=Kr.object({note:Kr.string().max(24).optional(),surfaceId:Kr.string().min(1)}).strict(),F3=Kr.object({protectedSurfaces:Kr.array(ER)}).strict()});var _c=i(()=>{"use strict"});var Oy=i(()=>{"use strict";_c()});var Ny=i(()=>{"use strict"});var Pc=i(()=>{"use strict"});var Wy=i(()=>{"use strict";Pc();$r()});var yt=i(()=>{"use strict";Tc();Py();$r();Ay();Ly();Oy();_c();Ny();Wy();Pc()});var f8,Lc=i(()=>{"use strict";rn();f8=Object.freeze({"serial-generation/editor-compress":Object.freeze({temperature:.7,topP:.9}),"serial-generation/editor-review":Object.freeze({temperature:[.3,.95],topP:[.4,.8]}),"serial-generation/editor-review-guide":Object.freeze({temperature:.4,topP:.6}),"serial-generation/reader-choice":Object.freeze({temperature:[.3,.95],topP:[.4,.8]}),"serial-generation/reader-extraction":Object.freeze({temperature:[.3,.95],topP:[.4,.8]})})});var Oc=i(()=>{"use strict";tt()});var jy=i(()=>{"use strict";Oc()});var Uy=i(()=>{"use strict";jy();Oc()});var qy=i(()=>{"use strict"});var By=i(()=>{"use strict"});var Hy=i(()=>{"use strict";qy();By()});var zr=i(()=>{"use strict";We()});var $y=i(()=>{"use strict";P();zr()});var Jy=i(()=>{"use strict";zr()});var Ky=i(()=>{"use strict"});import{z as x}from"zod";var zy,MR,Qy,FR,GR,jR,UR,qR,BR,Ga=i(()=>{"use strict";P();zy=x.object({from:x.union([x.number().int(),x.string()]),strength:x.string().optional(),to:x.union([x.number().int(),x.string()])}),MR=x.object({quote:x.string().optional(),sentence_id:x.string().optional()}).passthrough(),Qy=x.union([x.record(x.string(),x.unknown()),x.array(MR)]),FR=x.object({content:x.string(),evidence:Qy.nullish(),label:x.string(),retention:x.enum(["verbatim","detailed","focused","relevant"]),temp_id:x.string()}).passthrough(),GR=x.object({chunks:x.array(FR),fragment_summary:x.string(),links:x.array(zy)}),jR=x.object({content:x.string(),evidence:Qy.nullish(),importance:x.enum(["critical","important","helpful"]),label:x.string(),temp_id:x.string()}).passthrough(),UR=x.object({chunk_id:x.number().int(),importance:x.enum(["critical","important","helpful"])}),qR=x.object({chunks:x.array(jR),importance_annotations:x.array(UR),links:x.array(zy)}),BR=x.object({choice:x.string()})});var Xy=i(()=>{"use strict";We();vn();Ky();zr();Ga()});var Vy=i(()=>{"use strict";We();P();$y();zr();Jy();Xy();Ga()});var Yy=i(()=>{"use strict";Vy();Ga()});var ja=i(()=>{"use strict"});import{detect as v5,validateISO2 as R5}from"tinyld";var Nc=i(()=>{"use strict";Fe()});var Zy=i(()=>{"use strict";Nc();Fe()});var eg=i(()=>{"use strict"});import{z as Qr}from"zod";var zR,z5,ng=i(()=>{"use strict";We();vn();Yy();ja();ja();Zy();eg();zR=Qr.object({content:Qr.string(),id:Qr.number(),label:Qr.string()}),z5=Qr.array(zR)});var Wc=i(()=>{"use strict";ng()});var rg=i(()=>{"use strict";rt()});var Dc=i(()=>{"use strict";rg()});var ig=i(()=>{"use strict";Hy();Wc();Dc()});var Ua=i(()=>{"use strict";ig();Dc()});var qa=i(()=>{"use strict"});var Ba=i(()=>{"use strict";Ua();qa()});var ag=i(()=>{"use strict";Ba()});var og=i(()=>{"use strict"});var Ha=i(()=>{"use strict"});var sg=i(()=>{"use strict";Ha()});var Cn,I4,eC,$a=i(()=>{"use strict";Uo();Cn=(r=>(r.Critical="critical",r.Major="major",r.Minor="minor",r))(Cn||{}),I4=on(Cn),eC=Xn(Cn,"review severity")});var _4,Fc=i(()=>{"use strict";Ha();$a();_4=Object.freeze({critical:9,major:3,minor:1})});var dg=i(()=>{"use strict";Nc();Fe();$a()});var cg=i(()=>{"use strict";y();tt();Fc()});var Gc=i(()=>{"use strict";P()});var ug=i(()=>{"use strict"});import{z as Tn}from"zod";var tC,nC,Z4,lg=i(()=>{"use strict";tt();We();Ha();Gc();$a();tC=["critical","major","minor"],nC=Tn.object({problem:Tn.string(),severity:Tn.enum(tC),suggestion:Tn.string().default("")}),Z4=Tn.object({issues:Tn.array(nC)})});var mg=i(()=>{"use strict";og();sg();Fc();dg();cg();Gc();ug();lg()});var jc=i(()=>{"use strict";mg()});var hg=i(()=>{"use strict"});var fg=i(()=>{"use strict"});var yg=i(()=>{"use strict";hg();fg()});var Xr=i(()=>{"use strict"});var OZ,NZ,_n=i(()=>{"use strict";P();OZ={critical:9,helpful:1,important:3},NZ={detailed:9,focused:3,relevant:1,verbatim:27}});var Pn=i(()=>{"use strict"});var Vr=i(()=>{"use strict"});var Uc=i(()=>{"use strict";Pn()});var qc=i(()=>{"use strict";_n();Pn();Xr();Vr();Uc()});var Bc=i(()=>{"use strict";Xr();qc();Vr()});var bg=i(()=>{"use strict";_n();Pn();Vr()});var Sg=i(()=>{"use strict";_n();Pn();Xr();Vr();Uc()});var wg=i(()=>{"use strict";Bc();Pn();Xr();bg();qc();Sg()});var kg=i(()=>{"use strict";wg();Bc()});var xg=i(()=>{"use strict";_n()});var Eg=i(()=>{"use strict";kg();xg()});var Ig=i(()=>{"use strict";yg();Eg();_n()});var vg=i(()=>{"use strict";Ig()});var Hc=i(()=>{"use strict";Z()});var Rg=i(()=>{"use strict"});var $c=i(()=>{"use strict";Ba()});var Ka=i(()=>{"use strict"});var Cg=i(()=>{"use strict";$n();rn();jc();Ua();vg();Ba();qa();Hc();Rg();$c();Ka()});var Tg=i(()=>{"use strict";Hc();Ka();Z()});var _g=i(()=>{"use strict";ag();Cg();qa();Tg();$c();Ka()});var An=i(()=>{"use strict";_g()});var Pg=i(()=>{"use strict";ge();$n();An();ot()});var Ag=i(()=>{"use strict";ot();ot();P();ge();Uy();An();Pg();Ia();y()});var zc,gt=i(()=>{"use strict";zc=["Recall only source mentions that should become stable searchable knowledge graph objects.","Prefer named entities: historical persons, places, organizations, dynasties, political entities, named works, named events, battles, titles, and explicitly named domain concepts.","Recall a non-named common concept only when it is a central recurring topic of the chapter and would be useful as an entity search result across multiple evidence passages.","Do not recall a surface merely because it is useful for summarizing the story or explaining a detail.","Do not recall pure numbers, standalone dates without a named event role, units of measurement, dimensions, ordinal labels, chapter numbers, punctuation fragments, common function words, generic verbs, generic adjectives, generic roles, generic objects, or incidental attributes.","Measurements, quantities, dimensions, tactical details, and descriptive attributes should remain evidence text, not entity mentions.","When uncertain, skip the mention rather than creating a noisy knowledge graph object."].join(" ")});var Qc=i(()=>{"use strict";gt()});var Ng=i(()=>{"use strict";tt();Wo();Ag();Lc();Oe();Qc();y()});var za=i(()=>{"use strict"});import{z as p}from"zod";var Wg,V,hC,fC,Dg,yC,gC,bC,SC,wC,kC,xC,EC,IC,vC,RC,CC,TC,_C,k7,Ln=i(()=>{"use strict";y();Ce();za();Wg=1,V=p.number().int().nonnegative(),hC=p.literal(Wg),fC=p.string().regex(/^Q[1-9][0-9]*$/u),Dg=p.number().min(0).max(1).optional(),yC=p.object({text:p.string(),wordsCount:V}).strict(),gC=p.object({type:p.literal("meta"),schemaVersion:hC,chapterId:p.number().int(),stream:p.enum(["knowledge-graph","reading-graph","summary"])}).strict(),bC=p.object({type:p.literal("parameter"),scope:p.enum(["knowledge-graph","reading-graph","summary"]),language:p.string().optional(),prompt:p.string()}).strict(),SC=p.object({type:p.literal("source-fragment"),fragmentId:V,summary:p.string(),sentences:p.array(yC)}).strict(),wC=p.object({type:p.literal("reading-chunk"),id:p.string().min(1),generation:p.number().int(),sentenceIndex:V,label:p.string(),content:p.string(),sentenceIndexes:p.array(V).min(1),retention:p.enum(fe).optional(),importance:p.enum(Re).optional(),wordsCount:V,weight:p.number()}).strict(),kC=p.object({type:p.literal("reading-edge"),fromChunkId:p.string().min(1),toChunkId:p.string().min(1),strength:p.string().optional(),weight:p.number()}).strict(),xC=p.object({type:p.literal("fragment-group"),groupId:V,startSentenceIndex:V,endSentenceIndex:V}).strict(),EC=p.object({type:p.literal("snake"),id:p.string().min(1),groupId:V,localSnakeId:V,size:V,firstLabel:p.string(),lastLabel:p.string(),wordsCount:V,weight:p.number()}).strict(),IC=p.object({type:p.literal("snake-chunk"),snakeId:p.string().min(1),chunkId:p.string().min(1),position:V}).strict(),vC=p.object({type:p.literal("snake-edge"),fromSnakeId:p.string().min(1),toSnakeId:p.string().min(1),weight:p.number()}).strict(),RC=p.object({type:p.literal("summary"),text:p.string()}).strict(),CC=p.object({type:p.literal("mention"),id:p.string().min(1),fragmentId:V.optional(),sentenceIndex:V.optional(),rangeStart:V,rangeEnd:V,surface:p.string().min(1),qid:fC,confidence:Dg,note:p.string().optional()}).strict(),TC=p.object({type:p.literal("mention-link"),id:p.string().min(1),sourceMentionId:p.string().min(1),targetMentionId:p.string().min(1),predicate:p.string().min(1),evidenceSentenceIndexes:p.array(V).min(1),confidence:Dg,note:p.string().optional()}).strict(),_C=p.object({type:p.literal("end")}).strict(),k7=p.discriminatedUnion("type",[gC,bC,SC,wC,kC,xC,EC,IC,vC,RC,CC,TC,_C])});var Mg=i(()=>{"use strict"});var Fg=i(()=>{"use strict"});import{sha256 as R7}from"@noble/hashes/sha2.js";var C7,T7,Xc=i(()=>{"use strict";C7=new RegExp("\\p{Script=Han}+","gu"),T7=new RegExp("^\\p{Script=Han}+$","u")});var Vc=i(()=>{"use strict";Xc()});import{z as l}from"zod";function Gg(){return l.object({content:l.string(),generation:l.number().int(),id:l.string(),importance:l.enum(["critical","helpful","important"]).optional(),label:l.string(),retention:l.enum(["detailed","focused","relevant","verbatim"]).optional(),sentenceIndex:A,sentenceIndexes:l.array(A),type:l.literal("reading-chunk"),weight:l.number(),wordsCount:A})}function jg(){return l.object({fromChunkId:l.string(),strength:l.string().optional(),toChunkId:l.string(),type:l.literal("reading-edge"),weight:l.number()})}function Ug(){return l.object({endSentenceIndex:A,groupId:A,startSentenceIndex:A,type:l.literal("fragment-group")})}function qg(){return l.object({firstLabel:l.string(),groupId:A,id:l.string(),lastLabel:l.string(),localSnakeId:A,size:A,type:l.literal("snake"),weight:l.number(),wordsCount:A})}function Bg(){return l.object({chunkId:l.string(),position:A,snakeId:l.string(),type:l.literal("snake-chunk")})}function Hg(){return l.object({fromSnakeId:l.string(),toSnakeId:l.string(),type:l.literal("snake-edge"),weight:l.number()})}function $g(){return l.object({confidence:l.number().optional(),fragmentId:A.optional(),id:l.string(),note:l.string().optional(),qid:l.string(),rangeEnd:A,rangeStart:A,sentenceIndex:A.optional(),surface:l.string(),type:l.literal("mention")})}function PC(){return l.object({confidence:l.number().optional(),evidenceSentenceIndexes:l.array(A),id:l.string(),note:l.string().optional(),predicate:l.string(),sourceMentionId:l.string(),targetMentionId:l.string(),type:l.literal("mention-link")})}var A,Yc,N7,W7,Jt=i(()=>{"use strict";A=l.number().int().nonnegative(),Yc={sentenceIndex:A,text:l.string(),wordsCount:A},N7=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string().optional(),type:l.literal("job-options")}),l.object({...Yc,fragmentId:A.optional(),type:l.literal("source-text")}),l.object({fragmentId:A,summary:l.string(),type:l.literal("source-fragment")}),l.object({...Yc,fragmentId:A.optional(),type:l.literal("source-sentence")}),l.object({...Yc,type:l.literal("summary-sentence")}),l.object({chapterId:l.number().int(),title:l.string(),type:l.literal("chapter-title")}),Gg(),jg(),Ug(),qg(),Bg(),Hg(),$g()]),W7=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string(),scope:l.enum(["knowledge-graph","reading-graph"]),type:l.literal("job-parameter")}),Gg(),jg(),Ug(),qg(),Bg(),Hg(),$g(),PC(),l.object({position:A,text:l.string(),type:l.literal("summary-part")}),l.object({metadata:l.record(l.string(),l.unknown()),objectId:l.string(),objectKind:l.string(),rowId:l.string(),sentenceIndex:A.optional(),text:l.string(),tokens:l.array(l.string()),type:l.literal("lexical-row")}),l.object({dimensions:A,identity:l.string().optional(),model:l.string(),source:l.enum(["source","summary"]),type:l.literal("embedding-metadata"),version:l.literal(1)}),l.object({endSentenceIndex:A,segmentIndex:A,startSentenceIndex:A,text:l.string(),type:l.literal("embedding-segment"),vector:l.array(l.number()),wordsCount:A})])});var Zc=i(()=>{"use strict";Jt()});var eu=i(()=>{"use strict"});var Kt,tu=i(()=>{"use strict";Kt=["Classify the raw assistant reply into exactly one label.","Labels:","- malformed_json: the reply is trying to provide JSON, but it is broken or truncated","- natural_language: the reply is plain conversational language, apology, refusal, or explanation instead of JSON","- ambiguous: unclear or mixed","Reply with the label only."].join(`
|
|
855
|
+
`)});import{jsonrepair as q7}from"jsonrepair";var Jg=i(()=>{"use strict"});var Kg=i(()=>{"use strict";tu();eu();Jg()});var le=i(()=>{"use strict";eu();tu();Kg()});var Xg=i(()=>{"use strict"});var Yr=i(()=>{"use strict"});import{z as Ve}from"zod";var NC,WC,hee,ru=i(()=>{"use strict";le();Yr();NC=Ve.object({candidateId:Ve.string().min(1),decision:Ve.enum(["continue","recall","skip_this_time","never_recall"]),qid:Ve.string().nullable().optional()}).strict(),WC=Ve.object({decisions:Ve.array(NC),groupId:Ve.string().min(1)}).strict(),hee=Ve.object({groups:Ve.array(WC)}).strict()});import{z as Zr}from"zod";var MC,xee,Yg=i(()=>{"use strict";le();Yr();ru();MC=Zr.object({decision:Zr.enum(["keep","reject"]),qid:Zr.string().regex(/^Q[1-9][0-9]*$/)}).strict(),xee=Zr.object({qids:Zr.array(MC)}).strict()});var iu=i(()=>{"use strict"});import{z as ei}from"zod";var FC,Cee,Zg=i(()=>{"use strict";le();FC=ei.object({note:ei.string().max(24).optional(),surfaceId:ei.string().min(1)}).strict(),Cee=ei.object({protectedSurfaces:ei.array(FC)}).strict()});var eb=i(()=>{"use strict";iu()});var tb=i(()=>{"use strict"});var au=i(()=>{"use strict"});var nb=i(()=>{"use strict";au();Yr()});var ti=i(()=>{"use strict";Xg();Yg();Yr();ru();iu();Zg();eb();tb();nb();au()});var Xa=i(()=>{"use strict"});var rb=i(()=>{"use strict";ti();Xa()});var ib=i(()=>{"use strict";ti()});var ou=i(()=>{"use strict"});var ab=i(()=>{"use strict";ti();Xa();ib();ou()});function Va(t){let e=t.trim();return e===""?[]:Array.from(UC.segment(e)).map(n=>n.segment.trim()).filter(n=>n!=="")}function Ee(t){let e=t.replace(/\s+/gu," ").trim(),n=qC(e),r="";for(let a of n)if(!BC(a)){if(!ni(a)){r+=a;continue}r+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return r}function qC(t){let e=[],n=0;for(;n<t.length;){let r=t[n];if(r===void 0)break;if(r!==" "){e.push(r),n+=1;continue}if(e.length>=2&&jC.has(e[e.length-1]??"")&&ni(e[e.length-2]??"")&&n<t.length-1&&ni(t[n+1]??"")){e.pop(),n+=1;continue}let a=e[e.length-1]??"",o=t[n+1]??"";a!==""&&o!==""&&ni(a)&&ni(o)&&e.push(r),n+=1}return e}function ni(t){return t!==""&&new RegExp("\\p{Script=Latin}","u").test(t)&&new RegExp("\\p{L}","u").test(t)}function BC(t){return/[\p{P}\p{S}]/u.test(t)}var jC,UC,ri=i(()=>{"use strict";jC=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),UC=new Intl.Segmenter(void 0,{granularity:"sentence"})});function du(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function sb(t,e){let n=Ya(t,2),r=Ya(e,2),a=Ya(t,3),o=Ya(e,3);return(ob(n,r)+ob(a,o))/2}function Ya(t,e){if(t.length<=e)return t===""?new Set:new Set([t]);let n=new Set;for(let r=0;r<=t.length-e;r+=1)n.add(t.slice(r,r+e));return n}function ob(t,e){if(t.size===0||e.size===0)return 0;let n=0;for(let r of t)e.has(r)&&(n+=1);return 2*n/(t.size+e.size)}function db(t,e){if(t===e)return 1;if(t===""||e==="")return 0;let n=Array.from({length:e.length+1},(o,s)=>s),r=new Array(e.length+1).fill(0);for(let[o,s]of[...t].entries()){r[0]=o+1;for(let[d,c]of[...e].entries()){let u=(r[d]??0)+1,m=(n[d+1]??0)+1,b=(n[d]??0)+(s===c?0:1);r[d+1]=Math.min(u,m,b)}[n,r]=[r,n]}return 1-(n[e.length]??Math.max(t.length,e.length))/Math.max(t.length,e.length)}function cb(t,e){return 1-Math.abs(t.length-e.length)/Math.max(t.length,e.length)}function ub(t,e){if(t===e)return 1;let n=t.length,r=e.length;if(n===0||r===0)return 0;let a=Array.from({length:n+1},()=>new Array(r+1).fill(0)),o=0;for(let s=1;s<=n;s+=1)for(let d=1;d<=r;d+=1){if(t[s-1]!==e[d-1])continue;let c=a[s];c!==void 0&&(c[d]=(a[s-1]?.[d-1]??0)+1,o=Math.max(o,c[d]??0))}return 2*o/(n+r)}function lb(t){return` - ${t.occurrenceId} score=${t.score.toFixed(3)}
|
|
856
|
+
prev: ${su(t.prevText)}
|
|
857
|
+
text: ${su(t.text,120)}
|
|
858
|
+
next: ${su(t.nextText)}`}function su(t,e=80){let n=t.replace(/\s+/gu," ").trim();return n===""?"(none)":n.length<=e?n:`${n.slice(0,e-3)}...`}var cu=i(()=>{"use strict"});var uu=i(()=>{"use strict"});function pb(t,e,n){return t.mode==="head_tail"?JC(t,e):lu(t.text??"",e,n)}function JC(t,e){let n=t.head??"",r=t.tail??"",a=Ee(e),o=Ee(n),s=Ee(r);if(o===""||s==="")return du();let d=a.indexOf(o),c=a.lastIndexOf(s);if(d!==-1&&c!==-1&&d<=c){let v=o.length+s.length,f=Math.min(1,v/Math.max(1,a.length));return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:c+s.length,matchStart:d,score:.82+.18*f}}let u=lu(n,e,"start_anchor"),m=lu(r,e,"end_anchor"),b=u.matchStart<=m.matchStart?1:.85;return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:Math.max(u.matchEnd,m.matchEnd),matchStart:Math.min(u.matchStart,m.matchStart),score:(u.score+m.score)/2*b}}function lu(t,e,n){let r=t.trim(),a=e.trim(),o=Ee(r),s=Ee(a);if(o===""||s==="")return du();if(r===a)return{exactNormalized:!0,exactRaw:!0,exactSubstring:!0,matchEnd:s.length,matchStart:0,score:1};if(o===s)return{exactNormalized:!0,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:.995};if(s.includes(o)){let f=s.indexOf(o),k=o.length/Math.max(1,s.length),g=mb({candidateNormalized:s,label:n,matchEnd:f+o.length,matchStart:f,queryNormalized:o});return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:f+o.length,matchStart:f,score:Math.min(1,.75+.25*k+g)}}if(o.includes(s)){let f=s.length/Math.max(1,o.length);return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:Math.min(.92,.78+.14*f)}}let d=0,c=-1,u=-1,m=Math.min(s.length,Math.max(o.length,Math.floor(o.length*1.2))),b=Math.min(m,Math.max(1,Math.floor(o.length*.8))),v=new Set(o);for(let f=b;f<=m;f+=1)for(let k=0;k<=s.length-f;k+=1){let g=s.slice(k,k+f),C=new Set(g),L=new Set([...v,...C]).size,z=[...v].filter(ie=>C.has(ie)).length;if((L===0?0:z/L)<.35)continue;let j=.35*sb(o,g)+.35*ub(o,g)+.2*db(o,g)+.1*cb(o,g)+mb({candidateNormalized:s,label:n,matchEnd:k+f,matchStart:k,queryNormalized:o});j>d&&(d=Math.min(1,j),c=k,u=k+f)}return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:u,matchStart:c,score:d}}function mb(t){if(t.matchStart<0||t.matchEnd<0||t.queryNormalized.length<12||t.label==="start_anchor"&&t.matchStart!==0||t.label==="end_anchor"&&t.matchEnd!==t.candidateNormalized.length)return 0;let e=t.queryNormalized.length/Math.max(1,t.candidateNormalized.length);return .08*(.5+.5*Math.min(1,e))}var hb=i(()=>{"use strict";ri();cu();uu()});function fb(t){if(t==null)return[void 0,"anchor is required"];if(typeof t=="string"){let o=t.trim();if(o==="")return[void 0,"anchor string is empty"];if(o.includes("...")){let s=o.split("...").map(d=>d.trim()).filter(d=>d!=="");if(s.length>=2){let d=s[0],c=s[s.length-1];return d===void 0||c===void 0?[void 0,"anchor string is empty"]:[{head:d,mode:"head_tail",tail:c},void 0]}}return[{mode:"full",text:o},void 0]}if(typeof t!="object")return[void 0,`expected string or object, got ${typeof t}`];let e=t;if((e.mode==="head_tail"||e.head!==void 0?"head_tail":"full")==="full"){let o=typeof e.text=="string"?e.text.trim():"";return o===""?[void 0,"full anchor requires non-empty 'text'"]:[{mode:"full",text:o},void 0]}let r=typeof e.head=="string"?e.head.trim():"",a=typeof e.tail=="string"?e.tail.trim():"";return r!==""&&a===""?[{mode:"full",text:r},void 0]:r===""&&a!==""?[{mode:"full",text:a},void 0]:r===""||a===""?[void 0,"head_tail anchor requires non-empty 'head' and 'tail'"]:[{head:r,mode:"head_tail",tail:a},void 0]}function yb(t,e){if(t===void 0)return;if(t.mode==="head_tail"){let r=e==="end_anchor"?mu(t.tail??"","end_anchor"):mu(t.head??"","start_anchor");return r===""?void 0:{mode:"full",text:r}}return{mode:"full",text:mu(t.text??"",e)}}function pu(t){return t.mode==="head_tail"?Ee(t.head??"").length+Ee(t.tail??"").length:Ee(t.text??"").length}function mu(t,e){let n=Va(t);return n.length<=1?t.trim():e==="end_anchor"?n[n.length-1]??t.trim():n[0]??t.trim()}var gb=i(()=>{"use strict";ri()});var On,kb=i(()=>{"use strict";hb();gb();cu();uu();On=class{resolve(e,n,r){let a=e.start_anchor??e.start,o=e.end_anchor??e.end,[s,d]=this.parseAnchor(a,"start_anchor");if(d!==void 0)return[void 0,d];let c;if(o!==void 0){let[g,C]=this.parseAnchor(o,"end_anchor");if(C!==void 0)return[void 0,C];c=g}let[u,m,b]=this.resolveAnchor({anchor:s,candidateSentenceIds:n,candidateTexts:r,label:"start_anchor"});if(b!==void 0)return[void 0,b];if(u===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(c===void 0)return[{confidence:u.score,sentenceIds:[u.sentenceId],strategy:m},void 0];let[v,f,k]=this.resolveAnchor({anchor:c,candidateSentenceIds:n,candidateTexts:r,label:"end_anchor",minIndex:u.index});return k!==void 0?[void 0,k]:v===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:v.index<u.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${u.occurrenceId} -> ${v.occurrenceId}).`}]:[{confidence:Math.min(u.score,v.score),sentenceIds:n.slice(u.index,v.index+1),strategy:`${m}+${f}`},void 0]}resolveWithOverrides(e){let n=e.evidence.start_anchor??e.evidence.start,r=e.evidence.end_anchor??e.evidence.end,[a,o]=this.parseAnchor(n,"start_anchor");if(o!==void 0)return[void 0,o];let s=e.overrides.start_anchor,[d,c,u]=s===void 0?this.resolveAnchor({anchor:a,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"start_anchor"}):[s,"choice_final",void 0];if(u!==void 0)return[void 0,u];if(d===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(r===void 0)return[{confidence:d.score,sentenceIds:[d.sentenceId],strategy:c},void 0];let[m,b]=this.parseAnchor(r,"end_anchor");if(b!==void 0)return[void 0,b];let v=e.overrides.end_anchor,[f,k,g]=v===void 0?this.resolveAnchor({anchor:m,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"end_anchor",minIndex:d.index}):[v,"choice_final",void 0];return g!==void 0?[void 0,g]:f===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:f.index<d.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${d.occurrenceId} -> ${f.occurrenceId}).`}]:[{confidence:Math.min(d.score,f.score),sentenceIds:e.candidateSentenceIds.slice(d.index,f.index+1),strategy:`${c}+${k}`},void 0]}parseAnchor(e,n){let[r,a]=fb(e);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:n,message:`Invalid evidence.${n}: ${a}`}]:[yb(r,n),void 0]}resolveAnchor(e){if(e.anchor===void 0)return[void 0,"invalid",{candidates:[],code:"invalid",fieldName:e.label,message:`${e.label} is missing`}];let n=this.rankAnchor(e.anchor,e.candidateSentenceIds,e.candidateTexts,e.label),r=e.minIndex;if(r!==void 0&&(n=n.filter(m=>m.index>=r)),n.length===0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let a=n.filter(m=>m.exactRaw);if(a.length===1)return[a[0],"exact_raw",void 0];if(a.length>1)return[void 0,"ambiguous_exact_raw",this.#t(e.label,"ambiguous_exact_raw",a)];let o=n.filter(m=>m.exactSubstring);if(o.length===1&&pu(e.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&pu(e.anchor)>=8){let m=this.#e(o);return m!==void 0?[m,"exact_substring_scored",void 0]:[void 0,"ambiguous_exact_substring",this.#t(e.label,"ambiguous_exact_substring",o)]}let s=n.filter(m=>m.exactNormalized);if(s.length===1)return[s[0],"exact_normalized",void 0];if(s.length>1){let m=this.#e(s);return m!==void 0?[m,"exact_normalized_scored",void 0]:[void 0,"ambiguous_exact_normalized",this.#t(e.label,"ambiguous_exact_normalized",s)]}let d=n[0];if(d===void 0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let c=n[1]?.score??0,u=d.score-c;return d.score<.55?[void 0,"low_confidence",{candidates:n.slice(0,3),code:"low_confidence",fieldName:e.label,message:`${e.label} could not be matched confidently. Best candidate score=${d.score.toFixed(3)}.`}]:n.length===1?[d,"auto_top1_single_candidate",void 0]:d.score>=.97?[d,"auto_top1_very_high",void 0]:d.score>=.9&&u>=.07?[d,"auto_top1",void 0]:[void 0,"ambiguous_ranked",this.#t(e.label,"ambiguous_ranked",n)]}rankAnchor(e,n,r,a){let o=[];for(let[s,d]of n.entries()){let c=r[s]??"",u=s>0?r[s-1]??"":"",m=s<r.length-1?r[s+1]??"":"",b=pb(e,c,a);o.push({exactNormalized:b.exactNormalized,exactRaw:b.exactRaw,exactSubstring:b.exactSubstring,index:s,nextText:m,occurrenceId:`S${s+1}`,prevText:u,score:b.score,sentenceId:d,text:c})}return o.sort((s,d)=>s.score!==d.score?d.score-s.score:s.exactRaw!==d.exactRaw?s.exactRaw?-1:1:s.exactSubstring!==d.exactSubstring?s.exactSubstring?-1:1:s.exactNormalized!==d.exactNormalized?s.exactNormalized?-1:1:s.index-d.index),o}#e(e){if(e.length===0)return;if(e.length===1)return e[0];let n=e[0];if(n===void 0)return;let r=e[1]?.score??0;if(n.score>=.9&&n.score-r>=.07)return n}#t(e,n,r){let a=r.slice(0,3),o=a.map(s=>lb(s)).join(`
|
|
777
859
|
`);return{candidates:a,code:n,fieldName:e,message:`${e} is ambiguous. Top candidates:
|
|
778
860
|
${o}
|
|
779
|
-
Please provide a more specific anchor or surrounding context.`}}}});var
|
|
780
|
-
`)});var du=i(()=>{"use strict"});var pb=i(()=>{"use strict";du();ti()});var Xa=i(()=>{"use strict";lb();mb();du();pb();ti()});var fb=i(()=>{"use strict"});import{z as D}from"zod";var yb,PC,AC,LC,cte,ute,gb=i(()=>{"use strict";le();Xa();fb();yb=D.object({head:D.string().optional(),mode:D.enum(["full","head_tail"]).optional(),tail:D.string().optional(),text:D.string().optional()}).strict(),PC=D.object({quote:D.string().optional(),sentence_id:D.string().optional()}).strict(),AC=D.union([D.object({end_anchor:D.union([D.string(),yb]).optional(),quote:D.string().optional(),sentence_id:D.string().optional(),start_anchor:D.union([D.string(),yb]).optional()}).strict(),D.array(PC)]),LC=D.object({confidence:D.number().min(0).max(1).optional(),evidence:AC,predicate:D.string().min(1).max(64),sourceMentionId:D.string().min(1),targetMentionId:D.string().min(1)}).strict(),cte=D.object({relations:D.array(LC)}).strict(),ute=new Ln});var bb=i(()=>{"use strict"});var Sb=i(()=>{"use strict"});var wb=i(()=>{"use strict";gb();bb();Sb()});var kb=i(()=>{"use strict";wb();Ka();Zc()});var ni,On=i(()=>{"use strict";ni=Object.freeze({guaranteedResponseIntent:"guaranteed-response-intent",knowledgeGraph:"knowledge-graph",readingGraphEvidenceChoice:"reading-graph-evidence-choice",readingGraphExtraction:"reading-graph-extraction",readingSummaryCompress:"reading-summary-compress",readingSummaryReview:"reading-summary-review",readingSummaryReviewGuide:"reading-summary-review-guide"})});var Fte,uu=i(()=>{"use strict";le();$t();$g();Kg();kb();Zr();On();Fte=["Recall only source mentions that should become stable searchable knowledge graph objects.","Prefer named entities: historical persons, places, organizations, dynasties, political entities, named works, named events, battles, titles, and explicitly named domain concepts.","Recall a non-named common concept only when it is a central recurring topic of the chapter and would be useful as an entity search result across multiple evidence passages.","Do not recall a surface merely because it is useful for summarizing the story or explaining a detail.","Do not recall pure numbers, standalone dates without a named event role, units of measurement, dimensions, ordinal labels, chapter numbers, punctuation fragments, common function words, generic verbs, generic adjectives, generic roles, generic objects, or incidental attributes.","Measurements, quantities, dimensions, tactical details, and descriptive attributes should remain evidence text, not entity mentions.","When uncertain, skip the mention rather than creating a noisy knowledge graph object."].join(" ")});var xb=i(()=>{"use strict"});var Ib=i(()=>{"use strict"});var Eb=i(()=>{"use strict";xb();Ib()});var zt=i(()=>{"use strict"});var ri=i(()=>{"use strict";le()});var Rb=i(()=>{"use strict";zt();ri()});var Cb=i(()=>{"use strict";ri()});var Tb=i(()=>{"use strict"});import{z as I}from"zod";var _b,DC,Pb,MC,FC,GC,jC,UC,qC,Va=i(()=>{"use strict";zt();_b=I.object({from:I.union([I.number().int(),I.string()]),strength:I.string().optional(),to:I.union([I.number().int(),I.string()])}),DC=I.object({quote:I.string().optional(),sentence_id:I.string().optional()}).passthrough(),Pb=I.union([I.record(I.string(),I.unknown()),I.array(DC)]),MC=I.object({content:I.string(),evidence:Pb.nullish(),label:I.string(),retention:I.enum(["verbatim","detailed","focused","relevant"]),temp_id:I.string()}).passthrough(),FC=I.object({chunks:I.array(MC),fragment_summary:I.string(),links:I.array(_b)}),GC=I.object({content:I.string(),evidence:Pb.nullish(),importance:I.enum(["critical","important","helpful"]),label:I.string(),temp_id:I.string()}).passthrough(),jC=I.object({chunk_id:I.number().int(),importance:I.enum(["critical","important","helpful"])}),UC=I.object({chunks:I.array(GC),importance_annotations:I.array(jC),links:I.array(_b)}),qC=I.object({choice:I.string()})});var Ab=i(()=>{"use strict";le();Xa();Tb();ri();Va()});var Lb=i(()=>{"use strict";le();zt();Rb();ri();Cb();Ab();Va()});var Ob=i(()=>{"use strict";Lb();Va()});var mu=i(()=>{"use strict"});import{detect as Gne,validateISO2 as jne}from"tinyld";var Nb=i(()=>{"use strict"});var Wb=i(()=>{"use strict"});import{z as ii}from"zod";var $C,are,Db=i(()=>{"use strict";le();Xa();Ob();mu();mu();Nb();Wb();$C=ii.object({content:ii.string(),id:ii.number(),label:ii.string()}),are=ii.array($C)});var Mb=i(()=>{"use strict";Db()});var Fb=i(()=>{"use strict";Eb();Mb()});var Gb=i(()=>{"use strict";Fb()});var jb=i(()=>{"use strict"});var Ub=i(()=>{"use strict"});var pu=i(()=>{"use strict";jb();le();On();Ub()});var qb=i(()=>{"use strict"});var Bb=i(()=>{"use strict"});var Hb=i(()=>{"use strict";qb();Bb()});var ai=i(()=>{"use strict"});var Bre,Hre,Nn=i(()=>{"use strict";zt();Bre={critical:9,helpful:1,important:3},Hre={detailed:9,focused:3,relevant:1,verbatim:27}});var Wn=i(()=>{"use strict"});var oi=i(()=>{"use strict"});var hu=i(()=>{"use strict";Wn()});var fu=i(()=>{"use strict";Nn();Wn();ai();oi();hu()});var yu=i(()=>{"use strict";ai();fu();oi()});var Jb=i(()=>{"use strict";Nn();Wn();oi()});var Kb=i(()=>{"use strict";Nn();Wn();ai();oi();hu()});var zb=i(()=>{"use strict";yu();Wn();ai();Jb();fu();Kb()});var Qb=i(()=>{"use strict";zb();yu()});var Xb=i(()=>{"use strict";Nn()});var Vb=i(()=>{"use strict";Qb();Xb()});var Yb=i(()=>{"use strict";Hb();Vb();Nn()});var gu=i(()=>{"use strict";$t();On();Gb();pu();Yb()});var Zb=i(()=>{"use strict"});var Za=i(()=>{"use strict"});var eS=i(()=>{"use strict";Za()});var eo=i(()=>{"use strict"});var bae,nS=i(()=>{"use strict";Za();eo();bae=Object.freeze({critical:9,major:3,minor:1})});import{detect as kae,validateISO2 as xae}from"tinyld";var rS=i(()=>{"use strict";eo()});var iS=i(()=>{"use strict"});var aS=i(()=>{"use strict";zt()});var bu=i(()=>{"use strict";aS()});var oS=i(()=>{"use strict"});import{z as Dn}from"zod";var tT,nT,jae,sS=i(()=>{"use strict";le();Za();bu();eo();tT=["critical","major","minor"],nT=Dn.object({problem:Dn.string(),severity:Dn.enum(tT),suggestion:Dn.string().default("")}),jae=Dn.object({issues:Dn.array(nT)})});var dS=i(()=>{"use strict";Zb();eS();nS();rS();iS();bu();oS();sS()});var Su=i(()=>{"use strict";$t();On();zt();pu();dS()});var cS=i(()=>{"use strict";Hc();$t();Jc();uu();gu();Su()});import{z as G}from"zod";var Mn,rT,iT,aT,oT,Aoe,uS=i(()=>{"use strict";Mn=G.number().finite().nonnegative(),rT=G.enum(["committing","enrichment","grounding","indexing","matching","narrowing","relation-discovery","reading-extraction","screening","summary-compression"]),iT=G.enum(["candidate","char","item","page","qid","record","sentence","window"]),aT=G.object({cacheReadTokens:Mn.optional(),inputTokens:Mn.optional(),outputTokens:Mn.optional()}),oT=G.object({done:Mn,force:G.boolean().optional(),phase:rT,phaseDetail:G.string().optional(),total:Mn,unit:iT}),Aoe=G.discriminatedUnion("event",[G.object({characters:Mn,event:G.literal("output-characters")}),G.object({event:G.literal("token-usage"),usage:aT}),G.object({event:G.literal("progress"),progress:oT}),G.object({event:G.literal("artifact"),record:G.unknown()}),G.object({event:G.literal("complete"),revision:G.number().int().nonnegative()}),G.object({event:G.literal("error"),message:G.string()})])});var lS=i(()=>{"use strict"});var mS=i(()=>{"use strict"});var si=i(()=>{"use strict";vg();Rg();cS();Jc();Hc();$t();uu();gu();Su();On();uS();lS();mS();Bc()});var pS=i(()=>{"use strict";si();fn()});import{z as T}from"zod";var sT,dT,tse,nse,rse,hS=i(()=>{"use strict";y();sT="wikg-index-output/v1",dT=T.enum(["fts","embedding-source","embedding-summary"]),tse=T.object({artifactKind:dT,chapterId:T.number().int().nonnegative(),embedding:T.object({dimensions:T.number().int().nonnegative(),identity:T.string().optional(),model:T.string()}).optional(),inputRevision:T.number().int().nonnegative(),protocol:T.literal(sT),type:T.literal("manifest")}),nse=T.object({metadata:T.record(T.string(),T.unknown()).optional(),objectId:T.string().min(1),objectKind:T.string().min(1),rowId:T.string().min(1),sentenceIndex:T.number().int().nonnegative().optional(),text:T.string(),tokens:T.array(T.string()),type:T.literal("lexical-row")}),rse=T.object({endSentenceIndex:T.number().int().nonnegative(),segmentIndex:T.number().int().nonnegative(),startSentenceIndex:T.number().int().nonnegative(),text:T.string(),vector:T.array(T.number()),wordsCount:T.number().int().nonnegative(),type:T.literal("segment")})});var Qt=i(()=>{"use strict";pS();hS()});var fS=i(()=>{"use strict";Me();yt()});var yS=i(()=>{"use strict";P();Fa()});var bS=i(()=>{"use strict";y();P();Y();Pn();An();Qt();fS();yS()});var to=i(()=>{"use strict"});var SS=i(()=>{"use strict";to()});var wS=i(()=>{"use strict"});var kS=i(()=>{"use strict";to()});var xS=i(()=>{"use strict";to()});var IS=i(()=>{"use strict";SS();wS();kS();xS()});import{z as h}from"zod";var ES,wT,kT,xT,IT,ET,vT,RT,CT,TT,_T,vS=i(()=>{"use strict";Re();ES=h.tuple([h.number(),h.number()]),wT=h.object({text:h.string(),wordsCount:h.number()}),kT=h.object({serialId:h.number(),fragmentId:h.number(),summary:h.string(),sentences:h.array(wT)}),xT=h.object({documentOrder:h.number().optional(),id:h.number(),knowledgeGraphReady:h.boolean(),knowledgeGraphParameterHash:h.string().optional(),revision:h.number().optional(),topologyParameterHash:h.string().optional(),topologyReady:h.boolean()}).transform(t=>({documentOrder:t.documentOrder??t.id,id:t.id,knowledgeGraphReady:t.knowledgeGraphReady,...t.knowledgeGraphParameterHash===void 0?{}:{knowledgeGraphParameterHash:t.knowledgeGraphParameterHash},revision:t.revision??0,topologyReady:t.topologyReady,...t.topologyParameterHash===void 0?{}:{topologyParameterHash:t.topologyParameterHash}})),IT=h.object({id:h.number(),generation:h.number(),sentenceId:ES,label:h.string(),content:h.string(),sentenceIds:h.array(ES),retention:h.enum(he).optional(),importance:h.enum(ve).optional(),wordsCount:h.number(),weight:h.number()}),ET=h.object({fromId:h.number(),toId:h.number(),strength:h.string().optional(),weight:h.number()}),vT=h.object({id:h.number(),serialId:h.number(),groupId:h.number(),localSnakeId:h.number(),size:h.number(),firstLabel:h.string(),lastLabel:h.string(),wordsCount:h.number(),weight:h.number()}),RT=h.object({snakeId:h.number(),chunkId:h.number(),position:h.number()}),CT=h.object({fromSnakeId:h.number(),toSnakeId:h.number(),weight:h.number()}),TT=h.object({serialId:h.number(),groupId:h.number(),startSentenceIndex:h.number(),endSentenceIndex:h.number()}),_T=h.object({chunks:h.array(IT),fragmentGroups:h.array(TT),fragments:h.array(kT),readingEdges:h.array(ET),serial:xT,snakeChunks:h.array(RT),snakeEdges:h.array(CT),snakes:h.array(vT)})});var RS=i(()=>{"use strict";y();vS()});var CS=i(()=>{"use strict";nn();Oc();Z()});var TS=i(()=>{"use strict";y();P();Y();IS();RS();$a();CS();An();Qt()});var _S=i(()=>{"use strict"});var no=i(()=>{"use strict";TS();$a();_S()});var PS=i(()=>{"use strict";Y();no()});var AS=i(()=>{"use strict"});var LS=i(()=>{"use strict";bS();PS();AS()});var OS=i(()=>{"use strict";si()});var WS=i(()=>{"use strict";si();P();Y();Qt();no()});var DS=i(()=>{"use strict";si();ft();nn()});var MS=i(()=>{"use strict";LS();no();OS();WS();DS()});import{z as $}from"zod";var gce,AT,bce,Iu=i(()=>{"use strict";y();gce=$.object({id:$.string().min(1),chapterId:$.number().int(),sentenceIndex:$.number().int().nonnegative().optional(),rangeStart:$.number().int().nonnegative(),rangeEnd:$.number().int().nonnegative(),surface:$.string().min(1),qid:$.string().regex(/^Q[1-9][0-9]*$/),confidence:$.number().min(0).max(1).optional(),note:$.string().optional()}),AT=$.tuple([$.number().int().nonnegative(),$.number().int().nonnegative()]).readonly(),bce=$.object({id:$.string().min(1),sourceMentionId:$.string().min(1),targetMentionId:$.string().min(1),predicate:$.string().min(1),evidenceSentenceIds:$.array(AT).min(1),confidence:$.number().min(0).max(1).optional(),note:$.string().optional()})});var Eu=i(()=>{"use strict";y();Me();An();Iu()});var GS=i(()=>{"use strict";An();Qt();Iu()});var ro=i(()=>{"use strict"});var jS=i(()=>{"use strict";ft();ro()});var vu=i(()=>{"use strict"});var US=i(()=>{"use strict";ft()});var Ru=i(()=>{"use strict"});var Cu=i(()=>{"use strict";ft();ro();US();Ru()});var BS=i(()=>{"use strict";Cu()});var HS=i(()=>{"use strict";Me()});var $S=i(()=>{"use strict";Tc();En();Ma()});import{z as M}from"zod";var JS,WT,DT,MT,due,cue,KS=i(()=>{"use strict";Ne();En();$S();JS=M.object({head:M.string().optional(),mode:M.enum(["full","head_tail"]).optional(),tail:M.string().optional(),text:M.string().optional()}).strict(),WT=M.object({quote:M.string().optional(),sentence_id:M.string().optional()}).strict(),DT=M.union([M.object({end_anchor:M.union([M.string(),JS]).optional(),quote:M.string().optional(),sentence_id:M.string().optional(),start_anchor:M.union([M.string(),JS]).optional()}).strict(),M.array(WT)]),MT=M.object({confidence:M.number().min(0).max(1).optional(),evidence:DT,predicate:M.string().min(1).max(64),sourceMentionId:M.string().min(1),targetMentionId:M.string().min(1)}).strict(),due=M.object({relations:M.array(MT)}).strict(),cue=new Bt});var zS=i(()=>{"use strict"});var QS=i(()=>{"use strict";KS();zS()});var XS=i(()=>{"use strict";QS();ro();Ru()});var Tu=i(()=>{"use strict";Y();vu()});var ZS=i(()=>{"use strict";ft();yt();Eu();jS();vu();BS();HS();XS();Tu()});var ew=i(()=>{"use strict"});var tw=i(()=>{"use strict";Eu();GS();ZS();Cu();Tu();ew()});var nw=i(()=>{"use strict";tw()});var di=i(()=>{"use strict";Y()});var _u=i(()=>{"use strict";yt()});var Pu=i(()=>{"use strict";Me();yt();Pn();di();_u()});var aw=i(()=>{"use strict";yt();di();Pu()});var Au=i(()=>{"use strict";ye();Z()});var sw=i(()=>{"use strict";ye();ar();at();Au();Z()});var dw=i(()=>{"use strict";Pn();ye();di();sw();Au();Z()});import{z as Xt}from"zod";var cw,Hle,uw=i(()=>{"use strict";cw=Xt.object({children:Xt.lazy(()=>Xt.array(cw)),uri:Xt.string().min(1),title:Xt.string().nullable().optional()}).strict(),Hle=Xt.object({chapters:Xt.array(cw)}).strict()});var lw=i(()=>{"use strict";Y()});var mw=i(()=>{"use strict";aw();di();Pu();dw();_u();uw();lw()});var pw=i(()=>{"use strict";hr()});var Ve=i(()=>{"use strict";xg();ct();rc();MS();nw();ct();qc();mw();pw();ka()});function Fw(t){if(t?.platform===void 0){al();return}Yt(t.platform)}function Gw(t){if(t.host?.storage!==void 0&&t.stateDir!==void 0)throw new TypeError("Wiki Graph SDK host.storage and stateDir cannot be used together.")}async function mo(t,e){return Gw(t),Fw(t.host),t.host?.storage!==void 0?await en(t.host.storage,e):await yi(t.stateDir,e)}var po=i(()=>{"use strict";go();ce()});async function Qw(t="global"){let e=await Gu(),n=Ze(),r=Date.now(),a=!1;try{await e.transaction(async()=>{await tP(e),await e.run(`
|
|
861
|
+
Please provide a more specific anchor or surrounding context.`}}}});var xb=i(()=>{"use strict"});var Eb=i(()=>{"use strict";kb();xb()});var hu,Ib=i(()=>{"use strict";hu=["Evidence selection:",'- Return evidence as [{"sentence_id":"S1","quote":"exact short source quote"}].',"- evidence.quote is a locator for the source sentence, not a proof excerpt.","- Choose the shortest exact quote that still uniquely identifies the intended sentence.","- If the quote is too short, it may match multiple sentences; if it is too long, it may include unnecessary text or cross sentence boundaries.","- Do not use a whole sentence by default.","- evidence is an array. Use multiple items when the claim needs multiple source sentences.","- A source sentence means exactly one displayed source line labeled S1, S2, S3, etc.","- Each evidence item must point to exactly one source sentence.","- Each evidence item must quote one continuous span from exactly one labeled source line, for example only from S2.","- Never merge text from two labeled source lines into one evidence quote.","- sentence_id must be one of the sentence IDs shown in the source context.","- quote must be copied from the untagged original source sentence.","- If the source context contains XML-like tags, do not copy the tags into quote; copy only the visible text."].join(`
|
|
862
|
+
`)});var fu=i(()=>{"use strict"});var vb=i(()=>{"use strict";fu();ri()});var Za=i(()=>{"use strict";Eb();Ib();fu();vb();ri()});var Cb=i(()=>{"use strict"});import{z as D}from"zod";var Tb,XC,VC,YC,nne,rne,_b=i(()=>{"use strict";le();Za();Cb();Tb=D.object({head:D.string().optional(),mode:D.enum(["full","head_tail"]).optional(),tail:D.string().optional(),text:D.string().optional()}).strict(),XC=D.object({quote:D.string().optional(),sentence_id:D.string().optional()}).strict(),VC=D.union([D.object({end_anchor:D.union([D.string(),Tb]).optional(),quote:D.string().optional(),sentence_id:D.string().optional(),start_anchor:D.union([D.string(),Tb]).optional()}).strict(),D.array(XC)]),YC=D.object({confidence:D.number().min(0).max(1).optional(),evidence:VC,predicate:D.string().min(1).max(64),sourceMentionId:D.string().min(1),targetMentionId:D.string().min(1)}).strict(),nne=D.object({relations:D.array(YC)}).strict(),rne=new On});var Pb=i(()=>{"use strict"});var Ab=i(()=>{"use strict"});var Lb=i(()=>{"use strict";_b();Pb();Ab()});var Ob=i(()=>{"use strict";Lb();Xa();ou()});var ii,Nn=i(()=>{"use strict";ii=Object.freeze({guaranteedResponseIntent:"guaranteed-response-intent",knowledgeGraph:"knowledge-graph",readingGraphEvidenceChoice:"reading-graph-evidence-choice",readingGraphExtraction:"reading-graph-extraction",readingSummaryCompress:"reading-summary-compress",readingSummaryReview:"reading-summary-review",readingSummaryReviewGuide:"reading-summary-review-guide"})});var Ane,gu=i(()=>{"use strict";le();Jt();rb();ab();Ob();ti();Nn();Ane=["Recall only source mentions that should become stable searchable knowledge graph objects.","Prefer named entities: historical persons, places, organizations, dynasties, political entities, named works, named events, battles, titles, and explicitly named domain concepts.","Recall a non-named common concept only when it is a central recurring topic of the chapter and would be useful as an entity search result across multiple evidence passages.","Do not recall a surface merely because it is useful for summarizing the story or explaining a detail.","Do not recall pure numbers, standalone dates without a named event role, units of measurement, dimensions, ordinal labels, chapter numbers, punctuation fragments, common function words, generic verbs, generic adjectives, generic roles, generic objects, or incidental attributes.","Measurements, quantities, dimensions, tactical details, and descriptive attributes should remain evidence text, not entity mentions.","When uncertain, skip the mention rather than creating a noisy knowledge graph object."].join(" ")});var Nb=i(()=>{"use strict"});var Wb=i(()=>{"use strict"});var Db=i(()=>{"use strict";Nb();Wb()});var Qt=i(()=>{"use strict"});var ai=i(()=>{"use strict";le()});var Fb=i(()=>{"use strict";Qt();ai()});var Gb=i(()=>{"use strict";ai()});var jb=i(()=>{"use strict"});import{z as E}from"zod";var Ub,nT,qb,rT,iT,aT,oT,sT,dT,eo=i(()=>{"use strict";Qt();Ub=E.object({from:E.union([E.number().int(),E.string()]),strength:E.string().optional(),to:E.union([E.number().int(),E.string()])}),nT=E.object({quote:E.string().optional(),sentence_id:E.string().optional()}).passthrough(),qb=E.union([E.record(E.string(),E.unknown()),E.array(nT)]),rT=E.object({content:E.string(),evidence:qb.nullish(),label:E.string(),retention:E.enum(["verbatim","detailed","focused","relevant"]),temp_id:E.string()}).passthrough(),iT=E.object({chunks:E.array(rT),fragment_summary:E.string(),links:E.array(Ub)}),aT=E.object({content:E.string(),evidence:qb.nullish(),importance:E.enum(["critical","important","helpful"]),label:E.string(),temp_id:E.string()}).passthrough(),oT=E.object({chunk_id:E.number().int(),importance:E.enum(["critical","important","helpful"])}),sT=E.object({chunks:E.array(aT),importance_annotations:E.array(oT),links:E.array(Ub)}),dT=E.object({choice:E.string()})});var Bb=i(()=>{"use strict";le();Za();jb();ai();eo()});var Hb=i(()=>{"use strict";le();Qt();Fb();ai();Gb();Bb();eo()});var $b=i(()=>{"use strict";Hb();eo()});var Su=i(()=>{"use strict"});import{detect as Lre,validateISO2 as Ore}from"tinyld";var Jb=i(()=>{"use strict"});var Kb=i(()=>{"use strict"});import{z as oi}from"zod";var lT,Yre,zb=i(()=>{"use strict";le();Za();$b();Su();Su();Jb();Kb();lT=oi.object({content:oi.string(),id:oi.number(),label:oi.string()}),Yre=oi.array(lT)});var Qb=i(()=>{"use strict";zb()});var Xb=i(()=>{"use strict";Db();Qb()});var Vb=i(()=>{"use strict";Xb()});var Yb=i(()=>{"use strict"});var Zb=i(()=>{"use strict"});var wu=i(()=>{"use strict";Yb();le();Nn();Zb()});var eS=i(()=>{"use strict"});var tS=i(()=>{"use strict"});var nS=i(()=>{"use strict";eS();tS()});var si=i(()=>{"use strict"});var Die,Mie,Wn=i(()=>{"use strict";Qt();Die={critical:9,helpful:1,important:3},Mie={detailed:9,focused:3,relevant:1,verbatim:27}});var Dn=i(()=>{"use strict"});var di=i(()=>{"use strict"});var ku=i(()=>{"use strict";Dn()});var xu=i(()=>{"use strict";Wn();Dn();si();di();ku()});var Eu=i(()=>{"use strict";si();xu();di()});var iS=i(()=>{"use strict";Wn();Dn();di()});var aS=i(()=>{"use strict";Wn();Dn();si();di();ku()});var oS=i(()=>{"use strict";Eu();Dn();si();iS();xu();aS()});var sS=i(()=>{"use strict";oS();Eu()});var dS=i(()=>{"use strict";Wn()});var cS=i(()=>{"use strict";sS();dS()});var uS=i(()=>{"use strict";nS();cS();Wn()});var Iu=i(()=>{"use strict";Jt();Nn();Vb();wu();uS()});var lS=i(()=>{"use strict"});var no=i(()=>{"use strict"});var mS=i(()=>{"use strict";no()});var ro=i(()=>{"use strict"});var loe,hS=i(()=>{"use strict";no();ro();loe=Object.freeze({critical:9,major:3,minor:1})});import{detect as hoe,validateISO2 as foe}from"tinyld";var fS=i(()=>{"use strict";ro()});var yS=i(()=>{"use strict"});var gS=i(()=>{"use strict";Qt()});var vu=i(()=>{"use strict";gS()});var bS=i(()=>{"use strict"});import{z as Mn}from"zod";var kT,xT,Ooe,SS=i(()=>{"use strict";le();no();vu();ro();kT=["critical","major","minor"],xT=Mn.object({problem:Mn.string(),severity:Mn.enum(kT),suggestion:Mn.string().default("")}),Ooe=Mn.object({issues:Mn.array(xT)})});var wS=i(()=>{"use strict";lS();mS();hS();fS();yS();vu();bS();SS()});var Ru=i(()=>{"use strict";Jt();Nn();Qt();wu();wS()});var kS=i(()=>{"use strict";Vc();Jt();Zc();gu();Iu();Ru()});import{z as G}from"zod";var Fn,ET,IT,vT,RT,Ise,xS=i(()=>{"use strict";Fn=G.number().finite().nonnegative(),ET=G.enum(["committing","enrichment","grounding","indexing","matching","narrowing","relation-discovery","reading-extraction","screening","summary-compression"]),IT=G.enum(["candidate","char","item","page","qid","record","sentence","window"]),vT=G.object({cacheReadTokens:Fn.optional(),inputTokens:Fn.optional(),outputTokens:Fn.optional()}),RT=G.object({done:Fn,force:G.boolean().optional(),phase:ET,phaseDetail:G.string().optional(),total:Fn,unit:IT}),Ise=G.discriminatedUnion("event",[G.object({characters:Fn,event:G.literal("output-characters")}),G.object({event:G.literal("token-usage"),usage:vT}),G.object({event:G.literal("progress"),progress:RT}),G.object({event:G.literal("artifact"),record:G.unknown()}),G.object({event:G.literal("complete"),revision:G.number().int().nonnegative()}),G.object({event:G.literal("error"),message:G.string()})])});var ES=i(()=>{"use strict"});var IS=i(()=>{"use strict"});var ci=i(()=>{"use strict";Mg();Fg();kS();Zc();Vc();Jt();gu();Iu();Ru();Nn();xS();ES();IS();Xc()});var vS=i(()=>{"use strict";ci();yn()});import{z as T}from"zod";var CT,TT,zse,Qse,Xse,RS=i(()=>{"use strict";y();CT="wikg-index-output/v1",TT=T.enum(["fts","embedding-source","embedding-summary"]),zse=T.object({artifactKind:TT,chapterId:T.number().int().nonnegative(),embedding:T.object({dimensions:T.number().int().nonnegative(),identity:T.string().optional(),model:T.string()}).optional(),inputRevision:T.number().int().nonnegative(),protocol:T.literal(CT),type:T.literal("manifest")}),Qse=T.object({metadata:T.record(T.string(),T.unknown()).optional(),objectId:T.string().min(1),objectKind:T.string().min(1),rowId:T.string().min(1),sentenceIndex:T.number().int().nonnegative().optional(),text:T.string(),tokens:T.array(T.string()),type:T.literal("lexical-row")}),Xse=T.object({endSentenceIndex:T.number().int().nonnegative(),segmentIndex:T.number().int().nonnegative(),startSentenceIndex:T.number().int().nonnegative(),text:T.string(),vector:T.array(T.number()),wordsCount:T.number().int().nonnegative(),type:T.literal("segment")})});var Xt=i(()=>{"use strict";vS();RS()});var CS=i(()=>{"use strict";Fe();gt()});var TS=i(()=>{"use strict";P();Ua()});var PS=i(()=>{"use strict";y();P();Y();An();Ln();Xt();CS();TS()});var io=i(()=>{"use strict"});var AS=i(()=>{"use strict";io()});var LS=i(()=>{"use strict"});var OS=i(()=>{"use strict";io()});var NS=i(()=>{"use strict";io()});var WS=i(()=>{"use strict";AS();LS();OS();NS()});import{z as h}from"zod";var DS,jT,UT,qT,BT,HT,$T,JT,KT,zT,QT,MS=i(()=>{"use strict";Ce();DS=h.tuple([h.number(),h.number()]),jT=h.object({text:h.string(),wordsCount:h.number()}),UT=h.object({serialId:h.number(),fragmentId:h.number(),summary:h.string(),sentences:h.array(jT)}),qT=h.object({documentOrder:h.number().optional(),id:h.number(),knowledgeGraphReady:h.boolean(),knowledgeGraphParameterHash:h.string().optional(),revision:h.number().optional(),topologyParameterHash:h.string().optional(),topologyReady:h.boolean()}).transform(t=>({documentOrder:t.documentOrder??t.id,id:t.id,knowledgeGraphReady:t.knowledgeGraphReady,...t.knowledgeGraphParameterHash===void 0?{}:{knowledgeGraphParameterHash:t.knowledgeGraphParameterHash},revision:t.revision??0,topologyReady:t.topologyReady,...t.topologyParameterHash===void 0?{}:{topologyParameterHash:t.topologyParameterHash}})),BT=h.object({id:h.number(),generation:h.number(),sentenceId:DS,label:h.string(),content:h.string(),sentenceIds:h.array(DS),retention:h.enum(fe).optional(),importance:h.enum(Re).optional(),wordsCount:h.number(),weight:h.number()}),HT=h.object({fromId:h.number(),toId:h.number(),strength:h.string().optional(),weight:h.number()}),$T=h.object({id:h.number(),serialId:h.number(),groupId:h.number(),localSnakeId:h.number(),size:h.number(),firstLabel:h.string(),lastLabel:h.string(),wordsCount:h.number(),weight:h.number()}),JT=h.object({snakeId:h.number(),chunkId:h.number(),position:h.number()}),KT=h.object({fromSnakeId:h.number(),toSnakeId:h.number(),weight:h.number()}),zT=h.object({serialId:h.number(),groupId:h.number(),startSentenceIndex:h.number(),endSentenceIndex:h.number()}),QT=h.object({chunks:h.array(BT),fragmentGroups:h.array(zT),fragments:h.array(UT),readingEdges:h.array(HT),serial:qT,snakeChunks:h.array(JT),snakeEdges:h.array(KT),snakes:h.array($T)})});var FS=i(()=>{"use strict";y();MS()});var GS=i(()=>{"use strict";rn();jc();Z()});var jS=i(()=>{"use strict";y();P();Y();WS();FS();za();GS();Ln();Xt()});var US=i(()=>{"use strict"});var ao=i(()=>{"use strict";jS();za();US()});var qS=i(()=>{"use strict";Y();ao()});var BS=i(()=>{"use strict"});var HS=i(()=>{"use strict";PS();qS();BS()});var $S=i(()=>{"use strict";ci()});var KS=i(()=>{"use strict";ci();P();Y();Xt();ao()});var zS=i(()=>{"use strict";ci();yt();rn()});var QS=i(()=>{"use strict";HS();ao();$S();KS();zS()});import{z as $}from"zod";var uue,VT,lue,Pu=i(()=>{"use strict";y();uue=$.object({id:$.string().min(1),chapterId:$.number().int(),sentenceIndex:$.number().int().nonnegative().optional(),rangeStart:$.number().int().nonnegative(),rangeEnd:$.number().int().nonnegative(),surface:$.string().min(1),qid:$.string().regex(/^Q[1-9][0-9]*$/),confidence:$.number().min(0).max(1).optional(),note:$.string().optional()}),VT=$.tuple([$.number().int().nonnegative(),$.number().int().nonnegative()]).readonly(),lue=$.object({id:$.string().min(1),sourceMentionId:$.string().min(1),targetMentionId:$.string().min(1),predicate:$.string().min(1),evidenceSentenceIds:$.array(VT).min(1),confidence:$.number().min(0).max(1).optional(),note:$.string().optional()})});var Au=i(()=>{"use strict";y();Fe();Ln();Pu()});var VS=i(()=>{"use strict";Ln();Xt();Pu()});var oo=i(()=>{"use strict"});var YS=i(()=>{"use strict";yt();oo()});var Lu=i(()=>{"use strict"});var ZS=i(()=>{"use strict";yt()});var Ou=i(()=>{"use strict"});var Nu=i(()=>{"use strict";yt();oo();ZS();Ou()});var tw=i(()=>{"use strict";Nu()});var nw=i(()=>{"use strict";Fe()});var rw=i(()=>{"use strict";Wc();vn();ja()});import{z as M}from"zod";var iw,t_,n_,r_,tle,nle,aw=i(()=>{"use strict";We();vn();rw();iw=M.object({head:M.string().optional(),mode:M.enum(["full","head_tail"]).optional(),tail:M.string().optional(),text:M.string().optional()}).strict(),t_=M.object({quote:M.string().optional(),sentence_id:M.string().optional()}).strict(),n_=M.union([M.object({end_anchor:M.union([M.string(),iw]).optional(),quote:M.string().optional(),sentence_id:M.string().optional(),start_anchor:M.union([M.string(),iw]).optional()}).strict(),M.array(t_)]),r_=M.object({confidence:M.number().min(0).max(1).optional(),evidence:n_,predicate:M.string().min(1).max(64),sourceMentionId:M.string().min(1),targetMentionId:M.string().min(1)}).strict(),tle=M.object({relations:M.array(r_)}).strict(),nle=new Ht});var ow=i(()=>{"use strict"});var sw=i(()=>{"use strict";aw();ow()});var dw=i(()=>{"use strict";sw();oo();Ou()});var Wu=i(()=>{"use strict";Y();Lu()});var lw=i(()=>{"use strict";yt();gt();Au();YS();Lu();tw();nw();dw();Wu()});var mw=i(()=>{"use strict"});var pw=i(()=>{"use strict";Au();VS();lw();Nu();Wu();mw()});var hw=i(()=>{"use strict";pw()});var ui=i(()=>{"use strict";Y()});var Du=i(()=>{"use strict";gt()});var Mu=i(()=>{"use strict";Fe();gt();An();ui();Du()});var gw=i(()=>{"use strict";gt();ui();Mu()});var Fu=i(()=>{"use strict";ge();Z()});var Sw=i(()=>{"use strict";ge();or();ot();Fu();Z()});var ww=i(()=>{"use strict";An();ge();ui();Sw();Fu();Z()});import{z as Vt}from"zod";var kw,Mme,xw=i(()=>{"use strict";kw=Vt.object({children:Vt.lazy(()=>Vt.array(kw)),uri:Vt.string().min(1),title:Vt.string().nullable().optional()}).strict(),Mme=Vt.object({chapters:Vt.array(kw)}).strict()});var Ew=i(()=>{"use strict";Y()});var Iw=i(()=>{"use strict";gw();ui();Mu();ww();Du();xw();Ew()});var vw=i(()=>{"use strict";yr()});var Ye=i(()=>{"use strict";Ng();ut();uc();QS();hw();ut();Qc();Iw();vw();Ia()});import{AsyncLocalStorage as X_}from"async_hooks";function V_(){let t=globalThis,e=t[Bw];if(e!==void 0)return e;let n=new X_;return Object.defineProperty(t,Bw,{configurable:!1,enumerable:!1,value:n,writable:!1}),n}async function li(t,e){return await Hw.run(t,e)}function mo(){return Hw.getStore()??{cwd:process.cwd(),env:process.env,envPolicy:"production",providers:{}}}var Bw,Hw,me=i(()=>{"use strict";Bw=Symbol.for("wiki-graph-sdk.runtime-context.v1"),Hw=V_()});function Vw(t){if(t?.platform===void 0){ll();return}Zt(t.platform)}function Yw(t){if(t.host?.storage!==void 0&&t.host.stateDir===void 0)throw new TypeError("Wiki Graph SDK host.storage requires host.stateDir so SDK configuration cannot fall back to the default user state directory.");if(t.stateDir!==void 0&&(t.host?.stateDir!==void 0||t.host?.storage!==void 0))throw new TypeError("Wiki Graph SDK host state/storage and top-level stateDir cannot be used together. Put the state directory in host.stateDir when providing host.storage.")}async function yo(t,e){let n=mo(),r={...t.host===void 0?n.host===void 0?{}:{host:n.host}:{host:t.host},...t.stateDir===void 0?n.stateDir===void 0?{}:{stateDir:n.stateDir}:{stateDir:t.stateDir}};Yw(r),Vw(r.host);let a=async()=>await li({...n,...r.host===void 0?{}:{host:r.host},...r.stateDir===void 0?{}:{stateDir:r.stateDir}},e);return r.host?.storage!==void 0?await tn(r.host.storage,a):await Si(r.host?.stateDir??r.stateDir,a)}var go=i(()=>{"use strict";ko();ce();me()});async function dk(t="global"){let e=await $u(),n=et(),r=Date.now(),a=!1;try{await e.transaction(async()=>{await vP(e),await e.run(`
|
|
781
863
|
INSERT OR IGNORE INTO gc_locks (
|
|
782
864
|
scope, owner_id, owner_pid, heartbeat_at, created_at
|
|
783
865
|
) VALUES (?, ?, ?, ?, ?)
|
|
784
|
-
`,[t,n,0,r,r]),a=await e.queryOne("SELECT owner_id FROM gc_locks WHERE scope = ?",[t],s=>
|
|
866
|
+
`,[t,n,0,r,r]),a=await e.queryOne("SELECT owner_id FROM gc_locks WHERE scope = ?",[t],s=>I(s,"owner_id"))===n})}finally{await e.close()}if(!a)return;let o=setInterval(()=>{IP(t,n).catch(()=>{})},EP);return async()=>{clearInterval(o);let s=await $u();try{await s.run("DELETE FROM gc_locks WHERE scope = ? AND owner_id = ?",[t,n])}finally{await s.close()}}}async function IP(t,e){let n=await $u();try{await n.run(`
|
|
785
867
|
UPDATE gc_locks
|
|
786
868
|
SET heartbeat_at = ?, owner_pid = ?
|
|
787
869
|
WHERE scope = ? AND owner_id = ?
|
|
788
|
-
`,[Date.now(),0,t,e])}finally{await n.close()}}async function
|
|
870
|
+
`,[Date.now(),0,t,e])}finally{await n.close()}}async function vP(t){let e=await t.queryAll("SELECT * FROM gc_locks",void 0,TP);for(let{lock:n,scope:r}of e.filter(({lock:a})=>RP(a)))await t.run(`
|
|
789
871
|
DELETE FROM gc_locks
|
|
790
872
|
WHERE scope = ?
|
|
791
873
|
AND owner_id = ?
|
|
792
874
|
AND heartbeat_at = ?
|
|
793
|
-
`,[r,n.ownerId,n.heartbeatAt])}function
|
|
875
|
+
`,[r,n.ownerId,n.heartbeatAt])}function RP(t){return!(Date.now()-t.heartbeatAt<xP)}async function $u(){return await K("tmp/gc.sqlite",kP)}function CP(t){return{createdAt:S(t,"created_at"),heartbeatAt:S(t,"heartbeat_at"),ownerId:I(t,"owner_id"),ownerPid:S(t,"owner_pid")}}function TP(t){return{lock:CP(t),scope:I(t,"scope")}}var kP,xP,EP,ck=i(()=>{"use strict";F();w();P();kP=`
|
|
794
876
|
CREATE TABLE IF NOT EXISTS gc_locks (
|
|
795
877
|
scope TEXT PRIMARY KEY,
|
|
796
878
|
owner_id TEXT NOT NULL,
|
|
@@ -798,8 +880,8 @@ CREATE TABLE IF NOT EXISTS gc_locks (
|
|
|
798
880
|
heartbeat_at INTEGER NOT NULL,
|
|
799
881
|
created_at INTEGER NOT NULL
|
|
800
882
|
);
|
|
801
|
-
`,
|
|
802
|
-
`)}var
|
|
803
|
-
`}function
|
|
883
|
+
`,xP=6e4,EP=2e4});async function uk(t){let e=await R().library.getDirectory("tmp"),n=0,r=0,a=0;if(e===void 0)return{freedBytes:a,removed:r,scanned:n};for(let o of await PP(e)){n+=1;let s=await Ze(o.value);if(!t.force&&(s===void 0||t.now-s<_P))continue;let d=await ht(o.value);t.dryRun||await o.parent.remove(o.value.name,{recursive:!0}),r+=1,a+=d}return{freedBytes:a,removed:r,scanned:n}}async function PP(t){let e=[];for(let n of await t.list())if(U(n))for(let r of await n.list())e.push({parent:n,value:r});return e}var _P,lk=i(()=>{"use strict";y();Xd();_P=3600*1e3});async function bo(t={}){let e=Date.now(),n=await dk();if(n===void 0)return{finishedAt:Date.now(),freedBytes:0,jobs:[],removed:0,scanned:0,skipped:!0,startedAt:e};try{if(t.opportunistic===!0&&!await NP(e))return{finishedAt:Date.now(),freedBytes:0,jobs:[],removed:0,scanned:0,skipped:!0,startedAt:e};let r={dryRun:t.dryRun===!0,force:t.force===!0,now:e},a=[];for(let s of AP)a.push(await OP(s,r));let o={finishedAt:Date.now(),freedBytes:Ju(a,"freedBytes"),jobs:a,removed:Ju(a,"removed"),scanned:Ju(a,"scanned"),skipped:!1,startedAt:e};return await WP(o.finishedAt).catch(()=>{}),o}finally{await n()}}async function OP(t,e){try{return{name:t.name,...await t.run(e)}}catch(n){return{error:nn(n),freedBytes:0,name:t.name,removed:0,scanned:0}}}function Ju(t,e){return t.reduce((n,r)=>{let a=r[e];return n+(typeof a=="number"?a:0)},0)}async function NP(t){let e=await J(R().library,"tmp/gc.last-run"),n=Number((e===void 0?"":await ae(e).catch(()=>"")).trim());return!Number.isFinite(n)||t-n>=LP}async function WP(t){let e=await H(R().library,"tmp/gc.last-run");await pe(e,`${t}
|
|
884
|
+
`)}var AP,LP,mk=i(()=>{"use strict";y();ut();Ye();Oe();Oa();Ec();he();ck();lk();AP=[{name:"wikg-coordinator",run:Ra},{name:"search-cache",run:qi},{name:"library-index",run:Uf},{name:"build-queue",run:_a},{name:"wikimedia-cache",run:kc},{name:"tmp",run:uk}],LP=600*1e3});var pk=i(()=>{"use strict";mk()});var hk=i(()=>{"use strict";pk()});var fk={};Sk(fk,{tryRunWikiGraphGc:()=>DP});async function DP(t={}){let{host:e,stateDir:n,...r}=t;return await yo({...e===void 0?{}:{host:e},...n===void 0?{}:{stateDir:n}},async()=>await bo(r))}var yk=i(()=>{"use strict";hk();go()});ce();import{AsyncLocalStorage as hP}from"async_hooks";import{randomUUID as zye}from"crypto";import{link as Xye,mkdtemp as Vye,rename as Yye,rm as Zye,stat as ege}from"fs/promises";import{tmpdir as nge}from"os";import{basename as ige,dirname as age,join as oge}from"path";import{Readable as dge}from"stream";Fe();y();wi();import{z as Hn}from"zod";var $k=1,pA=Hn.object({completedAt:Hn.string().optional(),startedAt:Hn.string(),status:Hn.enum(["running","succeeded"]),version:Hn.literal($k)});Wo();rn();tt();Z();Mo();jn();Oa();vn();Ec();yt();Lc();Ye();ge();Oe();P();ot();ut();P();or();Oi();_i();Xt();y();rt();Ke();mt();lt();qd();_i();Oa();yn();Xt();P();y();Oe();y();w();w();y();w();y();ws();y();he();Ye();Ye();Ye();Ye();Ye();gt();yt();P();Ln();y();import{createHash as sye}from"crypto";import{createReadStream as cye}from"fs";import{rm as lye}from"fs/promises";import{basename as pye}from"path";import{createAnthropic as mfe}from"@ai-sdk/anthropic";import{createGoogleGenerativeAI as hfe}from"@ai-sdk/google";import{createOpenAI as yfe}from"@ai-sdk/openai";import{createOpenAICompatible as bfe}from"@ai-sdk/openai-compatible";ce();import{z as re}from"zod";me();ce();import{mkdir as Cfe}from"fs/promises";import{join as _fe}from"path";import{homedir as Afe}from"os";me();var Y_=["anthropic","google","openai","openai-compatible"],$w=re.enum(Y_),Dfe=re.object({apiKey:re.string().min(1).optional(),baseURL:re.string().min(1).optional(),baseUrl:re.string().min(1).optional(),chatCompletionsUrl:re.string().min(1).optional(),llm:re.object({apiKey:re.string().min(1).optional(),baseURL:re.string().min(1).optional(),baseUrl:re.string().min(1).optional(),chatCompletionsUrl:re.string().min(1).optional(),model:re.string().min(1).optional(),name:re.string().min(1).optional(),provider:$w.optional()}).optional(),model:re.string().min(1).optional(),name:re.string().min(1).optional(),provider:$w.optional()});me();me();import{homedir as jfe}from"os";import{isAbsolute as qfe,resolve as Bfe}from"path";import{realpath as Kfe,stat as zfe}from"fs/promises";import{basename as Xfe,dirname as Vfe,isAbsolute as Yfe,join as Zfe,relative as eye,resolve as tye}from"path";ce();ce();import{embed as Iye,embedMany as vye}from"ai";import{createOpenAI as Cye}from"@ai-sdk/openai";import{createOpenAICompatible as _ye}from"@ai-sdk/openai-compatible";me();import{spawn as Ige}from"child_process";import{streamText as Gge}from"ai";Ye();me();ce();go();me();var mP=["WIKIGRAPH_DEV","WIKIGRAPH_ENV_POLICY","WIKIGRAPH_QUEUE_DISABLE_AUTOSTART","WIKIGRAPH_STATE_DIR"];function ek(t){let e=pP(t.env);if(t.envPolicy==="production"){let o=mP.filter(s=>e[s]!==void 0);if(o.length>0)throw new Error(`Wiki Graph production entries do not support runtime env overrides: ${o.join(", ")}. Use the development entry or explicit SDK options instead.`);return{env:e,envPolicy:t.envPolicy,stateDir:t.stateDir}}let n=e.WIKIGRAPH_DEV??e.WIKIGRAPH_STATE_DIR,r=Zw(t.stateDir??n);if(r===void 0)throw new Error("Wiki Graph development entries require an explicit runtime state directory.");let a=Zw(t.devProjectRoot);if(a===void 0)throw new Error("Wiki Graph development entries require an explicit project root.");return{devProjectRoot:a,env:e,envPolicy:t.envPolicy,stateDir:r}}function pP(t){return t===void 0?{...process.env}:{...process.env,...t}}function Zw(t){if(!(t===void 0||t.trim()===""))return t}ce();me();ce();import{mkdir as Jbe}from"fs/promises";var Ybe=64*1024;ce();import{basename as nSe}from"path";ce();me();go();me();var fP=new hP;async function tk(t,e){return await fP.run(t,async()=>await li({cwd:t.cwd,env:t.env,envPolicy:t.envPolicy,providers:{},...t.stateDir===void 0?{}:{stateDir:t.stateDir}},e))}var nk="--wikigraph-internal-child",rk="--wikigraph-dev-project-root",ik="--wikigraph-env-policy",ak="--wikigraph-state-dir";async function ok(t,e){let n=yP(process.argv.slice(2));if(n.internalChild!==t)throw new Error("This Wiki Graph worker entry is internal.");let r=ek({argv:n.argv,devProjectRoot:n.devProjectRoot,envPolicy:n.envPolicy,stateDir:n.stateDir});return await Si(r.stateDir,async()=>tk({argv:n.argv,cwd:process.cwd(),devProjectRoot:r.devProjectRoot,env:r.env,envPolicy:r.envPolicy,exitCode:0,queueAutostart:!1,stateDir:r.stateDir,stderr:process.stderr,stdin:process.stdin,stdout:process.stdout},async()=>await e(n)))}function yP(t){let e=[],n,r,a="production",o;for(let s=0;s<t.length;s+=1){let d=t[s];if(d===nk){if(s+1>=t.length)throw new Error(`${nk} requires a value.`);n=t[s+1],s+=1;continue}if(d===ik){let c=t[s+1];if(c!=="development"&&c!=="production")throw new Error(`${ik} requires development or production.`);a=c,s+=1;continue}if(d===rk){let c=t[s+1];if(c===void 0||c.trim()==="")throw new Error(`${rk} requires a value.`);r=c,s+=1;continue}if(d!==ak){e.push(d);continue}if(s+1>=t.length)throw new Error(`${ak} requires a value.`);o=t[s+1],s+=1}return{argv:e,devProjectRoot:r,envPolicy:a,internalChild:n??"",stateDir:o}}var gP={command:`${"wg"} --help`,config:`${"wg"} help config`,format:`${"wg"} help format`,readiness:`${"wg"} help readiness`,root:`${"wg"} --help`,runtime:`${"wg"} help runtime`,uri:`${"wg"} help uri`};import{extname as uwe}from"path";import{createReadStream as bwe}from"fs";import{mkdtemp as wwe,rm as kwe}from"fs/promises";import{join as Ewe}from"path";import{tmpdir as vwe}from"os";var bP=new Map(["at","seq","uri","id","jobId","type","target","label","labels","title","state","name","qid","predicate","subjectLabel","objectLabel","subjectQid","objectQid","score","queueRank","chapter","chapterId","fragment","fragmentId","position","range","start","end","shown","total","count","mentionCount","nodeCount","edgeCount","summaryCount","limit","order","match","lens","terms","types","chapters","query","objects","items","nextCursor","archiveKey","archivePath","workspacePath","eventsPath","createdAt","updatedAt","finishedAt","currentStep","step","phase","phaseDetail","phaseDone","phaseTotal","phaseUnit","words","totalWords","outputTokens","authors","language","identifier","publisher","publishedAt","sourceFormat","snippet","summary","description","recommendation","risk","error","message","children","nodes","links","neighbors","incoming","outgoing","nodeGroups","sourceFragments","sources","tree","meta","evidence","content","source","text","prompt","llmJSON","errorJSON"].map((t,e)=>[t,e]));function sk(t){return`${JSON.stringify(Hu(t),null,2)}
|
|
885
|
+
`}function Hu(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>Hu(e)??null);if(typeof t=="object")return SP(t)}function SP(t){let e=Object.entries(t).map(([r,a],o)=>({index:o,key:r,priority:bP.get(r)??Number.MAX_SAFE_INTEGER,value:a})),n={};for(let r of e.sort((a,o)=>a.priority-o.priority||a.index-o.index)){let a=Hu(r.value);a!==void 0&&(n[r.key]=a)}return n}import{homedir as Nwe}from"os";import{isAbsolute as Dwe,relative as Mwe,resolve as Fwe}from"path";import{existsSync as Bwe,readFileSync as Hwe}from"fs";import{dirname as Jwe,join as Kwe,parse as zwe,resolve as Qwe}from"path";ul();var{tryRunWikiGraphGc:MP}=await Promise.resolve().then(()=>(yk(),fk));async function FP(){await ok("gc-worker",async({argv:t})=>{let e=GP(t);process.stdout.write(sk(await MP({dryRun:e.dryRun,force:e.force})))})}function GP(t){return{dryRun:t.includes("--dry-run"),force:t.includes("--force")}}FP().catch(t=>{process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}
|
|
804
886
|
`),process.exitCode=1});
|
|
805
887
|
//# sourceMappingURL=gc-worker.js.map
|