wiki-graph 0.8.0 → 0.8.1
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 +485 -485
- package/dist/cli.js.map +1 -1
- package/dist/data/help/commands/library.jinja +7 -2
- package/dist/data/help/commands/predicate.jinja +11 -9
- package/dist/data/help/commands/uri.jinja +13 -0
- package/dist/data/help/topics/library.jinja +3 -1
- package/dist/data/help/topics/readiness.jinja +3 -3
- package/dist/data/help/topics/recipe.jinja +1 -1
- package/dist/data/help/topics/uri.jinja +6 -1
- package/dist/gc-worker.js +54 -54
- package/dist/gc-worker.js.map +1 -1
- package/dist/index.cjs +164 -17
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +164 -17
- package/dist/index.js.map +1 -1
- package/dist/queue-worker.js +475 -475
- 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 Jw=Object.defineProperty;var i=(t,e)=>()=>(t&&(e=t(t=0)),e);var Kw=(t,e)=>{for(var n in e)Jw(t,n,{get:e[n],enumerable:!0})};async function di(t){let e=await t.openReader();try{return e.size}finally{await e.close()}}async function gt(t){return await di(t)===0}async function ae(t){return new TextDecoder().decode(await Xt(t))}async function Xt(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 Ee(t){if(U(t)){let e=0;for(let n of await t.list())e+=await Ee(n);return e}return await di(t)}async function Qe(t){return await t.getLastModified?.()}function U(t){return t.kind==="directory"}var Eu=i(()=>{"use strict"});function no(t){Vt().installedPlatform=t}function A(){let{installedPlatform:t}=Vt();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 bt(t){if(typeof t!="string")return t;let e=await A().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=ro(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=ro(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=ro(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 ro(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 Vt(){let t=globalThis,e=t[Ru];if(e!==void 0)return e;let n={storageContext:new to};return Object.defineProperty(t,Ru,{configurable:!1,enumerable:!1,value:n,writable:!1}),n}function io(t){Vt().installedStorage=t}async function ui(t,e){return t===void 0?await e():await Vt().storageContext.run(t,e)}function v(){let{installedStorage:t,storageContext:e}=Vt(),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 Ru,to,y=i(()=>{"use strict";Eu();Ru=Symbol.for("wiki-graph-core.runtime.v1");to=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}=Vt();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 li(t){if(Qw.test(t))throw new Error(`invalid template name ${t}`);let n=t.replace(Xw,"").replace(zw,"");if(n.split("/").includes(".."))throw new Error(`invalid template name ${t}`);return`${n}.jinja`}var zw,Qw,Xw,Nn=i(()=>{"use strict";y();zw=/\.jinja$/iu,Qw=/^\.+\//u,Xw=/^\/+/u});var Cu=i(()=>{"use strict";y();Nn()});import*as _u from"async_hooks";import*as Pu from"crypto";import*as pi from"fs";import*as B from"fs/promises";import*as Au from"os";import*as O from"path";import*as uo from"process";import{Readable as Lu,Writable as Vw}from"stream";import{pipeline as Yw}from"stream/promises";import*as lo from"sqlite3";import*as Ou from"yauzl";import*as Nu from"yazl";import{Environment as Zw,Loader as ek}from"nunjucks";async function Tu(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 Wu(t,e,n){if(Du(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 Du(t){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("File offset must be a non-negative safe integer")}function Mu(t,e){return`node-${t}:${Buffer.from(O.resolve(e),"utf8").toString("base64url")}`}function ao(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 Wn(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 tk(t,e){let n=(e.mode==="readonly"?Dn.OPEN_READONLY:Dn.OPEN_READWRITE|(e.create?Dn.OPEN_CREATE:0))|Dn.OPEN_FULLMUTEX;return new so(await nk(t,n))}async function nk(t,e){let n=Fu(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 Dn.Database(n,e,s=>{s?a(s):r(o)})})}async function rk(t){let e=Fu(t,"file");if(e===void 0)throw new TypeError("The Node ZIP adapter requires a NodeFile");let n=await new Promise((o,s)=>{Ou.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 ik(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 ok(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 ik(t,e,n){let r=await n.openWriter();try{let a=await mi(t,e);await Gu(a,r),await r.commit()}catch(a){throw await r.abort().catch(()=>{}),a}}async function ak(t,e){return await ju(await mi(t,e))}async function ok(t,e,n,r){if(Wu(n,r,e.uncompressedSize),r===0)return new Uint8Array;if(e.compressionMethod!==0){let o=await sk(await mi(t,e),n,r);return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}let a=await ju(await mi(t,e,{decompress:null,decrypt:null,end:n+r,start:n}));return new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}async function sk(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 mi(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 dk(t,e){let n=new Nu.ZipFile,r=await t.openWriter(),a=n.outputStream,o=Gu(a,r),s={cancelled:!1,complete:!1},d;try{d=mk(e);let c=ck(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&&pk(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 ck(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(uk(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(lk(r.value),r.value.name,{compress:!1,size:r.value.size})}}function uk(t){return Lu.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 Fu(t,e){if(typeof t!="object"||t===null)return;let n=t;return n[mo]===e&&typeof n.path=="string"?n.path:void 0}function lk(t){return Lu.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 mk(t){let e=t[Symbol.asyncIterator];return e===void 0?t[Symbol.iterator]():e.call(t)}function pk(t){if(t.return!==void 0)try{Promise.resolve(t.return()).catch(()=>{})}catch{}}async function Gu(t,e){await Yw(t,new Vw({write:(n,r,a)=>{e.write(n).then(()=>a(),o=>a(o instanceof Error?o:new Error("Cannot stream ZIP archive")))}}))}async function ju(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 fk(){let t=globalThis.__WIKIGRAPH_DATA_DIR__;if(typeof t=="string"&&t!=="")return t;let e=oo.cwd();for(;;){for(let r of[O.join(e,"data"),O.join(e,"packages","core","data")])try{if(pi.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 Uu(t=O.join(Au.homedir(),".wikigraph")){return{library:new De(t),documentStore:new De(O.join(t,"documents"))}}function Mn(t){no(hk),io(Uu(t))}async function Yt(t,e){return await ui(t===void 0?void 0:Uu(t),e)}var oo,Dn,mo,se,De,so,hk,co,de=i(()=>{"use strict";Cu();oo=uo.default??uo,Dn=lo.default??lo,mo=Symbol.for("wiki-graph-sdk.node-resource.v1"),se=class{constructor(e,n=O.basename(e)){this.path=e;this.identity=Mu("file",e),this.name=n}path;kind="file";[mo]="file";identity;name;async openReader(){let e=await B.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");Wu(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 B.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async openWriter(){await B.mkdir(O.dirname(this.path),{recursive:!0});let e=`${this.path}.tmp-${Pu.randomUUID()}`,n=await B.open(e,"wx"),r=!1;return{write:async a=>{if(r)throw new Error("Cannot write to a closed FileWriter");await Tu(n,a)},writeAt:async(a,o)=>{if(r)throw new Error("Cannot write to a closed FileWriter");Du(a),await Tu(n,o,a)},commit:async()=>{r||(await n.close(),await B.rename(e,this.path)),r=!0},abort:async()=>{r||(await n.close(),await B.rm(e,{force:!0})),r=!0}}}};De=class t{constructor(e){this.path=e;this.identity=Mu("directory",e),this.name=O.basename(e)}path;kind="directory";[mo]="directory";identity;name;async getFile(e){Wn(e);let n=new se(O.join(this.path,e));try{return(await B.stat(n.path)).isFile()?n:void 0}catch{return}}async getLastModified(){try{return(await B.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async getDirectory(e){Wn(e);let n=new t(O.join(this.path,e));try{return(await B.stat(n.path)).isDirectory()?n:void 0}catch{return}}async list(){return(await B.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){Wn(e),await B.mkdir(this.path,{recursive:!0});let n=new se(O.join(this.path,e));return await B.writeFile(n.path,"",{flag:"wx"}),n}async createDirectory(e){Wn(e),await B.mkdir(this.path,{recursive:!0});let n=new t(O.join(this.path,e));return await B.mkdir(n.path),n}async remove(e,n){Wn(e),await B.rm(O.join(this.path,e),{force:!0,recursive:n?.recursive===!0})}};so=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()})})}};hk={asyncContext:{create:()=>new _u.AsyncLocalStorage},database:{open:tk},lifecycle:{instanceId:`node-process:${oo.pid}`,isInstanceAlive:t=>{let e=/^node-process:(\d+)$/u.exec(t);if(e===null)return Promise.resolve(void 0);try{return oo.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=ao(t,"directory");return Promise.resolve(e===void 0?void 0:new De(e))},getFile:t=>{let e=ao(t,"file");return Promise.resolve(e===void 0?void 0:new se(e))},resolveLegacyDirectory:t=>{let e=ao(t,"directory");return Promise.resolve(e===void 0?void 0:new De(e))}},templates:{createEnvironment:t=>new Zw(new co,t)},zip:{open:rk,write:dk}},co=class extends ek{#e;constructor(e){super(),this.#e=e}getSource(e){let n=li(e),r=O.join(this.#e??fk(),n);return{noCache:!1,path:n,src:pi.readFileSync(r,"utf8")}}}});var Me=i(()=>{"use strict"});function Bu(t){return new TextEncoder().encode(t)}function St(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}var Re=i(()=>{"use strict"});import{sha1 as yk}from"@noble/hashes/legacy.js";import{sha256 as gk,sha512 as bk}from"@noble/hashes/sha2.js";function oe(t){let e=Sk(t);return{update(n){return e.update(typeof n=="string"?Bu(n):n),this},digest(n){let r=e.digest();return n==="hex"?St(r):r}}}function Fn(t){let e=new Uint8Array(t);return globalThis.crypto.getRandomValues(e),e}function Xe(){if(typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();let t=Fn(16);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=St(t);return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function Sk(t){switch(t){case"sha1":return yk.create();case"sha256":return gk.create();case"sha512":return bk.create()}}var F=i(()=>{"use strict";Re()});var hi=i(()=>{"use strict";F()});var Hu=i(()=>{"use strict";y()});var $u=i(()=>{"use strict";Hu()});var Ju=i(()=>{"use strict"});function Fe(t){return t instanceof Error}function Zt(t){let e=[],n=new Set,r=t;for(;r!==void 0&&!n.has(r);){if(n.add(r),r instanceof Error){Ku(e,Rk(r)),r=r.cause;continue}Ku(e,String(r));break}return e.join(": ")}function Rk(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 Ku(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 zu=i(()=>{"use strict";pe()});var Qu=i(()=>{"use strict"});import{APICallError as KP}from"ai";var Xu=i(()=>{"use strict";y()});var Ve=i(()=>{"use strict";y()});var wt,jn=i(()=>{"use strict";wt=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 ho=i(()=>{"use strict";Ve()});var fo=i(()=>{"use strict"});var Vu=i(()=>{"use strict";y()});var yo=i(()=>{"use strict"});import{generateText as wA,streamText as kA}from"ai";var Zu=i(()=>{"use strict";$u();Ju();zu();Qu();Xu();Ve();Nn();jn();hi();pe();ho();fo();Vu();yo()});var el=i(()=>{"use strict";Zu()});var bo=i(()=>{"use strict";el();ho();fo();yo()});var Pk,So,tl,en=i(()=>{"use strict";Pk=Object.freeze(["serial-generation/editor-compress","serial-generation/editor-review","serial-generation/editor-review-guide","serial-generation/reader-choice","serial-generation/reader-extraction"]),So=Object.freeze({compress:"serial-generation/editor-compress",review:"serial-generation/editor-review",reviewGuide:"serial-generation/editor-review-guide"}),tl=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 wo=i(()=>{"use strict"});async function Lk(t){try{return await gt(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 Ak,N,ko,w=i(()=>{"use strict";y();pe();Ak=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=A().asyncContext.create()}static async open(e,n,r){let a=await bt(e),o=r.mode==="readwrite"&&r.create&&n.trim()!==""&&await Lk(a),s=r.mode==="readonly"?await A().database.open(a,{mode:"readonly"}):await A().database.open(a,{create:r.create,mode:"readwrite"}),d;try{return d=new t(new ko(s),r),await d.#o(`PRAGMA busy_timeout = ${Ak}`),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)}};ko=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 kt(){let t=v().library,e=yi.get(t.identity);if(e!==void 0){await e;return}let n=Nk(t);yi.set(t.identity,n);try{await n}finally{yi.get(t.identity)===n&&yi.delete(t.identity)}}async function ki(){let t=await J(v().library,"core.sqlite");if(t===void 0||await xi(t))return 0;let e=await N.open(t,"",{mode:"readonly"});try{return await tn(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 Nk(t){let e=await ki();if(e>xo)throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`);let n=await H(t,"core.sqlite");if(e===0){await gi(n,xo);return}for(;e<xo;)switch(e){case 1:await nl(t),await gi(n,2),e=2;break;case 2:await nl(t),await gi(n,3),e=3;break;case 3:await Wk(n),await gi(n,4),e=4;break;default:throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`)}}async function nl(t){await sl(t),await ol(t)}async function Wk(t){let e=v().library;await sl(e),await Dk(t),await ol(e)}async function Dk(t){let e=await N.open(t,"",{create:!1,mode:"readwrite"});try{if(!await tn(e,"libraries"))return;let n=await Si(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=A().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 gi(t,e){let n=await N.open(t,"",{create:!0,mode:"readwrite"});try{await n.execute(Ok),await n.run(`INSERT INTO schema_versions (scope, version, updated_at)
|
|
6
|
+
var Yw=Object.defineProperty;var i=(t,e)=>()=>(t&&(e=t(t=0)),e);var Zw=(t,e)=>{for(var n in e)Yw(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 Au=i(()=>{"use strict"});function lo(t){Yt().installedPlatform=t}function A(){let{installedPlatform:t}=Yt();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 A().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=mo(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=mo(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=mo(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 mo(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 Yt(){let t=globalThis,e=t[Lu];if(e!==void 0)return e;let n={storageContext:new uo};return Object.defineProperty(t,Lu,{configurable:!1,enumerable:!1,value:n,writable:!1}),n}function po(t){Yt().installedStorage=t}async function mi(t,e){return t===void 0?await e():await Yt().storageContext.run(t,e)}function R(){let{installedStorage:t,storageContext:e}=Yt(),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 Lu,uo,y=i(()=>{"use strict";Au();Lu=Symbol.for("wiki-graph-core.runtime.v1");uo=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}=Yt();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(tk.test(t))throw new Error(`invalid template name ${t}`);let n=t.replace(nk,"").replace(ek,"");if(n.split("/").includes(".."))throw new Error(`invalid template name ${t}`);return`${n}.jinja`}var ek,tk,nk,Fn=i(()=>{"use strict";y();ek=/\.jinja$/iu,tk=/^\.+\//u,nk=/^\/+/u});var Nu=i(()=>{"use strict";y();Fn()});import*as Du from"async_hooks";import*as Mu from"crypto";import*as fi from"fs";import*as B from"fs/promises";import*as Fu from"os";import*as O from"path";import*as bo from"process";import{Readable as Gu,Writable as rk}from"stream";import{pipeline as ik}from"stream/promises";import*as So from"sqlite3";import*as ju from"yauzl";import*as Uu from"yazl";import{Environment as ak,Loader as ok}from"nunjucks";async function Wu(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 Bu(t,e,n){if(qu(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 qu(t){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("File offset must be a non-negative safe integer")}function Hu(t,e){return`node-${t}:${Buffer.from(O.resolve(e),"utf8").toString("base64url")}`}function ho(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 Gn(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 sk(t,e){let n=(e.mode==="readonly"?jn.OPEN_READONLY:jn.OPEN_READWRITE|(e.create?jn.OPEN_CREATE:0))|jn.OPEN_FULLMUTEX;return new yo(await dk(t,n))}async function dk(t,e){let n=$u(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 jn.Database(n,e,s=>{s?a(s):r(o)})})}async function ck(t){let e=$u(t,"file");if(e===void 0)throw new TypeError("The Node ZIP adapter requires a NodeFile");let n=await new Promise((o,s)=>{ju.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 uk(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 mk(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 lk(n,s)}}}async function uk(t,e,n){let r=await n.openWriter();try{let a=await hi(t,e);await Ju(a,r),await r.commit()}catch(a){throw await r.abort().catch(()=>{}),a}}async function lk(t,e){return await Ku(await hi(t,e))}async function mk(t,e,n,r){if(Bu(n,r,e.uncompressedSize),r===0)return new Uint8Array;if(e.compressionMethod!==0){let o=await pk(await hi(t,e),n,r);return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}let a=await Ku(await hi(t,e,{decompress:null,decrypt:null,end:n+r,start:n}));return new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}async function pk(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 hk(t,e){let n=new Uu.ZipFile,r=await t.openWriter(),a=n.outputStream,o=Ju(a,r),s={cancelled:!1,complete:!1},d;try{d=bk(e);let c=fk(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&&Sk(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 fk(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(yk(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(gk(r.value),r.value.name,{compress:!1,size:r.value.size})}}function yk(t){return Gu.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 $u(t,e){if(typeof t!="object"||t===null)return;let n=t;return n[wo]===e&&typeof n.path=="string"?n.path:void 0}function gk(t){return Gu.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 bk(t){let e=t[Symbol.asyncIterator];return e===void 0?t[Symbol.iterator]():e.call(t)}function Sk(t){if(t.return!==void 0)try{Promise.resolve(t.return()).catch(()=>{})}catch{}}async function Ju(t,e){await ik(t,new rk({write:(n,r,a)=>{e.write(n).then(()=>a(),o=>a(o instanceof Error?o:new Error("Cannot stream ZIP archive")))}}))}async function Ku(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 kk(){let t=globalThis.__WIKIGRAPH_DATA_DIR__;if(typeof t=="string"&&t!=="")return t;let e=fo.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 zu(t=O.join(Fu.homedir(),".wikigraph")){return{library:new De(t),documentStore:new De(O.join(t,"documents"))}}function Un(t){lo(wk),po(zu(t))}async function Zt(t,e){return await mi(t===void 0?void 0:zu(t),e)}var fo,jn,wo,se,De,yo,wk,go,de=i(()=>{"use strict";Nu();fo=bo.default??bo,jn=So.default??So,wo=Symbol.for("wiki-graph-sdk.node-resource.v1"),se=class{constructor(e,n=O.basename(e)){this.path=e;this.identity=Hu("file",e),this.name=n}path;kind="file";[wo]="file";identity;name;async openReader(){let e=await B.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");Bu(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 B.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async openWriter(){await B.mkdir(O.dirname(this.path),{recursive:!0});let e=`${this.path}.tmp-${Mu.randomUUID()}`,n=await B.open(e,"wx"),r=!1;return{write:async a=>{if(r)throw new Error("Cannot write to a closed FileWriter");await Wu(n,a)},writeAt:async(a,o)=>{if(r)throw new Error("Cannot write to a closed FileWriter");qu(a),await Wu(n,o,a)},commit:async()=>{r||(await n.close(),await B.rename(e,this.path)),r=!0},abort:async()=>{r||(await n.close(),await B.rm(e,{force:!0})),r=!0}}}};De=class t{constructor(e){this.path=e;this.identity=Hu("directory",e),this.name=O.basename(e)}path;kind="directory";[wo]="directory";identity;name;async getFile(e){Gn(e);let n=new se(O.join(this.path,e));try{return(await B.stat(n.path)).isFile()?n:void 0}catch{return}}async getLastModified(){try{return(await B.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async getDirectory(e){Gn(e);let n=new t(O.join(this.path,e));try{return(await B.stat(n.path)).isDirectory()?n:void 0}catch{return}}async list(){return(await B.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){Gn(e),await B.mkdir(this.path,{recursive:!0});let n=new se(O.join(this.path,e));return await B.writeFile(n.path,"",{flag:"wx"}),n}async createDirectory(e){Gn(e),await B.mkdir(this.path,{recursive:!0});let n=new t(O.join(this.path,e));return await B.mkdir(n.path),n}async remove(e,n){Gn(e),await B.rm(O.join(this.path,e),{force:!0,recursive:n?.recursive===!0})}};yo=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()})})}};wk={asyncContext:{create:()=>new Du.AsyncLocalStorage},database:{open:sk},lifecycle:{instanceId:`node-process:${fo.pid}`,isInstanceAlive:t=>{let e=/^node-process:(\d+)$/u.exec(t);if(e===null)return Promise.resolve(void 0);try{return fo.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=ho(t,"directory");return Promise.resolve(e===void 0?void 0:new De(e))},getFile:t=>{let e=ho(t,"file");return Promise.resolve(e===void 0?void 0:new se(e))},resolveLegacyDirectory:t=>{let e=ho(t,"directory");return Promise.resolve(e===void 0?void 0:new De(e))}},templates:{createEnvironment:t=>new ak(new go,t)},zip:{open:ck,write:hk}},go=class extends ok{#e;constructor(e){super(),this.#e=e}getSource(e){let n=pi(e),r=O.join(this.#e??kk(),n);return{noCache:!1,path:n,src:fi.readFileSync(r,"utf8")}}}});var Me=i(()=>{"use strict"});function Qu(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 xk}from"@noble/hashes/legacy.js";import{sha256 as Ik,sha512 as Ek}from"@noble/hashes/sha2.js";function oe(t){let e=vk(t);return{update(n){return e.update(typeof n=="string"?Qu(n):n),this},digest(n){let r=e.digest();return n==="hex"?xt(r):r}}}function Bn(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=Bn(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 vk(t){switch(t){case"sha1":return xk.create();case"sha256":return Ik.create();case"sha512":return Ek.create()}}var F=i(()=>{"use strict";Ee()});var yi=i(()=>{"use strict";F()});var Vu=i(()=>{"use strict";y()});var Yu=i(()=>{"use strict";Vu()});var Zu=i(()=>{"use strict"});function Fe(t){return t instanceof Error}function en(t){let e=[],n=new Set,r=t;for(;r!==void 0&&!n.has(r);){if(n.add(r),r instanceof Error){el(e,Ak(r)),r=r.cause;continue}el(e,String(r));break}return e.join(": ")}function Ak(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&&Lk(n)?`${t.name} (${r})`:n===""?t.name:r===void 0?n:`${n} (${r})`}function Lk(t){return/(?:^|[\s:'"(=])\/(?:[^\s/]+\/)*[^\s/]+/u.test(t)||/(?:^|[\s:'"(=])[A-Za-z]:[\\/]/u.test(t)||/\bfile:\/\//iu.test(t)}function el(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 tl=i(()=>{"use strict";pe()});var nl=i(()=>{"use strict"});import{APICallError as tA}from"ai";var rl=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 xo=i(()=>{"use strict";et()});var Io=i(()=>{"use strict"});var il=i(()=>{"use strict";y()});var Eo=i(()=>{"use strict"});import{generateText as TA,streamText as _A}from"ai";var ol=i(()=>{"use strict";Yu();Zu();tl();nl();rl();et();Fn();Hn();yi();pe();xo();Io();il();Eo()});var sl=i(()=>{"use strict";ol()});var Ro=i(()=>{"use strict";sl();xo();Io();Eo()});var Dk,Co,dl,tn=i(()=>{"use strict";Dk=Object.freeze(["serial-generation/editor-compress","serial-generation/editor-review","serial-generation/editor-review-guide","serial-generation/reader-choice","serial-generation/reader-extraction"]),Co=Object.freeze({compress:"serial-generation/editor-compress",review:"serial-generation/editor-review",reviewGuide:"serial-generation/editor-review-guide"}),dl=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 To=i(()=>{"use strict"});async function Fk(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 Mk,N,_o,w=i(()=>{"use strict";y();pe();Mk=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=A().asyncContext.create()}static async open(e,n,r){let a=await kt(e),o=r.mode==="readwrite"&&r.create&&n.trim()!==""&&await Fk(a),s=r.mode==="readonly"?await A().database.open(a,{mode:"readonly"}):await A().database.open(a,{create:r.create,mode:"readwrite"}),d;try{return d=new t(new _o(s),r),await d.#o(`PRAGMA busy_timeout = ${Mk}`),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)}};_o=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=bi.get(t.identity);if(e!==void 0){await e;return}let n=jk(t);bi.set(t.identity,n);try{await n}finally{bi.get(t.identity)===n&&bi.delete(t.identity)}}async function Ii(){let t=await J(R().library,"core.sqlite");if(t===void 0||await Ei(t))return 0;let e=await N.open(t,"",{mode:"readonly"});try{return await nn(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 Ii();if(e>Po)throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`);let n=await H(t,"core.sqlite");if(e===0){await Si(n,Po);return}for(;e<Po;)switch(e){case 1:await cl(t),await Si(n,2),e=2;break;case 2:await cl(t),await Si(n,3),e=3;break;case 3:await Uk(n),await Si(n,4),e=4;break;default:throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`)}}async function cl(t){await hl(t),await pl(t)}async function Uk(t){let e=R().library;await hl(e),await Bk(t),await pl(e)}async function Bk(t){let e=await N.open(t,"",{create:!1,mode:"readwrite"});try{if(!await nn(e,"libraries"))return;let n=await ki(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=A().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 Si(t,e){let n=await N.open(t,"",{create:!0,mode:"readwrite"});try{await n.execute(Gk),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 $n(await t.getDirectory("cache"),["search-sessions.sqlite","continuation-cursors.sqlite","cache.sqlite"]);let e=await t.getDirectory("staging");await $n(e,["library","work"]),await wi(e,"staging.sqlite");let n=await t.getDirectory("tmp");await wi(n,"gc.sqlite"),await wi(n,"wikg-coordinator.sqlite"),await $n(n,["gc.last-run"]);let r=await t.getDirectory("jobs");await $n(r,["cache","work"]),await wi(r,"job.sqlite");let a=R().documentStore,o;try{o=await a.list()}catch(s){if(Fe(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 wi(t,e){await $n(t,[e,`${e}-wal`,`${e}-shm`])}async function $n(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 hl(t){await ll(await J(t,"core.sqlite"),[["library_locks","Cannot upgrade home with active library locks."],["state_locks","Cannot upgrade home with active state locks."]]),await ll(await J(t,"tmp/gc.sqlite"),[["gc_locks","Cannot upgrade home with an active GC lock."]]),await qk(await J(t,"jobs/job.sqlite")),await ul(await J(t,"staging/staging.sqlite"),"legacy coordinator"),await ul(await J(t,"tmp/wikg-coordinator.sqlite"),"coordinator")}async function qk(t){if(t===void 0||await Ei(t))return;let e=await N.open(t,"",{mode:"readonly"});try{if(await nn(e,"build_worker_lease")){let n=await ki(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()-xi],()=>!0)===!0)throw Jn("Cannot upgrade home with an active build worker.")}}finally{await e.close()}}async function ul(t,e){if(t===void 0||await Ei(t))return;let n=await N.open(t,"",{mode:"readonly"});try{if(await nn(n,"archive_owners")){let r=await ki(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(ml(o.heartbeatAt))throw Jn(`Cannot upgrade home with active ${e} state.`);continue}let s=await A().lifecycle.isInstanceAlive(o.hostInstanceId);if(s===!0||s===void 0&&ml(o.heartbeatAt))throw Jn(`Cannot upgrade home with active ${e} state.`)}}for(let r of["entry_locks","entry_sqlite_leases","archive_commit_locks"]){if(!await nn(n,r)||!(await ki(n,r)).has("heartbeat_at"))continue;if(await n.queryOne(`SELECT 1 AS active FROM ${r} WHERE heartbeat_at >= ? LIMIT 1`,[Date.now()-xi],()=>!0)===!0)throw Jn(`Cannot upgrade home with active ${e} state.`)}}finally{await n.close()}}async function ll(t,e){if(t===void 0||await Ei(t))return;let n=await N.open(t,"",{mode:"readonly"});try{for(let[r,a]of e){if(!await nn(n,r))continue;if(await n.queryOne(`SELECT 1 AS active FROM ${r} WHERE heartbeat_at >= ? LIMIT 1`,[Date.now()-xi],()=>!0)===!0)throw Jn(a)}}finally{await n.close()}}function Jn(t){return new Q("home_upgrade_blocked",t)}function ml(t){return t!==void 0&&Date.now()-t<=xi}async function Ei(t){return await wt(t)}async function ki(t,e){return new Set(await t.queryAll(`PRAGMA table_info(${e})`,void 0,n=>E(n,"name")))}async function nn(t,e){return await t.queryOne("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ?",[e],()=>!0)===!0}var Po,xi,Gk,bi,vi=i(()=>{"use strict";y();pe();Z();w();Po=4,xi=300*1e3,Gk=`
|
|
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
|
-
`,K),b(g,K),
|
|
21
|
+
`,bi=new Map});async function X(t,e,n={create:!0,mode:"readwrite"}){await Et();let r=await H(R().library,t);return n.mode==="readonly"?await Kn(r,e,n):await Kn(r,e,n)}async function Kn(t,e,n={create:!0,mode:"readwrite"}){let r=await kt(t);return n.mode==="readonly"?await N.open(r,e,n):await N.open(r,e,n)}var fl=i(()=>{"use strict";y();vi();w()});function Ci(...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 Ao(t){return Ci(t).split("/").at(-1)??""}var vt=i(()=>{"use strict"});var zn=i(()=>{"use strict";vt()});var yl=i(()=>{"use strict"});function rn(t){let e=new Set(Object.values(t));return n=>e.has(n)}function Qn(t,e){let n=rn(t);return r=>{if(n(r))return r;throw new Error(`Unknown ${e}: ${r}`)}}var Lo=i(()=>{"use strict"});var he,gl,Oo,ve,bl,Ti,Re=i(()=>{"use strict";Lo();he=(a=>(a.Verbatim="verbatim",a.Detailed="detailed",a.Focused="focused",a.Relevant="relevant",a))(he||{}),gl=rn(he),Oo=Qn(he,"chunk retention"),ve=(r=>(r.Critical="critical",r.Important="important",r.Helpful="helpful",r))(ve||{}),bl=rn(ve),Ti=Qn(ve,"chunk importance")});var No=i(()=>{"use strict";Re()});function tt(t){let e=0,n=!1;for(let r of t.trim()){if(Hk.test(r)){e+=1,n=!1;continue}if($k.test(r)){n||(e+=1),n=!0;continue}n&&Jk.test(r)||(n=!1)}return e}var Hk,$k,Jk,nt=i(()=>{"use strict";Hk=new RegExp("\\p{Script=Han}","u"),$k=/[\p{Letter}\p{Number}]/u,Jk=new RegExp("\\p{Mark}","u")});var wl=i(()=>{"use strict";nt();Re()});var _i=i(()=>{"use strict"});var Do=i(()=>{"use strict";zn();Re();No();wl();_i()});var kl=i(()=>{"use strict";zn();yl();Do()});var Mo=i(()=>{"use strict";kl();No();Do();_i()});var Pi=i(()=>{"use strict";y();vt()});var Fo=i(()=>{"use strict"});var Il=i(()=>{"use strict";vt();Pi()});var El=i(()=>{"use strict";nt()});var Go=i(()=>{"use strict"});var jo=i(()=>{"use strict";vt();pe();Fo();Pi();Il();El();Go()});var vl=i(()=>{"use strict";vt();Pi();jo()});var Uo=i(()=>{"use strict";vl();Fo();jo();Go()});import{z as fe}from"zod";var Bo,Ge,Rl,qo,Xn=i(()=>{"use strict";Bo=["epub","pdf","txt","markdown"],Ge=1,Rl=fe.enum(Bo),qo=fe.object({version:fe.literal(Ge),sourceFormat:Rl,title:fe.string().min(1).nullable().default(null),authors:fe.array(fe.string().min(1)),language:fe.string().min(1).nullable(),identifier:fe.string().min(1).nullable(),publisher:fe.string().min(1).nullable(),publishedAt:fe.string().min(1).nullable(),description:fe.string().min(1).nullable()})});function Cl(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(ex.has(t))throw new Error(`Invalid ${e}: ${t} is reserved.`);return t}var ex,ye=i(()=>{"use strict";Ee();F();ex=new Set(["tree","source","summary","title","state","chunk","entity","triple","cover","meta","job","help"])});import{z as je}from"zod";var rt,Ho,Tl,$o=i(()=>{"use strict";ye();rt=1,Ho=je.object({key:je.string().min(1).transform(t=>Cl(t)).optional(),title:je.string().min(1).nullable().optional(),serialId:je.number().int().nonnegative().optional(),children:je.lazy(()=>je.array(Ho))}),Tl=je.object({version:je.literal(rt),items:je.array(Ho)})});function Ce(t){let e=[];for(let n of t.replaceAll("\\","/").trim().split("/"))n===""||n==="."||(n===".."?e.pop():e.push(n));return e.join("/")}function tx(t){let[e]=t.split("#",1);return Ce(e??"")}function Jo(t){if(t===void 0)return;let e=t.startsWith("#")?t.slice(1):t;return e===""?void 0:e}function Vn(t){let[e,n]=t.split("#",2);return{path:Ce(e??""),fragment:Jo(n)}}function nx(t){return t.split("/").slice(0,-1).join("/")}function rx(...t){return t.filter(Boolean).join("/")}var Ai,Yn=i(()=>{"use strict";y();F();Ai=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 A().zip.open(e);try{let s=new Map;for(let d of await o.listEntries()){let c=Ce(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(Ce(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: ${Ce(e)}`);return r}resolveRelativePath(e,n){let r=tx(n);if(r==="")throw new Error(`Invalid EPUB href: ${n}`);return Ce(rx(nx(Ce(e)),r))}createSectionId(e,n){let r=Ce(e);return n===void 0||n===""?r:`${r}#${n}`}createSyntheticSectionId(e,n){let r=Ce(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=Ce(e),r=this.#t.get(n);if(r===void 0)throw new Error(`EPUB entry does not exist: ${n}`);return r}}});import{parseDocument as ix}from"htmlparser2";async function Nl(t,e){let n=new Map;for(let[r,a]of e.entries()){let o=await Wl(t,r),s=Dl(o,a);for(let d of a){let c=s.get(d.id)??"";n.set(d.id,{hasContent:c.trim()!=="",wordsCount:tt(c)})}}return n}function sx(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 Wl(t,e){return await t.readText(e)}function Dl(t,e){let n=Ml(t,e,!1);return new Map([...n.entries()].map(([r,a])=>[e[r].id,a.text]))}function dx(t,e,n){let r=Ml(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 Ml(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=ix(t,{decodeEntities:!0}),u=(c.children??[]).find(Al);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=ux(C);return[g,{segments:L.segments,text:L.text}]}));function m(g,C){if(Pl(g)){if(d<0||d>=o.length)return;let j=g.data??"";if(j==="")return;let ie=o[d],St=ie?.spineIndex;if(n&&St===void 0)throw new Error(`EPUB section ${ie?.id??"unknown"} cannot produce a CFI locator.`);let ci=n&&St!==void 0?Ol(St,C,0,j.length):Ko;f(d,j,ci,n?0:void 0,n?j.length:void 0);return}let L=px(g);if(L===void 0){b(g,C);return}if(ox.has(L))return;let K=C,q=g.attribs?.id??g.attribs?.["xml:id"];if(q!==void 0){let j=r.get(q);j!==void 0&&j>d&&(d=j)}L==="br"&&k(d,`
|
|
22
|
+
`,K),b(g,K),ax.has(L)&&k(d,`
|
|
23
23
|
|
|
24
|
-
`,K)}function b(g,C){let L=0,K=new Map;for(let q of g.children??[]){if(
|
|
24
|
+
`,K)}function b(g,C){let L=0,K=new Map;for(let q of g.children??[]){if(Pl(q)){if(d<0||d>=o.length)continue;let ie=q.data??"";if(ie==="")continue;let St=L*2+1,ci=K.get(St)??0;K.set(St,ci+ie.length);let Vw=Ll(C,St,!0);v(q,Vw,ci,ie.length);continue}if(!Al(q))continue;let j=Ll(C,L,!1,q.attribs?.id??q.attribs?.["xml:id"]);L+=1,m(q,j)}}function v(g,C,L,K){if(d<0||d>=o.length)return;let q=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,q,n&&ie!==void 0?Ol(ie,C,L,L+K):Ko,n?L:void 0,n?L+K:void 0)}function f(g,C,L,K,q){let j=a.get(g);j!==void 0&&j.push({locator:L,...q===void 0?{}:{locatorEnd:q},...K===void 0?{}:{locatorStart:K},text:C})}function k(g,C,L){if(g<0||g>=o.length)return;let K=o[g],q=K?.spineIndex;if(n&&q===void 0)throw new Error(`EPUB section ${K?.id??"unknown"} cannot produce a CFI locator.`);f(g,C,n&&q!==void 0?fx(q,L):Ko)}}function cx(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 ux(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:Fo(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 Fo(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=ax(r);if(a===void 0)throw new Error("EPUB text mapping has an invalid CFI range locator.");return{...t,cfi:`epubcfi(${a.parentPath},${El(a.startPath,e)},${El(a.endPath,n)})`}}function ax(t){if(!t.startsWith("epubcfi(")||!t.endsWith(")"))return;let e=ox(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 ox(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 El(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 Rl(t){return t.type==="text"}function vl(t){return t.name!==void 0&&t.type!=="directive"}function Cl(t,e,n,r){let a=n?e:(e+1)*2,o=n||r===void 0?"":`[${lx(r)}]`;return`${t}/${a}${o}`}function Tl(t,e,n,r){let a=Ol(t),{parentPath:o,textPath:s}=dx(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 dx(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 cx(t,e){return{cfi:`epubcfi(${ux(t)}${e})`}}function ux(t){return`${Ol(t)}!`}function Ol(t){return`/6/${(t+1)*2}`}function lx(t){return[...t].map(e=>"[]^(),;=".includes(e)?`^${e}`:e).join("")}var Zk,ex,Mo,Pi,Nl=i(()=>{"use strict";Ze();Zk=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"]),ex=new Set(["script","style"]),Mo={},Pi=class{#e;#t;constructor(e,n){this.#e=e,this.#t=tx(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=nx(o,r.targets,e),d=rx(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 Pl(this.#e,e);return Al(r,n)}}});import{SaxesParser as mx}from"saxes";function rn(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 Wl(r)}function ge(t,e){return t.children.find(n=>Xn(n.name)===e)}function je(t,e){return t.children.filter(n=>Xn(n.name)===e)}function ee(t,e){return t.attributes[e]}function Qn(t){let e=t.text;for(let n of t.children)e+=Qn(n);return e}function Xn(t){let e=t.indexOf(":");return e===-1?t:t.slice(e+1)}function Wl(t){return{name:t.name,attributes:Object.freeze({...t.attributes}),children:Object.freeze(t.children.map(Wl)),text:t.text}}var Ai=i(()=>{"use strict"});async function Ml(t){let e=await fx(t),n=rn(await t.readText(e)),r=yx(ee(n,"version")),a=ge(n,"metadata"),o=ge(n,"manifest"),s=ge(n,"spine"),d=ge(n,"guide"),c=bx(t,e,o),u=new Map([...c.values()].map(C=>[C.path,C])),m=Sx(s,c),b=wx(t,e,d),R=gx(a),f=kx(c),k=xx(c,s),g=Ix(c,a);return{version:r,opfPath:e,metadata:{...R,version:et,sourceFormat:"epub"},manifest:c,manifestByPath:u,spine:m,navPath:f,ncxPath:k,coverPath:g?.path,coverMediaType:g?.mediaType,guideNonContentPaths:b}}async function fx(t){let e=rn(await t.readText("META-INF/container.xml")),r=ge(e,"rootfiles")?.children.find(o=>Xn(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 yx(t){return t?.trim().startsWith("3")===!0?3:2}function gx(t){if(t===void 0)return Dl();let e=It(t,"title"),n=It(t,"creator"),r=It(t,"language"),a=It(t,"identifier"),o=It(t,"publisher"),s=It(t,"date"),d=It(t,"description");return{...Dl(),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 Dl(){return{version:et,sourceFormat:"epub",title:null,authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null}}function It(t,e){return t.children.filter(n=>Xn(n.name)===e).map(n=>Rx(Qn(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 je(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 Sx(t,e){return t===void 0?[]:je(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 wx(t,e,n){let r=new Set;if(n===void 0)return r;for(let a of je(n,"reference")){let o=(ee(a,"type")??"").trim().toLowerCase();if(!hx.has(o))continue;let s=ee(a,"href");s===void 0||s.trim()===""||r.add(t.resolveRelativePath(e,Kn(s).path))}return r}function kx(t){for(let e of t.values())if(e.properties.has("nav"))return e.path}function xx(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 Ix(t,e){for(let r of t.values())if(r.properties.has("cover-image")&&r.mediaType.startsWith("image/"))return r;let n=Ex(e);if(n!==void 0){let r=t.get(n);if(r?.mediaType.startsWith("image/")===!0)return r}for(let r of px){let a=t.get(r);if(a?.mediaType.startsWith("image/")===!0)return a}for(let r of t.values())if(r.mediaType.startsWith("image/")&&Io(r.path).toLowerCase().includes("cover"))return r}function Ex(t){if(t!==void 0)for(let e of je(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 Rx(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var px,hx,Go=i(()=>{"use strict";xt();Jn();zn();Ai();px=["cover-image","coverimg","cover-img","cover"],hx=new Set(["cover","titlepage","other.titlepage"])});import{parseDocument as vx}from"htmlparser2";async function Gl(t,e){let n=await Tx(t,e)??await _x(t,e)??[];if(n.length===0)return Fl(e,new Set);let r=Bl(n),a=Fl(e,r);return a.length===0?n:[...n,...a]}async function Tx(t,e){if(e.navPath===void 0)return;let n=vx(await t.readText(e.navPath),{decodeEntities:!0}),r=jo(n,s=>nt(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=jo(r,s=>nt(s)==="ol");if(a===void 0)return;let o=Vn(a).filter(s=>nt(s)==="li").map(s=>jl(t,e.navPath,s)).filter(s=>s!==void 0);return o.length===0?void 0:o}async function _x(t,e){if(e.ncxPath===void 0)return;let n=rn(await t.readText(e.ncxPath)),r=ge(n,"navMap");if(r===void 0)return;let a=je(r,"navPoint").map(o=>Ul(t,e.ncxPath,o)).filter(o=>o!==void 0);return a.length===0?void 0:a}function jl(t,e,n){let r=ql(n),a=r===void 0?void 0:Jl(Hl(r)),o=r!==void 0&&nt(r)==="a"?r.attribs?.href:void 0,s=Ax(t,e,o),d=Vn(n).filter(c=>nt(c)==="ol").flatMap(c=>Vn(c)).filter(c=>nt(c)==="li").map(c=>jl(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 Ul(t,e,n){let r=ge(n,"navLabel"),a=r===void 0?void 0:ge(r,"text"),o=a===void 0?void 0:Jl(Qn(a)),s=ge(n,"content"),d=Lx(t,e,ee(s??n,"src")),c=je(n,"navPoint").map(u=>Ul(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 Fl(t,e){return t.spine.filter(n=>!Px(t,n.path,e)).filter(n=>!e.has(n.path)).map(n=>({title:Ox(n.path),path:n.path,fragment:void 0,children:[]}))}function Px(t,e,n){if(t.guideNonContentPaths.has(e))return!0;let r=Uo(e).toLowerCase();return t.navPath===e?!0:Cx.has(r)&&!n.has(e)}function Bl(t){let e=new Set;for(let n of t){n.path!==void 0&&e.add(n.path);for(let r of Bl(n.children))e.add(r)}return e}function Ax(t,e,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Kn(n);return{path:r===""?void 0:t.resolveRelativePath(e,r),fragment:a}}function Lx(t,e,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Kn(n);return{path:r===""?void 0:t.resolveRelativePath(e,r),fragment:a}}function jo(t,e){if($l(t)&&e(t))return t;for(let n of t.children??[]){let r=jo(n,e);if(r!==void 0)return r}}function ql(t){for(let e of Vn(t)){let n=nt(e);if(n==="a"||n==="span")return e}for(let e of Vn(t)){if(nt(e)==="ol")continue;let n=ql(e);if(n!==void 0)return n}}function Hl(t){return t.type==="text"?t.data??"":(t.children??[]).map(Hl).join("")}function Vn(t){return(t.children??[]).filter($l)}function $l(t){return t.type==="tag"||t.type==="script"||t.type==="style"}function nt(t){return t.name?.toLowerCase()}function Ox(t){let e=Nx(t),n=Uo(t).slice(0,-e.length||void 0).trim();return n===""?void 0:n}function Uo(t){return t.replaceAll("\\","/").split("/").at(-1)??""}function Nx(t){let e=Uo(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n)}function Jl(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var Cx,Kl=i(()=>{"use strict";zn();Go();Ai();Cx=new Set(["toc.xhtml","nav.xhtml","contents.xhtml","tableofcontents.xhtml","cover.xhtml","titlepage.xhtml"])});function Wx(t){if(t.hasEntry("META-INF/encryption.xml"))throw new Error("Encrypted EPUB is not supported: found META-INF/encryption.xml.")}async function Dx(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 Mx(t,e){let n=new Map;return e.map((r,a)=>zl(t,r,[a],n))}function zl(t,e,n,r){let a=Do(e.fragment),o=e.path===void 0?`toc:${n.join(".")}`:t.createSectionId(e.path,a),s=Fx(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)=>zl(t,d,[...n,c],r))}}function Ql(t,e){return t.map(n=>{let r=e.get(n.id);return{...n,hasContent:r?.hasContent??!1,wordsCount:r?.wordsCount??0,children:Ql(n.children,e)}})}function Fx(t,e){let n=e.get(t)??0;return e.set(t,n+1),n===0?t:`${t}~${n+1}`}function Gx(t,e){let n=new Map,r=new Map(e.spine.map(a=>[a.path,a.spineIndex]));for(let a of Xl(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 Xl(t){let e=[];for(let n of t)e.push(n),e.push(...Xl(n.children));return e}var Bo,qo,Yn,Ho,Vl=i(()=>{"use strict";zn();zn();Nl();Kl();Go();Bo=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)}},qo=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){Wx(e);let n=await Ml(e),r={digest:e.digest,mediaType:"application/epub+zip",name:e.name,...n.metadata.identifier===null?{}:{identifier:n.metadata.identifier}},a=await Gl(e,n),o=Mx(e,a),s=Gx(o,n),d=await _l(e,s),c=Ql(o,d),u=await Dx(e,n);return new t(r,n,u,c,new Pi(e,s))}readMeta(){return Promise.resolve(this.#t.metadata)}readCover(){return Promise.resolve(this.#n)}readSections(){return Promise.resolve(this.#r.map(e=>new Bo(this,e)))}async openSection(e){return await this.#i.openSection(e)}async openSectionWithProvenance(e){return await this.#i.openSectionWithProvenance(e,this.#e)}},Yn=class{get format(){return"epub"}async openSession(e,n){let r=await _i.open(e);try{let a=await qo.open(r);return await n(a)}finally{await r.close()}}},Ho=new Yn});var Yl=i(()=>{"use strict";Vl()});var Zl=i(()=>{"use strict";y()});import{SaxesParser as aN}from"saxes";var em=i(()=>{"use strict";Ze();Ai();Zl()});var nm=i(()=>{"use strict";em()});async function*Ux(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 Bx(t){let e=t.lastIndexOf("."),n=(e<=0?t:t.slice(0,e)).trim();return n===""?null:n}var jx,$o,Jo,Zn,rm,im,am=i(()=>{"use strict";Jn();jx="root",$o=class{#e;#t;constructor(e,n=jx){this.#e=e,this.#t=n}get id(){return this.#t}get hasContent(){return!0}get title(){}get children(){return[]}open(){return Promise.resolve(Ux(this.#e))}},Jo=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,this.#e=new $o(e)}readMeta(){return Promise.resolve({version:et,sourceFormat:this.#n,title:Bx(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])}},Zn=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 Jo(e,this.#e))}},rm=new Zn("txt"),im=new Zn("markdown")});var er=i(()=>{"use strict"});import{z as ue}from"zod";var gN,bN,om=i(()=>{"use strict";er();gN=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()}),bN=ue.object({type:ue.literal("text"),text:ue.string(),locator:ue.record(ue.string(),ue.unknown())})});var Et=i(()=>{"use strict";Jn();Yl();nm();am();om();Wo()});var zo=i(()=>{"use strict"});var tr=i(()=>{"use strict";Et();ye();zo();Z()});var qx,dm,cm,um,nr=i(()=>{"use strict";w();er();qx=`
|
|
26
|
+
`,locator:zo(c.locator,f,k),locatorEnd:k,locatorStart:f}),b+=1):e.push({baseLocator:c.locator,char:v,locator:zo(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: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=lx(r);if(a===void 0)throw new Error("EPUB text mapping has an invalid CFI range locator.");return{...t,cfi:`epubcfi(${a.parentPath},${_l(a.startPath,e)},${_l(a.endPath,n)})`}}function lx(t){if(!t.startsWith("epubcfi(")||!t.endsWith(")"))return;let e=mx(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 mx(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 _l(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 px(t){return t.name?.toLowerCase()}function Pl(t){return t.type==="text"}function Al(t){return t.name!==void 0&&t.type!=="directive"}function Ll(t,e,n,r){let a=n?e:(e+1)*2,o=n||r===void 0?"":`[${gx(r)}]`;return`${t}/${a}${o}`}function Ol(t,e,n,r){let a=Fl(t),{parentPath:o,textPath:s}=hx(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 hx(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 fx(t,e){return{cfi:`epubcfi(${yx(t)}${e})`}}function yx(t){return`${Fl(t)}!`}function Fl(t){return`/6/${(t+1)*2}`}function gx(t){return[...t].map(e=>"[]^(),;=".includes(e)?`^${e}`:e).join("")}var ax,ox,Ko,Li,Gl=i(()=>{"use strict";nt();ax=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"]),ox=new Set(["script","style"]),Ko={},Li=class{#e;#t;constructor(e,n){this.#e=e,this.#t=sx(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=dx(o,r.targets,e),d=cx(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 Wl(this.#e,e);return Dl(r,n)}}});import{SaxesParser as bx}from"saxes";function an(t){let e=new bx({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 jl(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 jl(t){return{name:t.name,attributes:Object.freeze({...t.attributes}),children:Object.freeze(t.children.map(jl)),text:t.text}}var Oi=i(()=>{"use strict"});async function Bl(t){let e=await kx(t),n=an(await t.readText(e)),r=xx(ee(n,"version")),a=ge(n,"metadata"),o=ge(n,"manifest"),s=ge(n,"spine"),d=ge(n,"guide"),c=Ex(t,e,o),u=new Map([...c.values()].map(C=>[C.path,C])),m=vx(s,c),b=Rx(t,e,d),v=Ix(a),f=Cx(c),k=Tx(c,s),g=_x(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 kx(t){let e=an(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 xx(t){return t?.trim().startsWith("3")===!0?3:2}function Ix(t){if(t===void 0)return Ul();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{...Ul(),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 Ul(){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=>Ax(Zn(n))).filter(n=>n!==void 0)}function Ex(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 vx(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 Rx(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(!wx.has(o))continue;let s=ee(a,"href");s===void 0||s.trim()===""||r.add(t.resolveRelativePath(e,Vn(s).path))}return r}function Cx(t){for(let e of t.values())if(e.properties.has("nav"))return e.path}function Tx(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 _x(t,e){for(let r of t.values())if(r.properties.has("cover-image")&&r.mediaType.startsWith("image/"))return r;let n=Px(e);if(n!==void 0){let r=t.get(n);if(r?.mediaType.startsWith("image/")===!0)return r}for(let r of Sx){let a=t.get(r);if(a?.mediaType.startsWith("image/")===!0)return a}for(let r of t.values())if(r.mediaType.startsWith("image/")&&Ao(r.path).toLowerCase().includes("cover"))return r}function Px(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 Ax(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var Sx,wx,Qo=i(()=>{"use strict";vt();Xn();Yn();Oi();Sx=["cover-image","coverimg","cover-img","cover"],wx=new Set(["cover","titlepage","other.titlepage"])});import{parseDocument as Lx}from"htmlparser2";async function Hl(t,e){let n=await Nx(t,e)??await Wx(t,e)??[];if(n.length===0)return ql(e,new Set);let r=Kl(n),a=ql(e,r);return a.length===0?n:[...n,...a]}async function Nx(t,e){if(e.navPath===void 0)return;let n=Lx(await t.readText(e.navPath),{decodeEntities:!0}),r=Xo(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=Xo(r,s=>it(s)==="ol");if(a===void 0)return;let o=tr(a).filter(s=>it(s)==="li").map(s=>$l(t,e.navPath,s)).filter(s=>s!==void 0);return o.length===0?void 0:o}async function Wx(t,e){if(e.ncxPath===void 0)return;let n=an(await t.readText(e.ncxPath)),r=ge(n,"navMap");if(r===void 0)return;let a=Ue(r,"navPoint").map(o=>Jl(t,e.ncxPath,o)).filter(o=>o!==void 0);return a.length===0?void 0:a}function $l(t,e,n){let r=zl(n),a=r===void 0?void 0:Vl(Ql(r)),o=r!==void 0&&it(r)==="a"?r.attribs?.href:void 0,s=Mx(t,e,o),d=tr(n).filter(c=>it(c)==="ol").flatMap(c=>tr(c)).filter(c=>it(c)==="li").map(c=>$l(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 Jl(t,e,n){let r=ge(n,"navLabel"),a=r===void 0?void 0:ge(r,"text"),o=a===void 0?void 0:Vl(Zn(a)),s=ge(n,"content"),d=Fx(t,e,ee(s??n,"src")),c=Ue(n,"navPoint").map(u=>Jl(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 ql(t,e){return t.spine.filter(n=>!Dx(t,n.path,e)).filter(n=>!e.has(n.path)).map(n=>({title:Gx(n.path),path:n.path,fragment:void 0,children:[]}))}function Dx(t,e,n){if(t.guideNonContentPaths.has(e))return!0;let r=Vo(e).toLowerCase();return t.navPath===e?!0:Ox.has(r)&&!n.has(e)}function Kl(t){let e=new Set;for(let n of t){n.path!==void 0&&e.add(n.path);for(let r of Kl(n.children))e.add(r)}return e}function Mx(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 Fx(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 Xo(t,e){if(Xl(t)&&e(t))return t;for(let n of t.children??[]){let r=Xo(n,e);if(r!==void 0)return r}}function zl(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=zl(e);if(n!==void 0)return n}}function Ql(t){return t.type==="text"?t.data??"":(t.children??[]).map(Ql).join("")}function tr(t){return(t.children??[]).filter(Xl)}function Xl(t){return t.type==="tag"||t.type==="script"||t.type==="style"}function it(t){return t.name?.toLowerCase()}function Gx(t){let e=jx(t),n=Vo(t).slice(0,-e.length||void 0).trim();return n===""?void 0:n}function Vo(t){return t.replaceAll("\\","/").split("/").at(-1)??""}function jx(t){let e=Vo(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n)}function Vl(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var Ox,Yl=i(()=>{"use strict";Yn();Qo();Oi();Ox=new Set(["toc.xhtml","nav.xhtml","contents.xhtml","tableofcontents.xhtml","cover.xhtml","titlepage.xhtml"])});function Ux(t){if(t.hasEntry("META-INF/encryption.xml"))throw new Error("Encrypted EPUB is not supported: found META-INF/encryption.xml.")}async function Bx(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)=>Zl(t,r,[a],n))}function Zl(t,e,n,r){let a=Jo(e.fragment),o=e.path===void 0?`toc:${n.join(".")}`:t.createSectionId(e.path,a),s=Hx(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)=>Zl(t,d,[...n,c],r))}}function em(t,e){return t.map(n=>{let r=e.get(n.id);return{...n,hasContent:r?.hasContent??!1,wordsCount:r?.wordsCount??0,children:em(n.children,e)}})}function Hx(t,e){let n=e.get(t)??0;return e.set(t,n+1),n===0?t:`${t}~${n+1}`}function $x(t,e){let n=new Map,r=new Map(e.spine.map(a=>[a.path,a.spineIndex]));for(let a of tm(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 tm(t){let e=[];for(let n of t)e.push(n),e.push(...tm(n.children));return e}var Yo,Zo,nr,es,nm=i(()=>{"use strict";Yn();Yn();Gl();Yl();Qo();Yo=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)}},Zo=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){Ux(e);let n=await Bl(e),r={digest:e.digest,mediaType:"application/epub+zip",name:e.name,...n.metadata.identifier===null?{}:{identifier:n.metadata.identifier}},a=await Hl(e,n),o=qx(e,a),s=$x(o,n),d=await Nl(e,s),c=em(o,d),u=await Bx(e,n);return new t(r,n,u,c,new Li(e,s))}readMeta(){return Promise.resolve(this.#t.metadata)}readCover(){return Promise.resolve(this.#n)}readSections(){return Promise.resolve(this.#r.map(e=>new Yo(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 Ai.open(e);try{let a=await Zo.open(r);return await n(a)}finally{await r.close()}}},es=new nr});var rm=i(()=>{"use strict";nm()});var im=i(()=>{"use strict";y()});import{SaxesParser as pN}from"saxes";var am=i(()=>{"use strict";nt();Oi();im()});var sm=i(()=>{"use strict";am()});async function*Kx(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 zx(t){let e=t.lastIndexOf("."),n=(e<=0?t:t.slice(0,e)).trim();return n===""?null:n}var Jx,ts,ns,rr,dm,cm,um=i(()=>{"use strict";Xn();Jx="root",ts=class{#e;#t;constructor(e,n=Jx){this.#e=e,this.#t=n}get id(){return this.#t}get hasContent(){return!0}get title(){}get children(){return[]}open(){return Promise.resolve(Kx(this.#e))}},ns=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,this.#e=new ts(e)}readMeta(){return Promise.resolve({version:Ge,sourceFormat:this.#n,title:zx(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 ns(e,this.#e))}},dm=new rr("txt"),cm=new rr("markdown")});var ir=i(()=>{"use strict"});import{z as ue}from"zod";var vN,RN,lm=i(()=>{"use strict";ir();vN=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()}),RN=ue.object({type:ue.literal("text"),text:ue.string(),locator:ue.record(ue.string(),ue.unknown())})});var at=i(()=>{"use strict";Xn();rm();sm();um();lm();$o()});var is=i(()=>{"use strict"});var ar=i(()=>{"use strict";at();ye();is();Z()});var Qx,pm,hm,fm,or=i(()=>{"use strict";w();ir();Qx=`
|
|
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 Jw=Object.defineProperty;var i=(t,e)=>()=>(t&&(e=t(t=0)),e);var Kw=(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 Jw=Object.defineProperty;var i=(t,e)=>()=>(t&&(e=t(t=0)),e);var Kw=(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
|
+
${Qx}
|
|
334
334
|
);
|
|
335
335
|
|
|
336
336
|
CREATE TABLE IF NOT EXISTS source_locators (
|
|
@@ -396,7 +396,7 @@ ${qx}
|
|
|
396
396
|
triple_predicate,
|
|
397
397
|
triple_object_qid
|
|
398
398
|
);
|
|
399
|
-
`,
|
|
399
|
+
`,hm=`
|
|
400
400
|
id INTEGER PRIMARY KEY,
|
|
401
401
|
archive_id INTEGER NOT NULL,
|
|
402
402
|
kind INTEGER NOT NULL,
|
|
@@ -406,14 +406,14 @@ ${qx}
|
|
|
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
|
+
`,fm=`
|
|
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
|
+
${hm}
|
|
417
417
|
);
|
|
418
418
|
|
|
419
419
|
CREATE INDEX IF NOT EXISTS idx_text_sentence_records_chapter
|
|
@@ -470,22 +470,22 @@ ${cm}
|
|
|
470
470
|
updated_at INTEGER NOT NULL,
|
|
471
471
|
PRIMARY KEY (archive_id, chapter_id)
|
|
472
472
|
);
|
|
473
|
-
`});var
|
|
473
|
+
`});var Ct=i(()=>{"use strict";w();Re()});var ym=i(()=>{"use strict";w();Ct()});var gm=i(()=>{"use strict";w()});var bm=i(()=>{"use strict";w();yi()});var Sm=i(()=>{"use strict";w();Re()});var wm=i(()=>{"use strict";w();Ct()});var km=i(()=>{"use strict";w();Ct()});var xm=i(()=>{"use strict";w();Ct()});var Im=i(()=>{"use strict";w();Ct()});var Em=i(()=>{"use strict";w();Ct()});var Cm=i(()=>{"use strict";Ee();w();ir()});var Tm=i(()=>{"use strict";w()});var _m=i(()=>{"use strict";w()});var Pm=i(()=>{"use strict";w()});var Am=i(()=>{"use strict";Tm();_m();Pm()});var ds=i(()=>{"use strict";ym();gm();bm();Sm();wm();km();xm();Im();Em();Cm();Am()});var cs=i(()=>{"use strict"});var $m=i(()=>{"use strict";y()});var Jm=i(()=>{"use strict";pe();zn()});var Tt=i(()=>{"use strict"});var Km=i(()=>{"use strict";y();w();or();Tt()});var zm=i(()=>{"use strict";pe();cs()});var Qm=i(()=>{"use strict"});import{z as us}from"zod";var iM,Vm=i(()=>{"use strict";y();Xn();$o();ar();w();Mo();or();ds();Re();cs();$m();Jm();Km();zn();zm();Qm();iM=us.object({mediaType:us.string().min(1),path:us.string()})});var Ym=i(()=>{"use strict"});var ms=i(()=>{"use strict";Vm();Ym()});var ep=i(()=>{"use strict";Uo()});var _=i(()=>{"use strict";w();fl();Mo();Uo();ms();ep();or();ir();ds();Re()});var hs=i(()=>{"use strict"});var qe=i(()=>{"use strict";hs()});async function ip(t){let e=await nI(t);try{return await tI(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 tI(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:rI(o),resourceKey:E(o,"resource_key"),scope:E(o,"scope")}));for(let{lock:o,resourceKey:s,scope:d}of a)aI(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 nI(t){if(t.databaseFile!==void 0)return await N.open(t.databaseFile,rp,{create:!0,mode:"readwrite"});if(t.stateDatabaseName!==void 0)return await X(t.stateDatabaseName,rp);throw new Error("State lock requires a database File or state database name.")}function rI(t){return{heartbeatAt:S(t,"heartbeat_at"),mode:iI(E(t,"mode")),ownerId:E(t,"owner_id")}}function iI(t){return t==="read"||t==="write"?t:"write"}function aI(t,e=eI){return Date.now()-t.heartbeatAt>e}var rp,eI,Ni=i(()=>{"use strict";F();w();_();rp=`
|
|
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 @@ ${cm}
|
|
|
499
499
|
|
|
500
500
|
CREATE INDEX IF NOT EXISTS idx_state_locks_resource
|
|
501
501
|
ON state_locks(scope, resource_key);
|
|
502
|
-
`,
|
|
502
|
+
`,eI=300*1e3});async function sp(t){return await ip({stateDatabaseName:"core.sqlite",resourceKey:dI(t),scope:sI,staleMs:op})||await cI(t)}function dI(t){return String(t)}async function cI(t){let e=await uI();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&&mI(n)}finally{await e.close()}}async function uI(){let t=await X("core.sqlite",oI);return await lI(t),t}async function lI(t){new Set(await t.queryAll("PRAGMA table_info(library_locks)",void 0,n=>E(n,"name"))).has("heartbeat_at")||await t.run("ALTER TABLE library_locks ADD COLUMN heartbeat_at INTEGER NOT NULL DEFAULT 0")}function mI(t){return Date.now()-t.heartbeatAt<=op}var oI,sI,op,_t=i(()=>{"use strict";w();_();Ni();oI=`
|
|
503
503
|
CREATE TABLE IF NOT EXISTS library_locks (
|
|
504
504
|
library_id INTEGER PRIMARY KEY,
|
|
505
505
|
mode TEXT NOT NULL,
|
|
@@ -508,7 +508,7 @@ ${cm}
|
|
|
508
508
|
heartbeat_at INTEGER NOT NULL,
|
|
509
509
|
created_at INTEGER NOT NULL
|
|
510
510
|
);
|
|
511
|
-
`,
|
|
511
|
+
`,sI="library",op=300*1e3});var qM,Lt=i(()=>{"use strict";y();w();_();qe();Ee();F();_t();hs();qM=Promise.resolve()});var $M,dr=i(()=>{"use strict";$M=new RegExp("\\p{Script=Han}","u")});var ys=i(()=>{"use strict";Ee()});var gs,Ot=i(()=>{"use strict";gs=`
|
|
512
512
|
CREATE TABLE IF NOT EXISTS search_sessions (
|
|
513
513
|
session_id TEXT PRIMARY KEY,
|
|
514
514
|
archive_key TEXT NOT NULL,
|
|
@@ -612,31 +612,31 @@ ON search_sessions(expires_at);
|
|
|
612
612
|
|
|
613
613
|
CREATE INDEX IF NOT EXISTS idx_search_sessions_prune
|
|
614
614
|
ON search_sessions(accessed_at DESC, created_at DESC, session_id);
|
|
615
|
-
`});async function
|
|
615
|
+
`});async function on(){let t=await X("cache/search-sessions.sqlite",gs);return bs?t:await hI(t)?(bs=!0,t):(await pI(t),bs=!0,t)}async function pI(t){await t.execute(`
|
|
616
616
|
DROP TABLE IF EXISTS search_evidence_hit_events;
|
|
617
617
|
DROP TABLE IF EXISTS search_triple_hits;
|
|
618
618
|
DROP TABLE IF EXISTS search_entity_hits;
|
|
619
619
|
DROP TABLE IF EXISTS search_chunk_hits;
|
|
620
620
|
DROP TABLE IF EXISTS search_sessions;
|
|
621
|
-
${
|
|
622
|
-
`)}async function
|
|
621
|
+
${gs}
|
|
622
|
+
`)}async function hI(t){return await Wi(t,"search_entity_hits","archive_id")&&await Wi(t,"search_chunk_hits","archive_id")&&await Wi(t,"search_triple_hits","archive_id")&&await Wi(t,"search_evidence_hit_events","archive_id")}async function Wi(t,e,n){return(await t.queryAll(`PRAGMA table_info(${e})`,void 0,a=>String(a.name))).includes(n)}var bs,sn=i(()=>{"use strict";_();Ot();bs=!1});var Di=i(()=>{"use strict"});async function up(t,e){await lp(t,e),await t.run("DELETE FROM search_sessions WHERE session_id = ?",[e])}async function lp(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 mp(t){await t.run(`
|
|
623
623
|
DELETE FROM predicate_dictionary
|
|
624
624
|
WHERE NOT EXISTS (
|
|
625
625
|
SELECT 1
|
|
626
626
|
FROM search_triple_hits
|
|
627
627
|
WHERE search_triple_hits.predicate_id = predicate_dictionary.id
|
|
628
628
|
)
|
|
629
|
-
`)}var
|
|
629
|
+
`)}var Ss=i(()=>{"use strict";w();sn();Di();Ot()});async function Mi(t){let e=await on();try{let n=await pp(e),r=await e.queryOne("SELECT COUNT(*) AS count FROM search_sessions",void 0,c=>S(c,"count")),a=t.force?await bI(e):await gI(e,t.now),o=t.force?[]:await SI(e),s=[...new Set([...a,...o])].sort();!t.dryRun&&s.length>0&&(await e.transaction(async()=>{for(let c of s)await up(e,c);await mp(e)}),await e.run("VACUUM"));let d=await pp(e);return{freedBytes:Math.max(0,n-d),removed:s.length,scanned:r??0}}finally{await e.close()}}async function gI(t,e){return await t.queryAll(`
|
|
630
630
|
SELECT session_id
|
|
631
631
|
FROM search_sessions
|
|
632
632
|
WHERE expires_at < ?
|
|
633
|
-
`,[e],n=>E(n,"session_id"))}async function
|
|
633
|
+
`,[e],n=>E(n,"session_id"))}async function bI(t){return await t.queryAll("SELECT session_id FROM search_sessions",void 0,e=>E(e,"session_id"))}async function SI(t){return await t.queryAll(`
|
|
634
634
|
SELECT session_id
|
|
635
635
|
FROM search_sessions
|
|
636
636
|
ORDER BY accessed_at DESC, created_at DESC, session_id
|
|
637
637
|
LIMIT -1 OFFSET ?
|
|
638
|
-
`,[500],e=>E(e,"session_id"))}async function
|
|
639
|
-
`,
|
|
638
|
+
`,[500],e=>E(e,"session_id"))}async function pp(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 hp=i(()=>{"use strict";w();sn();Ot();Ss()});var fp=i(()=>{"use strict";Ot()});var ws=i(()=>{"use strict"});var Fi=i(()=>{"use strict";w();sn();Di();fp();ws()});var gp=i(()=>{"use strict";F();Ot()});var bp=i(()=>{"use strict";w();ys();sn();Fi();gp();Di();Ot();Ss()});var Sp=i(()=>{"use strict";w();sn();Fi()});var Wt=i(()=>{"use strict";ys();hp();Fi();bp();Sp();ws()});var Gi=i(()=>{"use strict"});var ji=i(()=>{"use strict";at()});var xs=i(()=>{"use strict";Ee()});var Ui=i(()=>{"use strict"});var Is=i(()=>{"use strict";Ui()});var Es=i(()=>{"use strict";Ui()});var Bi=i(()=>{"use strict";Gi();xs();Is();Es()});var Lp=i(()=>{"use strict";qe()});var Op=i(()=>{"use strict";Gi();ji();xs();Ui();Bi();Is();Es();Lp()});var W=i(()=>{"use strict";Op()});var Rs=i(()=>{"use strict"});var Cs=i(()=>{"use strict";Z();ar();is();Rs()});var Np=i(()=>{"use strict";Cs()});var Y=i(()=>{"use strict";Cs();Np();Rs()});var uj,lj,Dt=i(()=>{"use strict";F();uj=new RegExp("\\p{Script=Han}+","gu"),lj=new RegExp("^\\p{Script=Han}+$","u")});var qi=i(()=>{"use strict";F()});var Ps=i(()=>{"use strict";Tt()});var Hi=i(()=>{"use strict";w();Ps()});var Mp=i(()=>{"use strict";Dt();qi();Hi();Tt()});var Gp=i(()=>{"use strict";Tt()});var jp=i(()=>{"use strict";Dt()});var Up=i(()=>{"use strict"});var Ws=i(()=>{"use strict";w();Up();qi()});var qp=i(()=>{"use strict";w();Dt();jp();Ps();Tt();Ws();Hi()});var Hp=i(()=>{"use strict";Mp();Gp();qi();qp();Ws();Tt();Hi()});var $e=i(()=>{"use strict";Hp();Dt()});var Mt=i(()=>{"use strict";Y();$e();Dt();ji()});var ne=i(()=>{"use strict";ye();qe();W()});var Se=i(()=>{"use strict";qe();W()});var Te=i(()=>{"use strict";Y();nt();W();ne()});var Pe=i(()=>{"use strict";Y();$e();W();ne();Se();Te();W();Mt()});var mn=i(()=>{"use strict";Wt();$e();Pe();Se()});var Bs=i(()=>{"use strict";Y();dr();W();ne();Te();Se()});var hr=i(()=>{"use strict";Z()});var Ae=i(()=>{"use strict";Y();hr();W();ne();Te()});var Qi=i(()=>{"use strict"});var fr=i(()=>{"use strict"});var yr=i(()=>{"use strict";Te();Ae()});var qs=i(()=>{"use strict";W();Ae();fr();yr()});var rh=i(()=>{"use strict";$e();Mt();W();Pe();Qi();Ae();fr();qs();yr();yr();fr()});var ih=i(()=>{"use strict";rh();qs();fr();yr()});var br=i(()=>{"use strict";ih()});var oh=i(()=>{"use strict";Wt();W();ne();Te();Ae();Se();br()});var Sr=i(()=>{"use strict";ne();Ae();W();Se();br();oh()});var Js=i(()=>{"use strict";Y();W();ne();Te();Ae();Sr();wr();Se()});var wr=i(()=>{"use strict";W();ne();Te();Se();Js()});var Zi=i(()=>{"use strict";W();Pe();Se()});var ea=i(()=>{"use strict";W();$e()});var ta=i(()=>{"use strict";Y();dr();Wt();$e();W();mn();Bs();Sr();wr();Pe();Zi();ea()});var hn=i(()=>{"use strict";$e()});var ph=i(()=>{"use strict";dr();Wt();W();Mt();mn();Bs();Sr();wr();ta();Pe();hn()});var hh=i(()=>{"use strict";ph();Zi();ea();ta();mn();Pe()});var na=i(()=>{"use strict";Ae();br();ne()});var kr=i(()=>{"use strict";W()});var ra=i(()=>{"use strict";W();Mt();ne();Pe();mn();$e();kr()});var Qs=i(()=>{"use strict";W();Se();na();ra();kr()});var Xs=i(()=>{"use strict"});var gh=i(()=>{"use strict";hr();W();Ae();na();Qs();ra();kr();Xs();ne();Qi()});var oa=i(()=>{"use strict";gh();Qs();na();ra();kr();Xs()});var Vs=i(()=>{"use strict";_();qe();Y();hr();W();Ae();br();wr();Se();oa();ne();Te()});var bh=i(()=>{"use strict";_();Y();ye();qe();Ee();W();Te()});var Sh=i(()=>{"use strict";Vs();oa();ne()});var rd=i(()=>{"use strict";hh();Vs();oa();Mt();ne();Js();Sr();bh();Sh()});var xh=i(()=>{"use strict";rd()});var EE,Ih=i(()=>{"use strict";Ee();F();w();_();EE=10080*60*1e3});var Eh=i(()=>{"use strict"});var vh=i(()=>{"use strict";w();Ih();Eh()});var Rh=i(()=>{"use strict"});var Ch=i(()=>{"use strict";vh();Rh()});var ct=i(()=>{"use strict";xh();Ch();Wt()});var Je=i(()=>{"use strict"});var ut=i(()=>{"use strict";Je()});import{z as dd}from"zod";var Tr,ua,cd,f1,lt=i(()=>{"use strict";Je();Tr=1,ua=5,cd=`${JSON.stringify({formatVersion:Tr,schemaVersion:ua})}
|
|
639
|
+
`,f1=dd.object({formatVersion:dd.literal(Tr),schemaVersion:dd.number().int().positive().optional()})});var Oh=i(()=>{"use strict";y();ut();Je();lt()});var la=i(()=>{"use strict";y();Je();lt();ut()});var Nh=i(()=>{"use strict";Je()});var Dh=i(()=>{"use strict";y();Je();Nh();lt();ut()});var jh=i(()=>{"use strict";Oh();la();lt();Dh()});var Kh=i(()=>{"use strict";qe()});var zh=i(()=>{"use strict";Z()});var ga=i(()=>{"use strict"});var Ar=i(()=>{"use strict";To();Fn()});var hd=i(()=>{"use strict";y();ga();Ar()});var Qh=i(()=>{"use strict";Ar()});var Xh=i(()=>{"use strict";ga();Ar()});var fd=i(()=>{"use strict";Ar()});var Vh=i(()=>{"use strict";hd();Qh();Xh();fd();ga();Z()});var Yh=i(()=>{"use strict";hd();Vh();fd()});var Zh=i(()=>{"use strict";zh();Yh()});var ba=i(()=>{"use strict";Z();y();Zh();Le()});var mt=i(()=>{"use strict"});var $J,Lr=i(()=>{"use strict";y();w();Hn();mt();$J=new It(1)});var gd=i(()=>{"use strict";w();F();mt();Lr()});var Sa=i(()=>{"use strict";y();F()});var bd=i(()=>{"use strict";F();Lr();Sa()});var kd=i(()=>{"use strict";y();lt();Je();ut();la();mt();gd();bd();Lr()});var af=i(()=>{"use strict";mt();ut()});var xd=i(()=>{"use strict";y();F();Lr()});var Id=i(()=>{"use strict";y();F();la();lt();ut();mt();kd();af();gd();xd();bd();Sa()});var of=i(()=>{"use strict";F();Id();kd();xd();mt()});async function wa(t){let e=R().documentStore,n=0,r=0,a=0,o;try{o=await e.list()}catch(d){if(Fe(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 Ye(d);!t.force&&(c===void 0||t.now-c<$E)||(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 $E,sf=i(()=>{"use strict";y();pe();$E=3600*1e3});var df=i(()=>{"use strict";w();y();F();mt();Sa()});var vd=i(()=>{"use strict";of();Id();sf();df()});var Rd=i(()=>{"use strict";vd()});var cf=i(()=>{"use strict";_();ba();ct();Rd()});var Le=i(()=>{"use strict";jh();Kh();cf();Rd()});var Td,_d=i(()=>{"use strict";Td=["queued","running","canceling","paused","succeeded","failed","canceled"]});async function uf(){return await z(R().library,"jobs/work")}async function lf(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 Or=i(()=>{"use strict";y()});var Nr=i(()=>{"use strict";F()});var Pd=i(()=>{"use strict"});var Wr=i(()=>{"use strict";y()});var mf,pf=i(()=>{"use strict";mf=`
|
|
640
640
|
CREATE TABLE IF NOT EXISTS build_jobs (
|
|
641
641
|
job_id TEXT PRIMARY KEY,
|
|
642
642
|
archive_key TEXT NOT NULL,
|
|
@@ -695,7 +695,7 @@ CREATE TABLE IF NOT EXISTS build_worker_lease (
|
|
|
695
695
|
|
|
696
696
|
INSERT OR IGNORE INTO build_worker_lease (id)
|
|
697
697
|
VALUES (1);
|
|
698
|
-
`});function
|
|
698
|
+
`});function Ut(t){let e=VE(jt(t,"current_step"),"current_step"),n=jt(t,"owner_id"),r=t.owner_pid===null?void 0:ce(t,"owner_pid"),a=t.reading_summary_started_at===null?void 0:ce(t,"reading_summary_started_at"),o=t.finished_at===null?void 0:ce(t,"finished_at"),s=jt(t,"error_json"),d=t.input_revision===null?void 0:ce(t,"input_revision"),c=jt(t,"llm_json"),u=jt(t,"prompt");return{archiveKey:Oe(t,"archive_key"),archiveIdentity:Oe(t,"archive_path"),cacheLocator:Oe(t,"cache_path"),chapterId:ce(t,"chapter_id"),createdAt:ce(t,"created_at"),...e===void 0?{}:{currentStep:e},...s===void 0?{}:{errorJSON:s},eventsLocator:Oe(t,"events_path"),...o===void 0?{}:{finishedAt:o},jobId:Oe(t,"job_id"),...d===void 0?{}:{inputRevision:d},logLocator:Oe(t,"log_path"),...c===void 0?{}:{llmJSON:c},...n===void 0?{}:{ownerId:n},...r===void 0?{}:{ownerPid:r},...u===void 0?{}:{prompt:u},queueRank:ce(t,"queue_rank"),state:XE(Oe(t,"state")),...a===void 0?{}:{readingSummaryStartedAt:a},target:hf(Oe(t,"target"),"target"),updatedAt:ce(t,"updated_at"),workspaceLocator:Oe(t,"workspace_path")}}async function Mr(t){let e=A().resources,[n,r,a,o,s]=await Promise.all([e.getFile(t.archiveIdentity),Ad(t.cacheLocator),QE(t.eventsLocator),Ad(t.logLocator),Ad(t.workspaceLocator)]);if(n===void 0)throw Dr("archive");if(r===void 0)throw Dr("cache");if(a===void 0)throw Dr("events");if(o===void 0)throw Dr("log");if(s===void 0)throw Dr("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 Ad(t){return t.startsWith("jobs/")?await We(R().library,t)??zE(t):await A().resources.getDirectory(t)}function zE(t){let e=R().library,n=r=>`${t}/${r}`;return{createDirectory:async r=>await z(e,n(r)),createFile:async r=>await H(e,n(r)),getDirectory:async r=>await We(e,n(r)),getFile:async r=>await J(e,n(r)),getLastModified:async()=>await(await We(e,t))?.getLastModified?.(),identity:`managed:library:${t}`,kind:"directory",list:async()=>(await We(e,t))?.list()??[],name:t.split("/").at(-1)??t,remove:async(r,a)=>{await(await We(e,t))?.remove(r,a)}}}async function QE(t){return t.startsWith("jobs/")?await J(R().library,t):await A().resources.getFile(t)}function Dr(t){return new Error(`Build job ${t} resource is unavailable`)}function XE(t){if(Td.includes(t))return t;throw new Error(`Invalid build job state: ${t}`)}function hf(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 VE(t,e){return t===void 0?void 0:hf(t,e)}function Oe(t,e){let n=t[e];if(typeof n!="string")throw new TypeError(`Expected ${e} to be a string`);return n}function ce(t,e){let n=t[e];if(typeof n!="number")throw new TypeError(`Expected ${e} to be a number`);return n}function jt(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";_d();y()});async function bn(){let t=await X("jobs/job.sqlite",mf);try{return await t.run(`
|
|
699
699
|
UPDATE build_jobs
|
|
700
700
|
SET workspace_path = 'jobs/work/' || job_id,
|
|
701
701
|
cache_path = 'jobs/cache/' || job_id,
|
|
@@ -705,12 +705,12 @@ VALUES (1);
|
|
|
705
705
|
OR cache_path NOT LIKE 'jobs/cache/%'
|
|
706
706
|
OR log_path NOT LIKE 'jobs/logs/%'
|
|
707
707
|
OR events_path NOT LIKE 'jobs/events/%'
|
|
708
|
-
`),t}catch(e){throw await t.close().catch(()=>{}),e}}var
|
|
708
|
+
`),t}catch(e){throw await t.close().catch(()=>{}),e}}var Sn=i(()=>{"use strict";_();y();pf();Bt()});var ka=i(()=>{"use strict";Nr();Wr();Sn();Or()});var xa=i(()=>{"use strict";Bt();ka();Or()});var Ld=i(()=>{"use strict";F();Or();Nr();Pd();Wr();Sn();xa();ka();Ni();Bt()});var bf=i(()=>{"use strict";Nr();Sn();xa();Bt();Ni()});var Sf=i(()=>{"use strict";F();Nr();Pd();Wr();Sn();xa();ka();Ld();Bt()});function iv(t){return nv.has(t)}async function av(t,e){if((await e.list()).some(a=>!iv(a.name)))return 0;let r=await pt(e);return await t.remove(e.name,{recursive:!0}),r}async function wf(t){let e=0,n=0,r=0;for(let a of await t.list()){if(!U(a))continue;r+=1;let o=await Ye(a);if(o===void 0||Date.now()-o<rv)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 pt(t){return await Ie(t)}var nv,rv,Od=i(()=>{"use strict";y();nv=new Set([".DS_Store"]),rv=6e4});async function Ia(t){let e=await bn(),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=>ce(c,"count")),a=await e.queryAll(`
|
|
709
709
|
SELECT *
|
|
710
710
|
FROM build_jobs
|
|
711
711
|
WHERE state IN ('succeeded', 'failed', 'canceled')
|
|
712
712
|
AND updated_at <= ?
|
|
713
|
-
`,[n],
|
|
713
|
+
`,[n],Ut),o=await Promise.all(a.map(Mr)),s=t.dryRun?{freedBytes:0,removed:0,scanned:0}:await wf(await uf()),d=0;for(let c of o)d+=await pt(c.workspace),d+=await pt(c.cache),d+=await pt(c.log),d+=await pt(c.events),t.dryRun||(await lf(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 kf=i(()=>{"use strict";Od();Or();Sn();Bt()});var Kd=i(()=>{"use strict";_d();Ld();bf();Sf();Wr();kf()});async function Ef(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 sv();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 sp(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 sv(){let t=await X("core.sqlite","");try{return await t.queryAll("SELECT id FROM libraries",void 0,e=>S(e,"id"))}catch{return}finally{await t.close()}}var wn=i(()=>{"use strict";F();y();w();or();_();Le();Mt();hn();Dt();kn();Lt();_t();Z()});var vf=i(()=>{"use strict"});var dv,rV,kn=i(()=>{"use strict";y();w();_();qe();Le();Le();Kd();ct();Ee();F();Lt();wn();_t();vf();dv=`
|
|
714
714
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
715
715
|
library_id INTEGER NOT NULL,
|
|
716
716
|
public_id TEXT NOT NULL,
|
|
@@ -723,9 +723,9 @@ WHERE state IN ('succeeded', 'failed', 'canceled')
|
|
|
723
723
|
created_at TEXT NOT NULL,
|
|
724
724
|
updated_at TEXT NOT NULL,
|
|
725
725
|
UNIQUE(library_id, public_id)
|
|
726
|
-
`,
|
|
726
|
+
`,rV=`
|
|
727
727
|
CREATE TABLE IF NOT EXISTS library_archives (
|
|
728
|
-
${
|
|
728
|
+
${dv}
|
|
729
729
|
);
|
|
730
730
|
|
|
731
731
|
CREATE INDEX IF NOT EXISTS idx_library_archives_library
|
|
@@ -733,14 +733,14 @@ ${tR}
|
|
|
733
733
|
|
|
734
734
|
CREATE INDEX IF NOT EXISTS idx_library_archives_library_path
|
|
735
735
|
ON library_archives(library_id, relative_path);
|
|
736
|
-
`});var
|
|
737
|
-
prev: ${
|
|
738
|
-
text: ${
|
|
739
|
-
next: ${
|
|
736
|
+
`});var _f=i(()=>{"use strict";ct();kn();_t();wn();Lt()});var zd=i(()=>{"use strict";Le();kn();Lt()});var Lf=i(()=>{"use strict";Gi();Bi();dr();ea();Zi();mn();Pe();ta();Wt();hn();wn();zd()});var Of=i(()=>{"use strict";rd();Qi();Bi();ji();Lf();Pe();kn();zd();Lt();wn();_t()});var Ca=i(()=>{"use strict";Lt();_f();kn();Of();wn();_t()});function Ta(t){let e=t.trim();return e===""?[]:Array.from(wv.segment(e)).map(n=>n.segment.trim()).filter(n=>n!=="")}function ke(t){let e=t.replace(/\s+/gu," ").trim(),n=kv(e),r="";for(let a of n)if(!xv(a)){if(!Gr(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&&Sv.has(e[e.length-1]??"")&&Gr(e[e.length-2]??"")&&n<t.length-1&&Gr(t[n+1]??"")){e.pop(),n+=1;continue}let a=e[e.length-1]??"",o=t[n+1]??"";a!==""&&o!==""&&Gr(a)&&Gr(o)&&e.push(r),n+=1}return e}function Gr(t){return t!==""&&new RegExp("\\p{Script=Latin}","u").test(t)&&new RegExp("\\p{L}","u").test(t)}function xv(t){return/[\p{P}\p{S}]/u.test(t)}var Sv,wv,jr=i(()=>{"use strict";Sv=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),wv=new Intl.Segmenter(void 0,{granularity:"sentence"})});function Xd(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function Wf(t,e){let n=_a(t,2),r=_a(e,2),a=_a(t,3),o=_a(e,3);return(Nf(n,r)+Nf(a,o))/2}function _a(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 Nf(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 Df(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 Mf(t,e){return 1-Math.abs(t.length-e.length)/Math.max(t.length,e.length)}function Ff(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 Gf(t){return` - ${t.occurrenceId} score=${t.score.toFixed(3)}
|
|
737
|
+
prev: ${Qd(t.prevText)}
|
|
738
|
+
text: ${Qd(t.text,120)}
|
|
739
|
+
next: ${Qd(t.nextText)}`}function Qd(t,e=80){let n=t.replace(/\s+/gu," ").trim();return n===""?"(none)":n.length<=e?n:`${n.slice(0,e-3)}...`}var Vd=i(()=>{"use strict"});var Yd=i(()=>{"use strict"});function Uf(t,e,n){return t.mode==="head_tail"?vv(t,e):Zd(t.text??"",e,n)}function vv(t,e){let n=t.head??"",r=t.tail??"",a=ke(e),o=ke(n),s=ke(r);if(o===""||s==="")return Xd();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=Zd(n,e,"start_anchor"),m=Zd(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 Zd(t,e,n){let r=t.trim(),a=e.trim(),o=ke(r),s=ke(a);if(o===""||s==="")return Xd();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=jf({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,K=[...v].filter(ie=>C.has(ie)).length;if((L===0?0:K/L)<.35)continue;let j=.35*Wf(o,g)+.35*Ff(o,g)+.2*Df(o,g)+.1*Mf(o,g)+jf({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 jf(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 Bf=i(()=>{"use strict";jr();Vd();Yd()});function qf(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 Hf(t,e){if(t===void 0)return;if(t.mode==="head_tail"){let r=e==="end_anchor"?ec(t.tail??"","end_anchor"):ec(t.head??"","start_anchor");return r===""?void 0:{mode:"full",text:r}}return{mode:"full",text:ec(t.text??"",e)}}function tc(t){return t.mode==="head_tail"?ke(t.head??"").length+ke(t.tail??"").length:ke(t.text??"").length}function ec(t,e){let n=Ta(t);return n.length<=1?t.trim():e==="end_anchor"?n[n.length-1]??t.trim():n[0]??t.trim()}var $f=i(()=>{"use strict";jr()});var qt,Qf=i(()=>{"use strict";Bf();$f();Vd();Yd();qt=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]=qf(e);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:n,message:`Invalid evidence.${n}: ${a}`}]:[Hf(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&&tc(e.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&tc(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=Uf(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=>Gf(s)).join(`
|
|
740
740
|
`);return{candidates:a,code:n,fieldName:e,message:`${e} is ambiguous. Top candidates:
|
|
741
741
|
${o}
|
|
742
|
-
Please provide a more specific anchor or surrounding context.`}}}});var
|
|
743
|
-
`)});var
|
|
742
|
+
Please provide a more specific anchor or surrounding context.`}}}});var Xf=i(()=>{"use strict"});var Vf=i(()=>{"use strict";Qf();Xf()});var Pa,Yf=i(()=>{"use strict";Pa=["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(`
|
|
743
|
+
`)});var nc=i(()=>{"use strict"});var Zf=i(()=>{"use strict";nc();jr()});var In=i(()=>{"use strict";Vf();Yf();nc();Zf();jr()});import{z as Ur}from"zod";var PY,ty=i(()=>{"use strict";PY=Ur.object({meanings:Ur.array(Ur.object({information:Ur.string(),qid:Ur.string().regex(/^Q[1-9][0-9]*$/u)}).strict())}).strict()});var ny=i(()=>{"use strict"});var La=i(()=>{"use strict"});var WY,ay=i(()=>{"use strict";La();WY=336*60*60*1e3});var oy=i(()=>{"use strict";La()});var sy=i(()=>{"use strict";ty();ny();ay();La();oy()});async function ic(t){let e=await Br.open();try{return await e.gc(t)}finally{await e.close()}}function jv(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 Uv(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 Fv,Gv,Br,dy=i(()=>{"use strict";sy();_();Fv=`
|
|
744
744
|
CREATE TABLE IF NOT EXISTS wikimedia_qid_cache_v2 (
|
|
745
745
|
qid TEXT PRIMARY KEY,
|
|
746
746
|
record_json TEXT NOT NULL,
|
|
@@ -758,39 +758,39 @@ CREATE TABLE IF NOT EXISTS wikimedia_disambiguation_cache_v2 (
|
|
|
758
758
|
record_json TEXT NOT NULL,
|
|
759
759
|
PRIMARY KEY(qid,wiki,page_id,revision_id,normalizer_version,model_id)
|
|
760
760
|
);
|
|
761
|
-
`,
|
|
762
|
-
WHERE qid IN (${e.map(()=>"?").join(",")})`,e,o=>String(o.record_json)),a=new Map;for(let o of r){let s=
|
|
761
|
+
`,Gv=336*60*60*1e3,Br=class t{#e;constructor(e){this.#e=e}static async open(){return new t(await X("cache/cache.sqlite",Fv))}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
|
|
762
|
+
WHERE qid IN (${e.map(()=>"?").join(",")})`,e,o=>String(o.record_json)),a=new Map;for(let o of r){let s=jv(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
763
|
VALUES(?,?,?)
|
|
764
764
|
ON CONFLICT(qid) DO UPDATE SET
|
|
765
765
|
record_json=excluded.record_json,
|
|
766
766
|
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
767
|
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=
|
|
768
|
+
AND (${a.join(" OR ")})`,[n.normalizerVersion,n.modelId,...o],d=>String(d.record_json))).flatMap(d=>{let c=Uv(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
769
|
qid,wiki,page_id,revision_id,normalizer_version,model_id,record_json
|
|
770
770
|
) VALUES(?,?,?,?,?,?,?)
|
|
771
771
|
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-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 Zd=i(()=>{"use strict";ny()});var ec=i(()=>{"use strict"});var tc=i(()=>{"use strict"});import{jsonrepair as MY}from"jsonrepair";var ry=i(()=>{"use strict"});var iy=i(()=>{"use strict";tc();ec();ry()});var Ne=i(()=>{"use strict";ec();tc();iy()});var Ur=i(()=>{"use strict"});import{z as $e}from"zod";var GR,jR,d2,ic=i(()=>{"use strict";Ne();Ur();GR=$e.object({candidateId:$e.string().min(1),decision:$e.enum(["continue","recall","skip_this_time","never_recall"]),qid:$e.string().nullable().optional()}).strict(),jR=$e.object({decisions:$e.array(GR),groupId:$e.string().min(1)}).strict(),d2=$e.object({groups:$e.array(jR)}).strict()});import{z as Br}from"zod";var qR,h2,sy=i(()=>{"use strict";Ne();Ur();ic();qR=Br.object({decision:Br.enum(["keep","reject"]),qid:Br.string().regex(/^Q[1-9][0-9]*$/)}).strict(),h2=Br.object({qids:Br.array(qR)}).strict()});var dy=i(()=>{"use strict"});import{z as qr}from"zod";var HR,S2,cy=i(()=>{"use strict";Ne();HR=qr.object({note:qr.string().max(24).optional(),surfaceId:qr.string().min(1)}).strict(),S2=qr.object({protectedSurfaces:qr.array(HR)}).strict()});var ac=i(()=>{"use strict"});var uy=i(()=>{"use strict";ac()});var ly=i(()=>{"use strict"});var oc=i(()=>{"use strict"});var my=i(()=>{"use strict";oc();Ur()});var mt=i(()=>{"use strict";ic();sy();Ur();dy();cy();uy();ac();ly();my();oc()});var X2,dc=i(()=>{"use strict";en();X2=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 cc=i(()=>{"use strict";Ve()});var gy=i(()=>{"use strict";cc()});var by=i(()=>{"use strict";gy();cc()});var Sy=i(()=>{"use strict"});var wy=i(()=>{"use strict"});var ky=i(()=>{"use strict";Sy();wy()});var Hr=i(()=>{"use strict";Ne()});var xy=i(()=>{"use strict";_();Hr()});var Iy=i(()=>{"use strict";Hr()});var Ey=i(()=>{"use strict"});import{z as x}from"zod";var Ry,iv,vy,av,ov,sv,dv,cv,uv,va=i(()=>{"use strict";_();Ry=x.object({from:x.union([x.number().int(),x.string()]),strength:x.string().optional(),to:x.union([x.number().int(),x.string()])}),iv=x.object({quote:x.string().optional(),sentence_id:x.string().optional()}).passthrough(),vy=x.union([x.record(x.string(),x.unknown()),x.array(iv)]),av=x.object({content:x.string(),evidence:vy.nullish(),label:x.string(),retention:x.enum(["verbatim","detailed","focused","relevant"]),temp_id:x.string()}).passthrough(),ov=x.object({chunks:x.array(av),fragment_summary:x.string(),links:x.array(Ry)}),sv=x.object({content:x.string(),evidence:vy.nullish(),importance:x.enum(["critical","important","helpful"]),label:x.string(),temp_id:x.string()}).passthrough(),dv=x.object({chunk_id:x.number().int(),importance:x.enum(["critical","important","helpful"])}),cv=x.object({chunks:x.array(sv),importance_annotations:x.array(dv),links:x.array(Ry)}),uv=x.object({choice:x.string()})});var Cy=i(()=>{"use strict";Ne();Sn();Ey();Hr();va()});var Ty=i(()=>{"use strict";Ne();_();xy();Hr();Iy();Cy();va()});var _y=i(()=>{"use strict";Ty();va()});var Ca=i(()=>{"use strict"});import{detect as o8,validateISO2 as s8}from"tinyld";var uc=i(()=>{"use strict";Me()});var Py=i(()=>{"use strict";uc();Me()});var Ay=i(()=>{"use strict"});import{z as $r}from"zod";var fv,_8,Oy=i(()=>{"use strict";Ne();Sn();_y();Ca();Ca();Py();Ay();fv=$r.object({content:$r.string(),id:$r.number(),label:$r.string()}),_8=$r.array(fv)});var lc=i(()=>{"use strict";Oy()});var Ny=i(()=>{"use strict";Ze()});var mc=i(()=>{"use strict";Ny()});var Wy=i(()=>{"use strict";ky();lc();mc()});var Ta=i(()=>{"use strict";Wy();mc()});var _a=i(()=>{"use strict"});var Pa=i(()=>{"use strict";Ta();_a()});var Dy=i(()=>{"use strict";Pa()});var My=i(()=>{"use strict"});var Aa=i(()=>{"use strict"});var Fy=i(()=>{"use strict";Aa()});var kn,a5,kv,La=i(()=>{"use strict";Eo();kn=(r=>(r.Critical="critical",r.Major="major",r.Minor="minor",r))(kn||{}),a5=nn(kn),kv=$n(kn,"review severity")});var u5,hc=i(()=>{"use strict";Aa();La();u5=Object.freeze({critical:9,major:3,minor:1})});var Gy=i(()=>{"use strict";uc();Me();La()});var jy=i(()=>{"use strict";y();Ve();hc()});var fc=i(()=>{"use strict";_()});var Uy=i(()=>{"use strict"});import{z as xn}from"zod";var xv,Iv,N5,By=i(()=>{"use strict";Ve();Ne();Aa();fc();La();xv=["critical","major","minor"],Iv=xn.object({problem:xn.string(),severity:xn.enum(xv),suggestion:xn.string().default("")}),N5=xn.object({issues:xn.array(Iv)})});var qy=i(()=>{"use strict";My();Fy();hc();Gy();jy();fc();Uy();By()});var yc=i(()=>{"use strict";qy()});var $y=i(()=>{"use strict"});var Jy=i(()=>{"use strict"});var Ky=i(()=>{"use strict";$y();Jy()});var Jr=i(()=>{"use strict"});var h4,f4,In=i(()=>{"use strict";_();h4={critical:9,helpful:1,important:3},f4={detailed:9,focused:3,relevant:1,verbatim:27}});var En=i(()=>{"use strict"});var Kr=i(()=>{"use strict"});var gc=i(()=>{"use strict";En()});var bc=i(()=>{"use strict";In();En();Jr();Kr();gc()});var Sc=i(()=>{"use strict";Jr();bc();Kr()});var Qy=i(()=>{"use strict";In();En();Kr()});var Xy=i(()=>{"use strict";In();En();Jr();Kr();gc()});var Vy=i(()=>{"use strict";Sc();En();Jr();Qy();bc();Xy()});var Yy=i(()=>{"use strict";Vy();Sc()});var Zy=i(()=>{"use strict";In()});var eg=i(()=>{"use strict";Yy();Zy()});var tg=i(()=>{"use strict";Ky();eg();In()});var ng=i(()=>{"use strict";tg()});var wc=i(()=>{"use strict";Z()});var rg=i(()=>{"use strict"});var kc=i(()=>{"use strict";Pa()});var Na=i(()=>{"use strict"});var ig=i(()=>{"use strict";jn();en();yc();Ta();ng();Pa();_a();wc();rg();kc();Na()});var ag=i(()=>{"use strict";wc();Na();Z()});var og=i(()=>{"use strict";Dy();ig();_a();ag();kc();Na()});var Rn=i(()=>{"use strict";og()});var sg=i(()=>{"use strict";ye();jn();Rn();Et()});var dg=i(()=>{"use strict";Et();Et();_();ye();by();Rn();sg();la();y()});var Ec,pt=i(()=>{"use strict";Ec=["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 Rc=i(()=>{"use strict";pt()});var lg=i(()=>{"use strict";Ve();bo();dg();dc();Le();Rc();y()});var Wa=i(()=>{"use strict"});import{z as p}from"zod";var mg,V,Wv,Dv,pg,Mv,Fv,Gv,jv,Uv,Bv,qv,Hv,$v,Jv,Kv,zv,Qv,Xv,n9,vn=i(()=>{"use strict";y();Ce();Wa();mg=1,V=p.number().int().nonnegative(),Wv=p.literal(mg),Dv=p.string().regex(/^Q[1-9][0-9]*$/u),pg=p.number().min(0).max(1).optional(),Mv=p.object({text:p.string(),wordsCount:V}).strict(),Fv=p.object({type:p.literal("meta"),schemaVersion:Wv,chapterId:p.number().int(),stream:p.enum(["knowledge-graph","reading-graph","summary"])}).strict(),Gv=p.object({type:p.literal("parameter"),scope:p.enum(["knowledge-graph","reading-graph","summary"]),language:p.string().optional(),prompt:p.string()}).strict(),jv=p.object({type:p.literal("source-fragment"),fragmentId:V,summary:p.string(),sentences:p.array(Mv)}).strict(),Uv=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(),Bv=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(),qv=p.object({type:p.literal("fragment-group"),groupId:V,startSentenceIndex:V,endSentenceIndex:V}).strict(),Hv=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(),$v=p.object({type:p.literal("snake-chunk"),snakeId:p.string().min(1),chunkId:p.string().min(1),position:V}).strict(),Jv=p.object({type:p.literal("snake-edge"),fromSnakeId:p.string().min(1),toSnakeId:p.string().min(1),weight:p.number()}).strict(),Kv=p.object({type:p.literal("summary"),text:p.string()}).strict(),zv=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:Dv,confidence:pg,note:p.string().optional()}).strict(),Qv=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:pg,note:p.string().optional()}).strict(),Xv=p.object({type:p.literal("end")}).strict(),n9=p.discriminatedUnion("type",[Fv,Gv,jv,Uv,Bv,qv,Hv,$v,Jv,Kv,zv,Qv,Xv])});var hg=i(()=>{"use strict"});var fg=i(()=>{"use strict"});import{sha256 as s9}from"@noble/hashes/sha2.js";var d9,c9,vc=i(()=>{"use strict";d9=new RegExp("\\p{Script=Han}+","gu"),c9=new RegExp("^\\p{Script=Han}+$","u")});var Cc=i(()=>{"use strict";vc()});import{z as l}from"zod";function yg(){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:P,sentenceIndexes:l.array(P),type:l.literal("reading-chunk"),weight:l.number(),wordsCount:P})}function gg(){return l.object({fromChunkId:l.string(),strength:l.string().optional(),toChunkId:l.string(),type:l.literal("reading-edge"),weight:l.number()})}function bg(){return l.object({endSentenceIndex:P,groupId:P,startSentenceIndex:P,type:l.literal("fragment-group")})}function Sg(){return l.object({firstLabel:l.string(),groupId:P,id:l.string(),lastLabel:l.string(),localSnakeId:P,size:P,type:l.literal("snake"),weight:l.number(),wordsCount:P})}function wg(){return l.object({chunkId:l.string(),position:P,snakeId:l.string(),type:l.literal("snake-chunk")})}function kg(){return l.object({fromSnakeId:l.string(),toSnakeId:l.string(),type:l.literal("snake-edge"),weight:l.number()})}function xg(){return l.object({confidence:l.number().optional(),fragmentId:P.optional(),id:l.string(),note:l.string().optional(),qid:l.string(),rangeEnd:P,rangeStart:P,sentenceIndex:P.optional(),surface:l.string(),type:l.literal("mention")})}function Vv(){return l.object({confidence:l.number().optional(),evidenceSentenceIndexes:l.array(P),id:l.string(),note:l.string().optional(),predicate:l.string(),sourceMentionId:l.string(),targetMentionId:l.string(),type:l.literal("mention-link")})}var P,Tc,f9,y9,Ht=i(()=>{"use strict";P=l.number().int().nonnegative(),Tc={sentenceIndex:P,text:l.string(),wordsCount:P},f9=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string().optional(),type:l.literal("job-options")}),l.object({...Tc,fragmentId:P.optional(),type:l.literal("source-text")}),l.object({fragmentId:P,summary:l.string(),type:l.literal("source-fragment")}),l.object({...Tc,fragmentId:P.optional(),type:l.literal("source-sentence")}),l.object({...Tc,type:l.literal("summary-sentence")}),l.object({chapterId:l.number().int(),title:l.string(),type:l.literal("chapter-title")}),yg(),gg(),bg(),Sg(),wg(),kg(),xg()]),y9=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string(),scope:l.enum(["knowledge-graph","reading-graph"]),type:l.literal("job-parameter")}),yg(),gg(),bg(),Sg(),wg(),kg(),xg(),Vv(),l.object({position:P,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:P.optional(),text:l.string(),tokens:l.array(l.string()),type:l.literal("lexical-row")}),l.object({dimensions:P,identity:l.string().optional(),model:l.string(),source:l.enum(["source","summary"]),type:l.literal("embedding-metadata"),version:l.literal(1)}),l.object({endSentenceIndex:P,segmentIndex:P,startSentenceIndex:P,text:l.string(),type:l.literal("embedding-segment"),vector:l.array(l.number()),wordsCount:P})])});var _c=i(()=>{"use strict";Ht()});var Pc=i(()=>{"use strict"});var $t,Ac=i(()=>{"use strict";$t=["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: ${
|
|
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-Gv).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 oc=i(()=>{"use strict";dy()});var sc=i(()=>{"use strict"});var dc=i(()=>{"use strict"});import{jsonrepair as t2}from"jsonrepair";var cy=i(()=>{"use strict"});var uy=i(()=>{"use strict";dc();sc();cy()});var Ne=i(()=>{"use strict";sc();dc();uy()});var qr=i(()=>{"use strict"});import{z as ze}from"zod";var Jv,Kv,R2,lc=i(()=>{"use strict";Ne();qr();Jv=ze.object({candidateId:ze.string().min(1),decision:ze.enum(["continue","recall","skip_this_time","never_recall"]),qid:ze.string().nullable().optional()}).strict(),Kv=ze.object({decisions:ze.array(Jv),groupId:ze.string().min(1)}).strict(),R2=ze.object({groups:ze.array(Kv)}).strict()});import{z as Hr}from"zod";var Xv,L2,py=i(()=>{"use strict";Ne();qr();lc();Xv=Hr.object({decision:Hr.enum(["keep","reject"]),qid:Hr.string().regex(/^Q[1-9][0-9]*$/)}).strict(),L2=Hr.object({qids:Hr.array(Xv)}).strict()});var hy=i(()=>{"use strict"});import{z as $r}from"zod";var Vv,M2,fy=i(()=>{"use strict";Ne();Vv=$r.object({note:$r.string().max(24).optional(),surfaceId:$r.string().min(1)}).strict(),M2=$r.object({protectedSurfaces:$r.array(Vv)}).strict()});var mc=i(()=>{"use strict"});var yy=i(()=>{"use strict";mc()});var gy=i(()=>{"use strict"});var pc=i(()=>{"use strict"});var by=i(()=>{"use strict";pc();qr()});var ft=i(()=>{"use strict";lc();py();qr();hy();fy();yy();mc();gy();by();pc()});var h3,fc=i(()=>{"use strict";tn();h3=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 yc=i(()=>{"use strict";et()});var Iy=i(()=>{"use strict";yc()});var Ey=i(()=>{"use strict";Iy();yc()});var vy=i(()=>{"use strict"});var Ry=i(()=>{"use strict"});var Cy=i(()=>{"use strict";vy();Ry()});var Jr=i(()=>{"use strict";Ne()});var Ty=i(()=>{"use strict";_();Jr()});var _y=i(()=>{"use strict";Jr()});var Py=i(()=>{"use strict"});import{z as x}from"zod";var Ay,lR,Ly,mR,pR,hR,fR,yR,gR,Oa=i(()=>{"use strict";_();Ay=x.object({from:x.union([x.number().int(),x.string()]),strength:x.string().optional(),to:x.union([x.number().int(),x.string()])}),lR=x.object({quote:x.string().optional(),sentence_id:x.string().optional()}).passthrough(),Ly=x.union([x.record(x.string(),x.unknown()),x.array(lR)]),mR=x.object({content:x.string(),evidence:Ly.nullish(),label:x.string(),retention:x.enum(["verbatim","detailed","focused","relevant"]),temp_id:x.string()}).passthrough(),pR=x.object({chunks:x.array(mR),fragment_summary:x.string(),links:x.array(Ay)}),hR=x.object({content:x.string(),evidence:Ly.nullish(),importance:x.enum(["critical","important","helpful"]),label:x.string(),temp_id:x.string()}).passthrough(),fR=x.object({chunk_id:x.number().int(),importance:x.enum(["critical","important","helpful"])}),yR=x.object({chunks:x.array(hR),importance_annotations:x.array(fR),links:x.array(Ay)}),gR=x.object({choice:x.string()})});var Oy=i(()=>{"use strict";Ne();In();Py();Jr();Oa()});var Ny=i(()=>{"use strict";Ne();_();Ty();Jr();_y();Oy();Oa()});var Wy=i(()=>{"use strict";Ny();Oa()});var Na=i(()=>{"use strict"});import{detect as E8,validateISO2 as v8}from"tinyld";var gc=i(()=>{"use strict";Me()});var Dy=i(()=>{"use strict";gc();Me()});var My=i(()=>{"use strict"});import{z as Kr}from"zod";var xR,K8,Gy=i(()=>{"use strict";Ne();In();Wy();Na();Na();Dy();My();xR=Kr.object({content:Kr.string(),id:Kr.number(),label:Kr.string()}),K8=Kr.array(xR)});var bc=i(()=>{"use strict";Gy()});var jy=i(()=>{"use strict";nt()});var Sc=i(()=>{"use strict";jy()});var Uy=i(()=>{"use strict";Cy();bc();Sc()});var Wa=i(()=>{"use strict";Uy();Sc()});var Da=i(()=>{"use strict"});var Ma=i(()=>{"use strict";Wa();Da()});var By=i(()=>{"use strict";Ma()});var qy=i(()=>{"use strict"});var Fa=i(()=>{"use strict"});var Hy=i(()=>{"use strict";Fa()});var vn,I5,TR,Ga=i(()=>{"use strict";Lo();vn=(r=>(r.Critical="critical",r.Major="major",r.Minor="minor",r))(vn||{}),I5=rn(vn),TR=Qn(vn,"review severity")});var T5,kc=i(()=>{"use strict";Fa();Ga();T5=Object.freeze({critical:9,major:3,minor:1})});var $y=i(()=>{"use strict";gc();Me();Ga()});var Jy=i(()=>{"use strict";y();et();kc()});var xc=i(()=>{"use strict";_()});var Ky=i(()=>{"use strict"});import{z as Rn}from"zod";var _R,PR,Y5,zy=i(()=>{"use strict";et();Ne();Fa();xc();Ga();_R=["critical","major","minor"],PR=Rn.object({problem:Rn.string(),severity:Rn.enum(_R),suggestion:Rn.string().default("")}),Y5=Rn.object({issues:Rn.array(PR)})});var Qy=i(()=>{"use strict";qy();Hy();kc();$y();Jy();xc();Ky();zy()});var Ic=i(()=>{"use strict";Qy()});var Vy=i(()=>{"use strict"});var Yy=i(()=>{"use strict"});var Zy=i(()=>{"use strict";Vy();Yy()});var zr=i(()=>{"use strict"});var L4,O4,Cn=i(()=>{"use strict";_();L4={critical:9,helpful:1,important:3},O4={detailed:9,focused:3,relevant:1,verbatim:27}});var Tn=i(()=>{"use strict"});var Qr=i(()=>{"use strict"});var Ec=i(()=>{"use strict";Tn()});var vc=i(()=>{"use strict";Cn();Tn();zr();Qr();Ec()});var Rc=i(()=>{"use strict";zr();vc();Qr()});var tg=i(()=>{"use strict";Cn();Tn();Qr()});var ng=i(()=>{"use strict";Cn();Tn();zr();Qr();Ec()});var rg=i(()=>{"use strict";Rc();Tn();zr();tg();vc();ng()});var ig=i(()=>{"use strict";rg();Rc()});var ag=i(()=>{"use strict";Cn()});var og=i(()=>{"use strict";ig();ag()});var sg=i(()=>{"use strict";Zy();og();Cn()});var dg=i(()=>{"use strict";sg()});var Cc=i(()=>{"use strict";Z()});var cg=i(()=>{"use strict"});var Tc=i(()=>{"use strict";Ma()});var Ua=i(()=>{"use strict"});var ug=i(()=>{"use strict";Hn();tn();Ic();Wa();dg();Ma();Da();Cc();cg();Tc();Ua()});var lg=i(()=>{"use strict";Cc();Ua();Z()});var mg=i(()=>{"use strict";By();ug();Da();lg();Tc();Ua()});var _n=i(()=>{"use strict";mg()});var pg=i(()=>{"use strict";ye();Hn();_n();at()});var hg=i(()=>{"use strict";at();at();_();ye();Ey();_n();pg();ba();y()});var Ac,yt=i(()=>{"use strict";Ac=["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 Lc=i(()=>{"use strict";yt()});var gg=i(()=>{"use strict";et();Ro();hg();fc();Le();Lc();y()});var Ba=i(()=>{"use strict"});import{z as p}from"zod";var bg,V,BR,qR,Sg,HR,$R,JR,KR,zR,QR,XR,VR,YR,ZR,eC,tC,nC,rC,w9,Pn=i(()=>{"use strict";y();Re();Ba();bg=1,V=p.number().int().nonnegative(),BR=p.literal(bg),qR=p.string().regex(/^Q[1-9][0-9]*$/u),Sg=p.number().min(0).max(1).optional(),HR=p.object({text:p.string(),wordsCount:V}).strict(),$R=p.object({type:p.literal("meta"),schemaVersion:BR,chapterId:p.number().int(),stream:p.enum(["knowledge-graph","reading-graph","summary"])}).strict(),JR=p.object({type:p.literal("parameter"),scope:p.enum(["knowledge-graph","reading-graph","summary"]),language:p.string().optional(),prompt:p.string()}).strict(),KR=p.object({type:p.literal("source-fragment"),fragmentId:V,summary:p.string(),sentences:p.array(HR)}).strict(),zR=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(),QR=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(),XR=p.object({type:p.literal("fragment-group"),groupId:V,startSentenceIndex:V,endSentenceIndex:V}).strict(),VR=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(),YR=p.object({type:p.literal("snake-chunk"),snakeId:p.string().min(1),chunkId:p.string().min(1),position:V}).strict(),ZR=p.object({type:p.literal("snake-edge"),fromSnakeId:p.string().min(1),toSnakeId:p.string().min(1),weight:p.number()}).strict(),eC=p.object({type:p.literal("summary"),text:p.string()}).strict(),tC=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:Sg,note:p.string().optional()}).strict(),nC=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:Sg,note:p.string().optional()}).strict(),rC=p.object({type:p.literal("end")}).strict(),w9=p.discriminatedUnion("type",[$R,JR,KR,zR,QR,XR,VR,YR,ZR,eC,tC,nC,rC])});var wg=i(()=>{"use strict"});var kg=i(()=>{"use strict"});import{sha256 as v9}from"@noble/hashes/sha2.js";var R9,C9,Oc=i(()=>{"use strict";R9=new RegExp("\\p{Script=Han}+","gu"),C9=new RegExp("^\\p{Script=Han}+$","u")});var Nc=i(()=>{"use strict";Oc()});import{z as l}from"zod";function xg(){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:P,sentenceIndexes:l.array(P),type:l.literal("reading-chunk"),weight:l.number(),wordsCount:P})}function Ig(){return l.object({fromChunkId:l.string(),strength:l.string().optional(),toChunkId:l.string(),type:l.literal("reading-edge"),weight:l.number()})}function Eg(){return l.object({endSentenceIndex:P,groupId:P,startSentenceIndex:P,type:l.literal("fragment-group")})}function vg(){return l.object({firstLabel:l.string(),groupId:P,id:l.string(),lastLabel:l.string(),localSnakeId:P,size:P,type:l.literal("snake"),weight:l.number(),wordsCount:P})}function Rg(){return l.object({chunkId:l.string(),position:P,snakeId:l.string(),type:l.literal("snake-chunk")})}function Cg(){return l.object({fromSnakeId:l.string(),toSnakeId:l.string(),type:l.literal("snake-edge"),weight:l.number()})}function Tg(){return l.object({confidence:l.number().optional(),fragmentId:P.optional(),id:l.string(),note:l.string().optional(),qid:l.string(),rangeEnd:P,rangeStart:P,sentenceIndex:P.optional(),surface:l.string(),type:l.literal("mention")})}function iC(){return l.object({confidence:l.number().optional(),evidenceSentenceIndexes:l.array(P),id:l.string(),note:l.string().optional(),predicate:l.string(),sourceMentionId:l.string(),targetMentionId:l.string(),type:l.literal("mention-link")})}var P,Wc,O9,N9,$t=i(()=>{"use strict";P=l.number().int().nonnegative(),Wc={sentenceIndex:P,text:l.string(),wordsCount:P},O9=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string().optional(),type:l.literal("job-options")}),l.object({...Wc,fragmentId:P.optional(),type:l.literal("source-text")}),l.object({fragmentId:P,summary:l.string(),type:l.literal("source-fragment")}),l.object({...Wc,fragmentId:P.optional(),type:l.literal("source-sentence")}),l.object({...Wc,type:l.literal("summary-sentence")}),l.object({chapterId:l.number().int(),title:l.string(),type:l.literal("chapter-title")}),xg(),Ig(),Eg(),vg(),Rg(),Cg(),Tg()]),N9=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string(),scope:l.enum(["knowledge-graph","reading-graph"]),type:l.literal("job-parameter")}),xg(),Ig(),Eg(),vg(),Rg(),Cg(),Tg(),iC(),l.object({position:P,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:P.optional(),text:l.string(),tokens:l.array(l.string()),type:l.literal("lexical-row")}),l.object({dimensions:P,identity:l.string().optional(),model:l.string(),source:l.enum(["source","summary"]),type:l.literal("embedding-metadata"),version:l.literal(1)}),l.object({endSentenceIndex:P,segmentIndex:P,startSentenceIndex:P,text:l.string(),type:l.literal("embedding-segment"),vector:l.array(l.number()),wordsCount:P})])});var Dc=i(()=>{"use strict";$t()});var Mc=i(()=>{"use strict"});var Jt,Fc=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 U9}from"jsonrepair";var _g=i(()=>{"use strict"});var Pg=i(()=>{"use strict";Fc();Mc();_g()});var le=i(()=>{"use strict";Mc();Fc();Pg()});var Og=i(()=>{"use strict"});var Xr=i(()=>{"use strict"});import{z as Xe}from"zod";var dC,cC,p7,jc=i(()=>{"use strict";le();Xr();dC=Xe.object({candidateId:Xe.string().min(1),decision:Xe.enum(["continue","recall","skip_this_time","never_recall"]),qid:Xe.string().nullable().optional()}).strict(),cC=Xe.object({decisions:Xe.array(dC),groupId:Xe.string().min(1)}).strict(),p7=Xe.object({groups:Xe.array(cC)}).strict()});import{z as Vr}from"zod";var lC,k7,Wg=i(()=>{"use strict";le();Xr();jc();lC=Vr.object({decision:Vr.enum(["keep","reject"]),qid:Vr.string().regex(/^Q[1-9][0-9]*$/)}).strict(),k7=Vr.object({qids:Vr.array(lC)}).strict()});var Uc=i(()=>{"use strict"});import{z as Yr}from"zod";var mC,R7,Dg=i(()=>{"use strict";le();mC=Yr.object({note:Yr.string().max(24).optional(),surfaceId:Yr.string().min(1)}).strict(),R7=Yr.object({protectedSurfaces:Yr.array(mC)}).strict()});var Mg=i(()=>{"use strict";Uc()});var Fg=i(()=>{"use strict"});var Bc=i(()=>{"use strict"});var Gg=i(()=>{"use strict";Bc();Xr()});var Zr=i(()=>{"use strict";Og();Wg();Xr();jc();Uc();Dg();Mg();Fg();Gg();Bc()});var Ha=i(()=>{"use strict"});var jg=i(()=>{"use strict";Zr();Ha()});var Ug=i(()=>{"use strict";Zr()});var qc=i(()=>{"use strict"});var Bg=i(()=>{"use strict";Zr();Ha();Ug();qc()});function $a(t){let e=t.trim();return e===""?[]:Array.from(fC.segment(e)).map(n=>n.segment.trim()).filter(n=>n!=="")}function xe(t){let e=t.replace(/\s+/gu," ").trim(),n=yC(e),r="";for(let a of n)if(!gC(a)){if(!ei(a)){r+=a;continue}r+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return r}function yC(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&&hC.has(e[e.length-1]??"")&&ei(e[e.length-2]??"")&&n<t.length-1&&ei(t[n+1]??"")){e.pop(),n+=1;continue}let a=e[e.length-1]??"",o=t[n+1]??"";a!==""&&o!==""&&ei(a)&&ei(o)&&e.push(r),n+=1}return e}function ei(t){return t!==""&&new RegExp("\\p{Script=Latin}","u").test(t)&&new RegExp("\\p{L}","u").test(t)}function gC(t){return/[\p{P}\p{S}]/u.test(t)}var hC,fC,ti=i(()=>{"use strict";hC=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),fC=new Intl.Segmenter(void 0,{granularity:"sentence"})});function $c(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function Hg(t,e){let n=Ja(t,2),r=Ja(e,2),a=Ja(t,3),o=Ja(e,3);return(qg(n,r)+qg(a,o))/2}function Ja(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 qg(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 $g(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 Jg(t,e){return 1-Math.abs(t.length-e.length)/Math.max(t.length,e.length)}function Kg(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 zg(t){return` - ${t.occurrenceId} score=${t.score.toFixed(3)}
|
|
774
|
+
prev: ${Hc(t.prevText)}
|
|
775
|
+
text: ${Hc(t.text,120)}
|
|
776
|
+
next: ${Hc(t.nextText)}`}function Hc(t,e=80){let n=t.replace(/\s+/gu," ").trim();return n===""?"(none)":n.length<=e?n:`${n.slice(0,e-3)}...`}var Jc=i(()=>{"use strict"});var Kc=i(()=>{"use strict"});function Xg(t,e,n){return t.mode==="head_tail"?wC(t,e):zc(t.text??"",e,n)}function wC(t,e){let n=t.head??"",r=t.tail??"",a=xe(e),o=xe(n),s=xe(r);if(o===""||s==="")return $c();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=zc(n,e,"start_anchor"),m=zc(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 zc(t,e,n){let r=t.trim(),a=e.trim(),o=xe(r),s=xe(a);if(o===""||s==="")return $c();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=Qg({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,K=[...v].filter(ie=>C.has(ie)).length;if((L===0?0:K/L)<.35)continue;let j=.35*Hg(o,g)+.35*Kg(o,g)+.2*$g(o,g)+.1*Jg(o,g)+Qg({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 Qg(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 Vg=i(()=>{"use strict";ti();Jc();Kc()});function Yg(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 Zg(t,e){if(t===void 0)return;if(t.mode==="head_tail"){let r=e==="end_anchor"?Qc(t.tail??"","end_anchor"):Qc(t.head??"","start_anchor");return r===""?void 0:{mode:"full",text:r}}return{mode:"full",text:Qc(t.text??"",e)}}function Xc(t){return t.mode==="head_tail"?xe(t.head??"").length+xe(t.tail??"").length:xe(t.text??"").length}function Qc(t,e){let n=$a(t);return n.length<=1?t.trim():e==="end_anchor"?n[n.length-1]??t.trim():n[0]??t.trim()}var eb=i(()=>{"use strict";ti()});var An,ib=i(()=>{"use strict";Vg();eb();Jc();Kc();An=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]=Yg(e);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:n,message:`Invalid evidence.${n}: ${a}`}]:[Zg(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&&Xc(e.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&Xc(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=Xg(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=>zg(s)).join(`
|
|
777
777
|
`);return{candidates:a,code:n,fieldName:e,message:`${e} is ambiguous. Top candidates:
|
|
778
778
|
${o}
|
|
779
|
-
Please provide a more specific anchor or surrounding context.`}}}});var
|
|
780
|
-
`)});var $c=i(()=>{"use strict"});var nb=i(()=>{"use strict";$c();Zr()});var ja=i(()=>{"use strict";eb();tb();$c();nb();Zr()});var ib=i(()=>{"use strict"});import{z as D}from"zod";var ab,gC,bC,SC,Mee,Fee,ob=i(()=>{"use strict";le();ja();ib();ab=D.object({head:D.string().optional(),mode:D.enum(["full","head_tail"]).optional(),tail:D.string().optional(),text:D.string().optional()}).strict(),gC=D.object({quote:D.string().optional(),sentence_id:D.string().optional()}).strict(),bC=D.union([D.object({end_anchor:D.union([D.string(),ab]).optional(),quote:D.string().optional(),sentence_id:D.string().optional(),start_anchor:D.union([D.string(),ab]).optional()}).strict(),D.array(gC)]),SC=D.object({confidence:D.number().min(0).max(1).optional(),evidence:bC,predicate:D.string().min(1).max(64),sourceMentionId:D.string().min(1),targetMentionId:D.string().min(1)}).strict(),Mee=D.object({relations:D.array(SC)}).strict(),Fee=new Cn});var sb=i(()=>{"use strict"});var db=i(()=>{"use strict"});var cb=i(()=>{"use strict";ob();sb();db()});var ub=i(()=>{"use strict";cb();Ma();Dc()});var ei,Tn=i(()=>{"use strict";ei=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 mte,Kc=i(()=>{"use strict";le();Ht();Ng();Dg();ub();Vr();Tn();mte=["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 lb=i(()=>{"use strict"});var mb=i(()=>{"use strict"});var pb=i(()=>{"use strict";lb();mb()});var Kt=i(()=>{"use strict"});var ti=i(()=>{"use strict";le()});var fb=i(()=>{"use strict";Kt();ti()});var yb=i(()=>{"use strict";ti()});var gb=i(()=>{"use strict"});import{z as I}from"zod";var bb,IC,Sb,EC,RC,vC,CC,TC,_C,Ua=i(()=>{"use strict";Kt();bb=I.object({from:I.union([I.number().int(),I.string()]),strength:I.string().optional(),to:I.union([I.number().int(),I.string()])}),IC=I.object({quote:I.string().optional(),sentence_id:I.string().optional()}).passthrough(),Sb=I.union([I.record(I.string(),I.unknown()),I.array(IC)]),EC=I.object({content:I.string(),evidence:Sb.nullish(),label:I.string(),retention:I.enum(["verbatim","detailed","focused","relevant"]),temp_id:I.string()}).passthrough(),RC=I.object({chunks:I.array(EC),fragment_summary:I.string(),links:I.array(bb)}),vC=I.object({content:I.string(),evidence:Sb.nullish(),importance:I.enum(["critical","important","helpful"]),label:I.string(),temp_id:I.string()}).passthrough(),CC=I.object({chunk_id:I.number().int(),importance:I.enum(["critical","important","helpful"])}),TC=I.object({chunks:I.array(vC),importance_annotations:I.array(CC),links:I.array(bb)}),_C=I.object({choice:I.string()})});var wb=i(()=>{"use strict";le();ja();gb();ti();Ua()});var kb=i(()=>{"use strict";le();Kt();fb();ti();yb();wb();Ua()});var xb=i(()=>{"use strict";kb();Ua()});var Qc=i(()=>{"use strict"});import{detect as pne,validateISO2 as hne}from"tinyld";var Ib=i(()=>{"use strict"});var Eb=i(()=>{"use strict"});import{z as ni}from"zod";var LC,One,Rb=i(()=>{"use strict";le();ja();xb();Qc();Qc();Ib();Eb();LC=ni.object({content:ni.string(),id:ni.number(),label:ni.string()}),One=ni.array(LC)});var vb=i(()=>{"use strict";Rb()});var Cb=i(()=>{"use strict";pb();vb()});var Tb=i(()=>{"use strict";Cb()});var _b=i(()=>{"use strict"});var Pb=i(()=>{"use strict"});var Xc=i(()=>{"use strict";_b();le();Tn();Pb()});var Ab=i(()=>{"use strict"});var Lb=i(()=>{"use strict"});var Ob=i(()=>{"use strict";Ab();Lb()});var ri=i(()=>{"use strict"});var gre,bre,_n=i(()=>{"use strict";Kt();gre={critical:9,helpful:1,important:3},bre={detailed:9,focused:3,relevant:1,verbatim:27}});var Pn=i(()=>{"use strict"});var ii=i(()=>{"use strict"});var Vc=i(()=>{"use strict";Pn()});var Yc=i(()=>{"use strict";_n();Pn();ri();ii();Vc()});var Zc=i(()=>{"use strict";ri();Yc();ii()});var Wb=i(()=>{"use strict";_n();Pn();ii()});var Db=i(()=>{"use strict";_n();Pn();ri();ii();Vc()});var Mb=i(()=>{"use strict";Zc();Pn();ri();Wb();Yc();Db()});var Fb=i(()=>{"use strict";Mb();Zc()});var Gb=i(()=>{"use strict";_n()});var jb=i(()=>{"use strict";Fb();Gb()});var Ub=i(()=>{"use strict";Ob();jb();_n()});var eu=i(()=>{"use strict";Ht();Tn();Tb();Xc();Ub()});var Bb=i(()=>{"use strict"});var qa=i(()=>{"use strict"});var qb=i(()=>{"use strict";qa()});var Ha=i(()=>{"use strict"});var Jie,$b=i(()=>{"use strict";qa();Ha();Jie=Object.freeze({critical:9,major:3,minor:1})});import{detect as Qie,validateISO2 as Xie}from"tinyld";var Jb=i(()=>{"use strict";Ha()});var Kb=i(()=>{"use strict"});var zb=i(()=>{"use strict";Kt()});var tu=i(()=>{"use strict";zb()});var Qb=i(()=>{"use strict"});import{z as An}from"zod";var BC,qC,hae,Xb=i(()=>{"use strict";le();qa();tu();Ha();BC=["critical","major","minor"],qC=An.object({problem:An.string(),severity:An.enum(BC),suggestion:An.string().default("")}),hae=An.object({issues:An.array(qC)})});var Vb=i(()=>{"use strict";Bb();qb();$b();Jb();Kb();tu();Qb();Xb()});var nu=i(()=>{"use strict";Ht();Tn();Kt();Xc();Vb()});var Yb=i(()=>{"use strict";Cc();Ht();_c();Kc();eu();nu()});import{z as G}from"zod";var Ln,HC,$C,JC,KC,aoe,Zb=i(()=>{"use strict";Ln=G.number().finite().nonnegative(),HC=G.enum(["committing","enrichment","grounding","indexing","matching","narrowing","relation-discovery","reading-extraction","screening","summary-compression"]),$C=G.enum(["candidate","char","item","page","qid","record","sentence","window"]),JC=G.object({cacheReadTokens:Ln.optional(),inputTokens:Ln.optional(),outputTokens:Ln.optional()}),KC=G.object({done:Ln,force:G.boolean().optional(),phase:HC,phaseDetail:G.string().optional(),total:Ln,unit:$C}),aoe=G.discriminatedUnion("event",[G.object({characters:Ln,event:G.literal("output-characters")}),G.object({event:G.literal("token-usage"),usage:JC}),G.object({event:G.literal("progress"),progress:KC}),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 tS=i(()=>{"use strict"});var ai=i(()=>{"use strict";hg();fg();Yb();_c();Cc();Ht();Kc();eu();nu();Tn();Zb();eS();tS();vc()});var nS=i(()=>{"use strict";ai();Wr()});import{z as T}from"zod";var zC,QC,_oe,Poe,Aoe,rS=i(()=>{"use strict";y();zC="wikg-index-output/v1",QC=T.enum(["fts","embedding-source","embedding-summary"]),_oe=T.object({artifactKind:QC,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(zC),type:T.literal("manifest")}),Poe=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")}),Aoe=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 zt=i(()=>{"use strict";nS();rS()});var iS=i(()=>{"use strict";Me();pt()});var aS=i(()=>{"use strict";_();Ta()});var sS=i(()=>{"use strict";y();_();Y();Rn();vn();zt();iS();aS()});var $a=i(()=>{"use strict"});var dS=i(()=>{"use strict";$a()});var cS=i(()=>{"use strict"});var uS=i(()=>{"use strict";$a()});var lS=i(()=>{"use strict";$a()});var mS=i(()=>{"use strict";dS();cS();uS();lS()});import{z as h}from"zod";var pS,sT,dT,cT,uT,lT,mT,pT,hT,fT,yT,hS=i(()=>{"use strict";Ce();pS=h.tuple([h.number(),h.number()]),sT=h.object({text:h.string(),wordsCount:h.number()}),dT=h.object({serialId:h.number(),fragmentId:h.number(),summary:h.string(),sentences:h.array(sT)}),cT=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}})),uT=h.object({id:h.number(),generation:h.number(),sentenceId:pS,label:h.string(),content:h.string(),sentenceIds:h.array(pS),retention:h.enum(he).optional(),importance:h.enum(ve).optional(),wordsCount:h.number(),weight:h.number()}),lT=h.object({fromId:h.number(),toId:h.number(),strength:h.string().optional(),weight:h.number()}),mT=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()}),pT=h.object({snakeId:h.number(),chunkId:h.number(),position:h.number()}),hT=h.object({fromSnakeId:h.number(),toSnakeId:h.number(),weight:h.number()}),fT=h.object({serialId:h.number(),groupId:h.number(),startSentenceIndex:h.number(),endSentenceIndex:h.number()}),yT=h.object({chunks:h.array(uT),fragmentGroups:h.array(fT),fragments:h.array(dT),readingEdges:h.array(lT),serial:cT,snakeChunks:h.array(pT),snakeEdges:h.array(hT),snakes:h.array(mT)})});var fS=i(()=>{"use strict";y();hS()});var yS=i(()=>{"use strict";en();yc();Z()});var gS=i(()=>{"use strict";y();_();Y();mS();fS();Wa();yS();vn();zt()});var bS=i(()=>{"use strict"});var Ja=i(()=>{"use strict";gS();Wa();bS()});var SS=i(()=>{"use strict";Y();Ja()});var wS=i(()=>{"use strict"});var kS=i(()=>{"use strict";sS();SS();wS()});var xS=i(()=>{"use strict";ai()});var ES=i(()=>{"use strict";ai();_();Y();zt();Ja()});var RS=i(()=>{"use strict";ai();mt();en()});var vS=i(()=>{"use strict";kS();Ja();xS();ES();RS()});import{z as $}from"zod";var $de,bT,Jde,ou=i(()=>{"use strict";y();$de=$.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()}),bT=$.tuple([$.number().int().nonnegative(),$.number().int().nonnegative()]).readonly(),Jde=$.object({id:$.string().min(1),sourceMentionId:$.string().min(1),targetMentionId:$.string().min(1),predicate:$.string().min(1),evidenceSentenceIds:$.array(bT).min(1),confidence:$.number().min(0).max(1).optional(),note:$.string().optional()})});var su=i(()=>{"use strict";y();Me();vn();ou()});var TS=i(()=>{"use strict";vn();zt();ou()});var Ka=i(()=>{"use strict"});var _S=i(()=>{"use strict";mt();Ka()});var du=i(()=>{"use strict"});var PS=i(()=>{"use strict";mt()});var cu=i(()=>{"use strict"});var uu=i(()=>{"use strict";mt();Ka();PS();cu()});var LS=i(()=>{"use strict";uu()});var OS=i(()=>{"use strict";Me()});var NS=i(()=>{"use strict";lc();Sn();Ca()});import{z as M}from"zod";var WS,xT,IT,ET,Dce,Mce,DS=i(()=>{"use strict";Ne();Sn();NS();WS=M.object({head:M.string().optional(),mode:M.enum(["full","head_tail"]).optional(),tail:M.string().optional(),text:M.string().optional()}).strict(),xT=M.object({quote:M.string().optional(),sentence_id:M.string().optional()}).strict(),IT=M.union([M.object({end_anchor:M.union([M.string(),WS]).optional(),quote:M.string().optional(),sentence_id:M.string().optional(),start_anchor:M.union([M.string(),WS]).optional()}).strict(),M.array(xT)]),ET=M.object({confidence:M.number().min(0).max(1).optional(),evidence:IT,predicate:M.string().min(1).max(64),sourceMentionId:M.string().min(1),targetMentionId:M.string().min(1)}).strict(),Dce=M.object({relations:M.array(ET)}).strict(),Mce=new Bt});var MS=i(()=>{"use strict"});var FS=i(()=>{"use strict";DS();MS()});var GS=i(()=>{"use strict";FS();Ka();cu()});var lu=i(()=>{"use strict";Y();du()});var BS=i(()=>{"use strict";mt();pt();su();_S();du();LS();OS();GS();lu()});var qS=i(()=>{"use strict"});var HS=i(()=>{"use strict";su();TS();BS();uu();lu();qS()});var $S=i(()=>{"use strict";HS()});var oi=i(()=>{"use strict";Y()});var mu=i(()=>{"use strict";pt()});var pu=i(()=>{"use strict";Me();pt();Rn();oi();mu()});var zS=i(()=>{"use strict";pt();oi();pu()});var hu=i(()=>{"use strict";ye();Z()});var XS=i(()=>{"use strict";ye();tr();Et();hu();Z()});var VS=i(()=>{"use strict";Rn();ye();oi();XS();hu();Z()});import{z as Qt}from"zod";var YS,ble,ZS=i(()=>{"use strict";YS=Qt.object({children:Qt.lazy(()=>Qt.array(YS)),uri:Qt.string().min(1),title:Qt.string().nullable().optional()}).strict(),ble=Qt.object({chapters:Qt.array(YS)}).strict()});var ew=i(()=>{"use strict";Y()});var tw=i(()=>{"use strict";zS();oi();pu();VS();mu();ZS();ew()});var nw=i(()=>{"use strict";lr()});var ze=i(()=>{"use strict";lg();ot();Gd();vS();$S();ot();Rc();tw();nw();la()});async function Dw(t="global"){let e=await xu(),n=Xe(),r=Date.now(),a=!1;try{await e.transaction(async()=>{await B_(e),await e.run(`
|
|
779
|
+
Please provide a more specific anchor or surrounding context.`}}}});var ab=i(()=>{"use strict"});var ob=i(()=>{"use strict";ib();ab()});var Vc,sb=i(()=>{"use strict";Vc=["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(`
|
|
780
|
+
`)});var Yc=i(()=>{"use strict"});var db=i(()=>{"use strict";Yc();ti()});var Ka=i(()=>{"use strict";ob();sb();Yc();db();ti()});var ub=i(()=>{"use strict"});import{z as D}from"zod";var lb,EC,vC,RC,tte,nte,mb=i(()=>{"use strict";le();Ka();ub();lb=D.object({head:D.string().optional(),mode:D.enum(["full","head_tail"]).optional(),tail:D.string().optional(),text:D.string().optional()}).strict(),EC=D.object({quote:D.string().optional(),sentence_id:D.string().optional()}).strict(),vC=D.union([D.object({end_anchor:D.union([D.string(),lb]).optional(),quote:D.string().optional(),sentence_id:D.string().optional(),start_anchor:D.union([D.string(),lb]).optional()}).strict(),D.array(EC)]),RC=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(),tte=D.object({relations:D.array(RC)}).strict(),nte=new An});var pb=i(()=>{"use strict"});var hb=i(()=>{"use strict"});var fb=i(()=>{"use strict";mb();pb();hb()});var yb=i(()=>{"use strict";fb();Ha();qc()});var ni,Ln=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 Pte,eu=i(()=>{"use strict";le();$t();jg();Bg();yb();Zr();Ln();Pte=["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 gb=i(()=>{"use strict"});var bb=i(()=>{"use strict"});var Sb=i(()=>{"use strict";gb();bb()});var zt=i(()=>{"use strict"});var ri=i(()=>{"use strict";le()});var kb=i(()=>{"use strict";zt();ri()});var xb=i(()=>{"use strict";ri()});var Ib=i(()=>{"use strict"});import{z as I}from"zod";var Eb,PC,vb,AC,LC,OC,NC,WC,DC,za=i(()=>{"use strict";zt();Eb=I.object({from:I.union([I.number().int(),I.string()]),strength:I.string().optional(),to:I.union([I.number().int(),I.string()])}),PC=I.object({quote:I.string().optional(),sentence_id:I.string().optional()}).passthrough(),vb=I.union([I.record(I.string(),I.unknown()),I.array(PC)]),AC=I.object({content:I.string(),evidence:vb.nullish(),label:I.string(),retention:I.enum(["verbatim","detailed","focused","relevant"]),temp_id:I.string()}).passthrough(),LC=I.object({chunks:I.array(AC),fragment_summary:I.string(),links:I.array(Eb)}),OC=I.object({content:I.string(),evidence:vb.nullish(),importance:I.enum(["critical","important","helpful"]),label:I.string(),temp_id:I.string()}).passthrough(),NC=I.object({chunk_id:I.number().int(),importance:I.enum(["critical","important","helpful"])}),WC=I.object({chunks:I.array(OC),importance_annotations:I.array(NC),links:I.array(Eb)}),DC=I.object({choice:I.string()})});var Rb=i(()=>{"use strict";le();Ka();Ib();ri();za()});var Cb=i(()=>{"use strict";le();zt();kb();ri();xb();Rb();za()});var Tb=i(()=>{"use strict";Cb();za()});var nu=i(()=>{"use strict"});import{detect as Ane,validateISO2 as Lne}from"tinyld";var _b=i(()=>{"use strict"});var Pb=i(()=>{"use strict"});import{z as ii}from"zod";var GC,Vne,Ab=i(()=>{"use strict";le();Ka();Tb();nu();nu();_b();Pb();GC=ii.object({content:ii.string(),id:ii.number(),label:ii.string()}),Vne=ii.array(GC)});var Lb=i(()=>{"use strict";Ab()});var Ob=i(()=>{"use strict";Sb();Lb()});var Nb=i(()=>{"use strict";Ob()});var Wb=i(()=>{"use strict"});var Db=i(()=>{"use strict"});var ru=i(()=>{"use strict";Wb();le();Ln();Db()});var Mb=i(()=>{"use strict"});var Fb=i(()=>{"use strict"});var Gb=i(()=>{"use strict";Mb();Fb()});var ai=i(()=>{"use strict"});var Wre,Dre,On=i(()=>{"use strict";zt();Wre={critical:9,helpful:1,important:3},Dre={detailed:9,focused:3,relevant:1,verbatim:27}});var Nn=i(()=>{"use strict"});var oi=i(()=>{"use strict"});var iu=i(()=>{"use strict";Nn()});var au=i(()=>{"use strict";On();Nn();ai();oi();iu()});var ou=i(()=>{"use strict";ai();au();oi()});var Ub=i(()=>{"use strict";On();Nn();oi()});var Bb=i(()=>{"use strict";On();Nn();ai();oi();iu()});var qb=i(()=>{"use strict";ou();Nn();ai();Ub();au();Bb()});var Hb=i(()=>{"use strict";qb();ou()});var $b=i(()=>{"use strict";On()});var Jb=i(()=>{"use strict";Hb();$b()});var Kb=i(()=>{"use strict";Gb();Jb();On()});var su=i(()=>{"use strict";$t();Ln();Nb();ru();Kb()});var zb=i(()=>{"use strict"});var Xa=i(()=>{"use strict"});var Qb=i(()=>{"use strict";Xa()});var Va=i(()=>{"use strict"});var uae,Vb=i(()=>{"use strict";Xa();Va();uae=Object.freeze({critical:9,major:3,minor:1})});import{detect as pae,validateISO2 as hae}from"tinyld";var Yb=i(()=>{"use strict";Va()});var Zb=i(()=>{"use strict"});var eS=i(()=>{"use strict";zt()});var du=i(()=>{"use strict";eS()});var tS=i(()=>{"use strict"});import{z as Wn}from"zod";var QC,XC,Lae,nS=i(()=>{"use strict";le();Xa();du();Va();QC=["critical","major","minor"],XC=Wn.object({problem:Wn.string(),severity:Wn.enum(QC),suggestion:Wn.string().default("")}),Lae=Wn.object({issues:Wn.array(XC)})});var rS=i(()=>{"use strict";zb();Qb();Vb();Yb();Zb();du();tS();nS()});var cu=i(()=>{"use strict";$t();Ln();zt();ru();rS()});var iS=i(()=>{"use strict";Nc();$t();Dc();eu();su();cu()});import{z as G}from"zod";var Dn,VC,YC,ZC,eT,Ioe,aS=i(()=>{"use strict";Dn=G.number().finite().nonnegative(),VC=G.enum(["committing","enrichment","grounding","indexing","matching","narrowing","relation-discovery","reading-extraction","screening","summary-compression"]),YC=G.enum(["candidate","char","item","page","qid","record","sentence","window"]),ZC=G.object({cacheReadTokens:Dn.optional(),inputTokens:Dn.optional(),outputTokens:Dn.optional()}),eT=G.object({done:Dn,force:G.boolean().optional(),phase:VC,phaseDetail:G.string().optional(),total:Dn,unit:YC}),Ioe=G.discriminatedUnion("event",[G.object({characters:Dn,event:G.literal("output-characters")}),G.object({event:G.literal("token-usage"),usage:ZC}),G.object({event:G.literal("progress"),progress:eT}),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 oS=i(()=>{"use strict"});var sS=i(()=>{"use strict"});var si=i(()=>{"use strict";wg();kg();iS();Dc();Nc();$t();eu();su();cu();Ln();aS();oS();sS();Oc()});var dS=i(()=>{"use strict";si();hn()});import{z as T}from"zod";var tT,nT,Koe,zoe,Qoe,cS=i(()=>{"use strict";y();tT="wikg-index-output/v1",nT=T.enum(["fts","embedding-source","embedding-summary"]),Koe=T.object({artifactKind:nT,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(tT),type:T.literal("manifest")}),zoe=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")}),Qoe=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";dS();cS()});var uS=i(()=>{"use strict";Me();yt()});var lS=i(()=>{"use strict";_();Wa()});var pS=i(()=>{"use strict";y();_();Y();_n();Pn();Qt();uS();lS()});var Ya=i(()=>{"use strict"});var hS=i(()=>{"use strict";Ya()});var fS=i(()=>{"use strict"});var yS=i(()=>{"use strict";Ya()});var gS=i(()=>{"use strict";Ya()});var bS=i(()=>{"use strict";hS();fS();yS();gS()});import{z as h}from"zod";var SS,hT,fT,yT,gT,bT,ST,wT,kT,xT,IT,wS=i(()=>{"use strict";Re();SS=h.tuple([h.number(),h.number()]),hT=h.object({text:h.string(),wordsCount:h.number()}),fT=h.object({serialId:h.number(),fragmentId:h.number(),summary:h.string(),sentences:h.array(hT)}),yT=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}})),gT=h.object({id:h.number(),generation:h.number(),sentenceId:SS,label:h.string(),content:h.string(),sentenceIds:h.array(SS),retention:h.enum(he).optional(),importance:h.enum(ve).optional(),wordsCount:h.number(),weight:h.number()}),bT=h.object({fromId:h.number(),toId:h.number(),strength:h.string().optional(),weight:h.number()}),ST=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()}),wT=h.object({snakeId:h.number(),chunkId:h.number(),position:h.number()}),kT=h.object({fromSnakeId:h.number(),toSnakeId:h.number(),weight:h.number()}),xT=h.object({serialId:h.number(),groupId:h.number(),startSentenceIndex:h.number(),endSentenceIndex:h.number()}),IT=h.object({chunks:h.array(gT),fragmentGroups:h.array(xT),fragments:h.array(fT),readingEdges:h.array(bT),serial:yT,snakeChunks:h.array(wT),snakeEdges:h.array(kT),snakes:h.array(ST)})});var kS=i(()=>{"use strict";y();wS()});var xS=i(()=>{"use strict";tn();Ic();Z()});var IS=i(()=>{"use strict";y();_();Y();bS();kS();Ba();xS();Pn();Qt()});var ES=i(()=>{"use strict"});var Za=i(()=>{"use strict";IS();Ba();ES()});var vS=i(()=>{"use strict";Y();Za()});var RS=i(()=>{"use strict"});var CS=i(()=>{"use strict";pS();vS();RS()});var TS=i(()=>{"use strict";si()});var PS=i(()=>{"use strict";si();_();Y();Qt();Za()});var AS=i(()=>{"use strict";si();ft();tn()});var LS=i(()=>{"use strict";CS();Za();TS();PS();AS()});import{z as $}from"zod";var cce,vT,uce,pu=i(()=>{"use strict";y();cce=$.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(),uce=$.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 hu=i(()=>{"use strict";y();Me();Pn();pu()});var NS=i(()=>{"use strict";Pn();Qt();pu()});var eo=i(()=>{"use strict"});var WS=i(()=>{"use strict";ft();eo()});var fu=i(()=>{"use strict"});var DS=i(()=>{"use strict";ft()});var yu=i(()=>{"use strict"});var gu=i(()=>{"use strict";ft();eo();DS();yu()});var FS=i(()=>{"use strict";gu()});var GS=i(()=>{"use strict";Me()});var jS=i(()=>{"use strict";bc();In();Na()});import{z as M}from"zod";var US,_T,PT,AT,eue,tue,BS=i(()=>{"use strict";Ne();In();jS();US=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(),PT=M.union([M.object({end_anchor:M.union([M.string(),US]).optional(),quote:M.string().optional(),sentence_id:M.string().optional(),start_anchor:M.union([M.string(),US]).optional()}).strict(),M.array(_T)]),AT=M.object({confidence:M.number().min(0).max(1).optional(),evidence:PT,predicate:M.string().min(1).max(64),sourceMentionId:M.string().min(1),targetMentionId:M.string().min(1)}).strict(),eue=M.object({relations:M.array(AT)}).strict(),tue=new qt});var qS=i(()=>{"use strict"});var HS=i(()=>{"use strict";BS();qS()});var $S=i(()=>{"use strict";HS();eo();yu()});var bu=i(()=>{"use strict";Y();fu()});var zS=i(()=>{"use strict";ft();yt();hu();WS();fu();FS();GS();$S();bu()});var QS=i(()=>{"use strict"});var XS=i(()=>{"use strict";hu();NS();zS();gu();bu();QS()});var VS=i(()=>{"use strict";XS()});var di=i(()=>{"use strict";Y()});var Su=i(()=>{"use strict";yt()});var wu=i(()=>{"use strict";Me();yt();_n();di();Su()});var ew=i(()=>{"use strict";yt();di();wu()});var ku=i(()=>{"use strict";ye();Z()});var nw=i(()=>{"use strict";ye();ar();at();ku();Z()});var rw=i(()=>{"use strict";_n();ye();di();nw();ku();Z()});import{z as Xt}from"zod";var iw,Dle,aw=i(()=>{"use strict";iw=Xt.object({children:Xt.lazy(()=>Xt.array(iw)),uri:Xt.string().min(1),title:Xt.string().nullable().optional()}).strict(),Dle=Xt.object({chapters:Xt.array(iw)}).strict()});var ow=i(()=>{"use strict";Y()});var sw=i(()=>{"use strict";ew();di();wu();rw();Su();aw();ow()});var dw=i(()=>{"use strict";hr()});var Ve=i(()=>{"use strict";gg();ct();Kd();LS();VS();ct();Lc();sw();dw();ba()});async function Bw(t="global"){let e=await _u(),n=Ze(),r=Date.now(),a=!1;try{await e.transaction(async()=>{await X_(e),await e.run(`
|
|
781
781
|
INSERT OR IGNORE INTO gc_locks (
|
|
782
782
|
scope, owner_id, owner_pid, heartbeat_at, created_at
|
|
783
783
|
) VALUES (?, ?, ?, ?, ?)
|
|
784
|
-
`,[t,n,0,r,r]),a=await e.queryOne("SELECT owner_id FROM gc_locks WHERE scope = ?",[t],s=>E(s,"owner_id"))===n})}finally{await e.close()}if(!a)return;let o=setInterval(()=>{
|
|
784
|
+
`,[t,n,0,r,r]),a=await e.queryOne("SELECT owner_id FROM gc_locks WHERE scope = ?",[t],s=>E(s,"owner_id"))===n})}finally{await e.close()}if(!a)return;let o=setInterval(()=>{Q_(t,n).catch(()=>{})},z_);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 Q_(t,e){let n=await _u();try{await n.run(`
|
|
785
785
|
UPDATE gc_locks
|
|
786
786
|
SET heartbeat_at = ?, owner_pid = ?
|
|
787
787
|
WHERE scope = ? AND owner_id = ?
|
|
788
|
-
`,[Date.now(),0,t,e])}finally{await n.close()}}async function
|
|
788
|
+
`,[Date.now(),0,t,e])}finally{await n.close()}}async function X_(t){let e=await t.queryAll("SELECT * FROM gc_locks",void 0,Z_);for(let{lock:n,scope:r}of e.filter(({lock:a})=>V_(a)))await t.run(`
|
|
789
789
|
DELETE FROM gc_locks
|
|
790
790
|
WHERE scope = ?
|
|
791
791
|
AND owner_id = ?
|
|
792
792
|
AND heartbeat_at = ?
|
|
793
|
-
`,[r,n.ownerId,n.heartbeatAt])}function
|
|
793
|
+
`,[r,n.ownerId,n.heartbeatAt])}function V_(t){return!(Date.now()-t.heartbeatAt<K_)}async function _u(){return await X("tmp/gc.sqlite",J_)}function Y_(t){return{createdAt:S(t,"created_at"),heartbeatAt:S(t,"heartbeat_at"),ownerId:E(t,"owner_id"),ownerPid:S(t,"owner_pid")}}function Z_(t){return{lock:Y_(t),scope:E(t,"scope")}}var J_,K_,z_,qw=i(()=>{"use strict";F();w();_();J_=`
|
|
794
794
|
CREATE TABLE IF NOT EXISTS gc_locks (
|
|
795
795
|
scope TEXT PRIMARY KEY,
|
|
796
796
|
owner_id TEXT NOT NULL,
|
|
@@ -798,8 +798,8 @@ CREATE TABLE IF NOT EXISTS gc_locks (
|
|
|
798
798
|
heartbeat_at INTEGER NOT NULL,
|
|
799
799
|
created_at INTEGER NOT NULL
|
|
800
800
|
);
|
|
801
|
-
`,
|
|
802
|
-
`)}var
|
|
803
|
-
`}function
|
|
801
|
+
`,K_=6e4,z_=2e4});async function Hw(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 tP(e)){n+=1;let s=await Ye(o.value);if(!t.force&&(s===void 0||t.now-s<eP))continue;let d=await pt(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 tP(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 eP,$w=i(()=>{"use strict";y();Od();eP=3600*1e3});async function co(t={}){let e=Date.now(),n=await Bw();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 aP(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 nP)a.push(await iP(s,r));let o={finishedAt:Date.now(),freedBytes:Pu(a,"freedBytes"),jobs:a,removed:Pu(a,"removed"),scanned:Pu(a,"scanned"),skipped:!1,startedAt:e};return await oP(o.finishedAt).catch(()=>{}),o}finally{await n()}}async function iP(t,e){try{return{name:t.name,...await t.run(e)}}catch(n){return{error:en(n),freedBytes:0,name:t.name,removed:0,scanned:0}}}function Pu(t,e){return t.reduce((n,r)=>{let a=r[e];return n+(typeof a=="number"?a:0)},0)}async function aP(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>=rP}async function oP(t){let e=await H(R().library,"tmp/gc.last-run");await me(e,`${t}
|
|
802
|
+
`)}var nP,rP,Jw=i(()=>{"use strict";y();ct();Ve();Le();Ca();oc();pe();qw();$w();nP=[{name:"wikg-coordinator",run:wa},{name:"search-cache",run:Mi},{name:"library-index",run:Ef},{name:"build-queue",run:Ia},{name:"wikimedia-cache",run:ic},{name:"tmp",run:Hw}],rP=600*1e3});var Kw=i(()=>{"use strict";Jw()});var zw=i(()=>{"use strict";Kw()});var Qw={};Zw(Qw,{tryRunWikiGraphGc:()=>sP});async function sP(t={}){Un();let{stateDir:e,...n}=t;return await Zt(e,async()=>await co(n))}var Xw=i(()=>{"use strict";zw();de()});de();import{AsyncLocalStorage as G_}from"async_hooks";import{randomUUID as jfe}from"crypto";import{link as Bfe,mkdtemp as qfe,rename as Hfe,rm as $fe,stat as Jfe}from"fs/promises";import{tmpdir as zfe}from"os";import{basename as Xfe,dirname as Vfe,join as Yfe}from"path";import{Readable as eye}from"stream";Me();y();yi();import{z as qn}from"zod";var Rk=1,FP=qn.object({completedAt:qn.string().optional(),startedAt:qn.string(),status:qn.enum(["running","succeeded"]),version:qn.literal(Rk)});Ro();tn();et();Z();To();Fn();Ca();In();oc();ft();fc();Ve();ye();Le();_();at();ct();_();ar();_i();vi();Qt();y();nt();Je();lt();ut();vd();vi();Ca();hn();Qt();_();y();Le();y();w();w();y();w();y();ms();y();pe();Ve();Ve();Ve();Ve();Ve();yt();ft();_();Pn();y();import{createHash as ife}from"crypto";import{createReadStream as ofe}from"fs";import{rm as dfe}from"fs/promises";import{basename as ufe}from"path";import{createAnthropic as lhe}from"@ai-sdk/anthropic";import{createGoogleGenerativeAI as phe}from"@ai-sdk/google";import{createOpenAI as fhe}from"@ai-sdk/openai";import{createOpenAICompatible as ghe}from"@ai-sdk/openai-compatible";de();import{z as re}from"zod";import{AsyncLocalStorage as x_}from"async_hooks";var Rw=Symbol.for("wiki-graph-sdk.runtime-context.v1"),I_=E_();function E_(){let t=globalThis,e=t[Rw];if(e!==void 0)return e;let n=new x_;return Object.defineProperty(t,Rw,{configurable:!1,enumerable:!1,value:n,writable:!1}),n}async function vu(t,e){return await I_.run(t,e)}de();import{join as Rhe}from"path";import{homedir as The}from"os";var R_=["anthropic","google","openai","openai-compatible"],Cw=re.enum(R_),Ohe=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:Cw.optional()}).optional(),model:re.string().min(1).optional(),name:re.string().min(1).optional(),provider:Cw.optional()});import{homedir as Mhe}from"os";import{isAbsolute as Ghe,resolve as jhe}from"path";import{realpath as Hhe,stat as $he}from"fs/promises";import{basename as Khe,dirname as zhe,isAbsolute as Qhe,join as Xhe,relative as Vhe,resolve as Yhe}from"path";de();de();import{embed as kfe,embedMany as xfe}from"ai";import{createOpenAI as Efe}from"@ai-sdk/openai";import{createOpenAICompatible as Rfe}from"@ai-sdk/openai-compatible";import{spawn as fye}from"child_process";import{streamText as Pye}from"ai";Ve();de();var M_=["WIKIGRAPH_DEV","WIKIGRAPH_ENV_POLICY","WIKIGRAPH_QUEUE_DISABLE_AUTOSTART","WIKIGRAPH_STATE_DIR"];function Nw(t){let e=F_(t.env);if(t.envPolicy==="production"){let o=M_.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=Ow(t.stateDir??n);if(r===void 0)throw new Error("Wiki Graph development entries require an explicit runtime state directory.");let a=Ow(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 F_(t){return t===void 0?{...process.env}:{...process.env,...t}}function Ow(t){if(!(t===void 0||t.trim()===""))return t}de();de();import{mkdir as Age}from"fs/promises";var Dge=64*1024;de();import{basename as jge}from"path";de();de();var j_=new G_;async function Ww(t,e){return await j_.run(t,async()=>await vu({cwd:t.cwd,env:t.env,envPolicy:t.envPolicy,providers:{},...t.stateDir===void 0?{}:{stateDir:t.stateDir}},e))}var Dw="--wikigraph-internal-child",Mw="--wikigraph-dev-project-root",Fw="--wikigraph-env-policy",Gw="--wikigraph-state-dir";async function jw(t,e){let n=U_(process.argv.slice(2));if(n.internalChild!==t)throw new Error("This Wiki Graph worker entry is internal.");let r=Nw({argv:n.argv,devProjectRoot:n.devProjectRoot,envPolicy:n.envPolicy,stateDir:n.stateDir});return await Zt(r.stateDir,async()=>Ww({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 U_(t){let e=[],n,r,a="production",o;for(let s=0;s<t.length;s+=1){let d=t[s];if(d===Dw){if(s+1>=t.length)throw new Error(`${Dw} requires a value.`);n=t[s+1],s+=1;continue}if(d===Fw){let c=t[s+1];if(c!=="development"&&c!=="production")throw new Error(`${Fw} requires development or production.`);a=c,s+=1;continue}if(d===Mw){let c=t[s+1];if(c===void 0||c.trim()==="")throw new Error(`${Mw} requires a value.`);r=c,s+=1;continue}if(d!==Gw){e.push(d);continue}if(s+1>=t.length)throw new Error(`${Gw} requires a value.`);o=t[s+1],s+=1}return{argv:e,devProjectRoot:r,envPolicy:a,internalChild:n??"",stateDir:o}}var B_={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 Jbe}from"path";import{createReadStream as eSe}from"fs";import{mkdtemp as nSe,rm as rSe}from"fs/promises";import{join as aSe}from"path";import{tmpdir as sSe}from"os";var q_=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 Uw(t){return`${JSON.stringify(Tu(t),null,2)}
|
|
803
|
+
`}function Tu(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>Tu(e)??null);if(typeof t=="object")return H_(t)}function H_(t){let e=Object.entries(t).map(([r,a],o)=>({index:o,key:r,priority:q_.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=Tu(r.value);a!==void 0&&(n[r.key]=a)}return n}import{homedir as ySe}from"os";import{isAbsolute as bSe,relative as SSe,resolve as wSe}from"path";import{existsSync as vSe,readFileSync as RSe}from"fs";import{dirname as TSe,join as _Se,parse as PSe,resolve as ASe}from"path";Un();var{tryRunWikiGraphGc:dP}=await Promise.resolve().then(()=>(Xw(),Qw));async function cP(){await jw("gc-worker",async({argv:t})=>{let e=uP(t);process.stdout.write(Uw(await dP({dryRun:e.dryRun,force:e.force})))})}function uP(t){return{dryRun:t.includes("--dry-run"),force:t.includes("--force")}}cP().catch(t=>{process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}
|
|
804
804
|
`),process.exitCode=1});
|
|
805
805
|
//# sourceMappingURL=gc-worker.js.map
|