wiki-graph 0.9.2 → 0.9.3

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/gc-worker.js CHANGED
@@ -3,11 +3,11 @@ 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 Rk=Object.defineProperty;var i=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ck=(t,e)=>{for(var n in e)Rk(t,n,{get:e[n],enumerable:!0})};async function bi(t){let e=await t.openReader();try{return e.size}finally{await e.close()}}async function nt(t){return await bi(t)===0}async function te(t){return new TextDecoder().decode(await It(t))}async function It(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 ce(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(K(t)){let e=0;for(let n of await t.list())e+=await Ie(n);return e}return await bi(t)}async function rt(t){return await t.getLastModified?.()}function K(t){return t.kind==="directory"}var il=i(()=>{"use strict"});function nn(t){rn().installedPlatform=t}function A(){let{installedPlatform:t}=rn();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 vt(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 ee(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 ve(t,e){let n=Co(e),r=t;for(let a of n){let o=await r.getDirectory(a);if(!o)return;r=o}return r}async function H(t,e){let n=Co(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 q(t,e){let n=Co(e),r=n.pop();if(!r)throw new TypeError("File name must remain relative");let a=await H(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 Co(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 rn(){let t=globalThis,e=t[al];if(e!==void 0)return e;let n={storageContext:new Ro};return Object.defineProperty(t,al,{configurable:!1,enumerable:!1,value:n,writable:!1}),n}function ki(t){rn().installedStorage=t}async function an(t,e){return t===void 0?await e():await rn().storageContext.run(t,e)}function C(){let{installedStorage:t,storageContext:e}=rn(),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 al,Ro,b=i(()=>{"use strict";il();al=Symbol.for("wiki-graph-core.runtime.v1");Ro=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}=rn();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 xi(t){if(_k.test(t))throw new Error(`invalid template name ${t}`);let n=t.replace(Pk,"").replace(Tk,"");if(n.split("/").includes(".."))throw new Error(`invalid template name ${t}`);return`${n}.jinja`}var Tk,_k,Pk,Hn=i(()=>{"use strict";b();Tk=/\.jinja$/iu,_k=/^\.+\//u,Pk=/^\/+/u});var To=i(()=>{"use strict";b();Hn()});import*as dl from"async_hooks";import*as cl from"crypto";import*as on from"fs";import*as D from"fs/promises";import*as ul from"os";import*as W from"path";import*as No from"process";import{Readable as Do,Writable as Ak}from"stream";import{pipeline as Lk}from"stream/promises";import*as Wo from"sqlite3";import*as vi from"yauzl";import*as ll from"yazl";import{Environment as Ok,Loader as Nk}from"nunjucks";async function ol(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 ml(t,e,n){if(pl(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 pl(t){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("File offset must be a non-negative safe integer")}function hl(t,e){return`node-${t}:${Buffer.from(W.resolve(e),"utf8").toString("base64url")}`}function _o(t,e){let n=`node-${e}:`;if(!t.startsWith(n))return W.isAbsolute(t)?t:void 0;try{return Buffer.from(t.slice(n.length),"base64url").toString("utf8")}catch{return}}function $n(t){if(t.length===0||t==="."||t===".."||W.isAbsolute(t)||t.includes("/")||t.includes("\\"))throw new TypeError(`Directory child must be a relative name: ${t}`)}async function Dk(t,e){let n=(e.mode==="readonly"?Jn.OPEN_READONLY:Jn.OPEN_READWRITE|(e.create?Jn.OPEN_CREATE:0))|Jn.OPEN_FULLMUTEX;return new Ao(await Wk(t,n))}async function Wk(t,e){let n=fl(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 Mk(t,e={}){let n=fl(t,"file");if(n===void 0)throw new TypeError("The Node ZIP adapter requires a NodeFile");let r=await D.open(n,"r"),a;try{a=(await r.stat()).size}catch(f){throw await r.close(),f}let o=()=>new Promise((f,w)=>{vi.fromRandomAccessReader(new Lo(r),a,{autoClose:!1,lazyEntries:!0},(p,S)=>{p||S===void 0?w(p??new Error("Cannot open ZIP")):f(S)})});try{(await o()).close()}catch(f){throw await r.close(),f}let s=!1,d=Promise.resolve(),c,u=f=>{if(s)return Promise.reject(new Error("Cannot read a closed ZIP archive"));let w=d.then(async()=>{let p=await o();try{return await f(p)}finally{p.close()}});return d=w.then(()=>{},()=>{}),w},m=(f,w)=>u(async p=>{let S,g,v=!1;if(await Ei(p,R=>{R.fileName===f&&(S=R),sl(R.fileName)===f&&(g!==void 0&&g.fileName!==R.fileName&&(v=!0),g=R)}),(S===void 0||e.entryNameMode==="normalized")&&v){let R=-1,U=await o();try{return await Ei(U,async O=>{if(sl(O.fileName)!==f)return;let N=await o(),V=0;try{await Ei(N,Fe=>{if(Fe.fileName===O.fileName)return!1;V++})}finally{N.close()}V>=R&&(R=V,g=O)}),await w(U,g)}finally{U.close()}}return await w(p,e.entryNameMode==="normalized"?g:S??g)});return{close:()=>(s=!0,c??=d.then(()=>r.close()),c),copyEntry:(f,w)=>m(f,async(p,S)=>S===void 0?!1:(await Fk(p,S,w),!0)),getEntrySize:f=>m(f,(w,p)=>Promise.resolve(p?.uncompressedSize)),listEntries:()=>u(async f=>{let w=new Set;return await Ei(f,p=>{w.add(p.fileName)}),[...w]}),readEntryRange:(f,w,p)=>m(f,async(S,g)=>{if(g!==void 0)return await jk(S,g,w,p)}),readEntry:f=>m(f,async(w,p)=>{if(p!==void 0)return await Gk(w,p)})}}function sl(t){let e=t.replaceAll("\\","/").trim().split("/").filter(n=>n!==""&&n!==".").join("/");return e.split("/").includes("..")?void 0:e}async function Ei(t,e){await new Promise((n,r)=>{let a=()=>{t.off("entry",d),t.off("end",s),t.off("error",o)},o=c=>{a(),r(c)},s=()=>{a(),n()},d=c=>{Promise.resolve().then(()=>c.fileName.endsWith("/")?void 0:e(c)).then(u=>{u===!1?s():t.readEntry()}).catch(u=>o(u instanceof Error?u:new Error("Cannot scan ZIP",{cause:u})))};t.on("entry",d),t.once("end",s),t.once("error",o),t.readEntry()})}async function Fk(t,e,n){let r=await n.openWriter();try{let a=await Ii(t,e);await yl(a,r),await r.commit()}catch(a){throw await r.abort().catch(()=>{}),a}}async function Gk(t,e){return await gl(await Ii(t,e))}async function jk(t,e,n,r){if(ml(n,r,e.uncompressedSize),r===0)return new Uint8Array;if(e.compressionMethod!==0){let o=await Uk(await Ii(t,e),n,r);return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}let a=await gl(await Ii(t,e,{decompress:null,decrypt:null,end:n+r,start:n}));return new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}async function Uk(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 Ii(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 qk(t,e){let n=new ll.ZipFile,r=await t.openWriter(),a=n.outputStream,o=yl(a,r),s={cancelled:!1,complete:!1},d;try{d=Jk(e);let c=Bk(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&&Kk(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 Bk(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(Hk(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($k(r.value),r.value.name,{compress:!1,size:r.value.size})}}function Hk(t){return Do.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 fl(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 $k(t){return Do.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 Jk(t){let e=t[Symbol.asyncIterator];return e===void 0?t[Symbol.iterator]():e.call(t)}function Kk(t){if(t.return!==void 0)try{Promise.resolve(t.return()).catch(()=>{})}catch{}}async function yl(t,e){await Lk(t,new Ak({write:(n,r,a)=>{e.write(n).then(()=>a(),o=>a(o instanceof Error?o:new Error("Cannot stream ZIP archive")))}}))}async function gl(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 zk(){let t=globalThis.__WIKIGRAPH_DATA_DIR__;if(typeof t=="string"&&t!=="")return t;let e=Po.cwd();for(;;){for(let r of[W.join(e,"data"),W.join(e,"packages","core","data")])try{if(on.statSync(r).isDirectory())return r}catch{}let n=W.dirname(e);if(n===e)throw new Error("Could not locate data directory");e=n}}function Fo(t=W.join(ul.homedir(),".wikigraph")){let e=typeof t=="string"?t:t.libraryRoot,n=typeof t=="string"?W.join(t,"documents"):t.documentStoreRoot;return{library:new Re(e),documentStore:new Re(n)}}function wl(t){nn(bl),ki(Fo(t))}function Sl(){try{A()}catch{nn(bl)}try{C()}catch{ki(Fo())}}async function Ri(t,e){return await an(t===void 0?void 0:Fo(t),e)}var Po,Jn,Mo,se,Re,Ao,Lo,bl,Oo,ue=i(()=>{"use strict";To();Po=No.default??No,Jn=Wo.default??Wo,Mo=Symbol.for("wiki-graph-sdk.node-resource.v1"),se=class{constructor(e,n=W.basename(e)){this.path=e;this.identity=hl("file",e),this.name=n}path;async getPhysicalIdentity(){let e=await D.stat(this.path).catch(n=>{if(!(typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT"))throw n});if(e!==void 0)return`${e.dev}:${e.ino}`}kind="file";[Mo]="file";identity;name;async openReader(){let e=await D.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");ml(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 D.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async openWriter(){await D.mkdir(W.dirname(this.path),{recursive:!0});let e=`${this.path}.tmp-${cl.randomUUID()}`,n=await D.open(e,"wx"),r=!1;return{write:async a=>{if(r)throw new Error("Cannot write to a closed FileWriter");await ol(n,a)},writeAt:async(a,o)=>{if(r)throw new Error("Cannot write to a closed FileWriter");pl(a),await ol(n,o,a)},commit:async()=>{r||(await n.close(),await D.rename(e,this.path)),r=!0},abort:async()=>{r||(await n.close(),await D.rm(e,{force:!0})),r=!0}}}};Re=class t{constructor(e){this.path=e;this.identity=hl("directory",e),this.name=W.basename(e)}path;async getPhysicalIdentity(){let e=await D.stat(this.path).catch(n=>{if(!(typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT"))throw n});if(e!==void 0)return`${e.dev}:${e.ino}`}kind="directory";[Mo]="directory";identity;name;async getFile(e){$n(e);let n=new se(W.join(this.path,e));try{return(await D.stat(n.path)).isFile()?n:void 0}catch(r){if(typeof r=="object"&&r!==null&&"code"in r&&(r.code==="ENOENT"||r.code==="ENOTDIR"))return;throw r}}async getLastModified(){try{return(await D.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async getDirectory(e){$n(e);let n=new t(W.join(this.path,e));try{return(await D.stat(n.path)).isDirectory()?n:void 0}catch(r){if(typeof r=="object"&&r!==null&&"code"in r&&(r.code==="ENOENT"||r.code==="ENOTDIR"))return;throw r}}async list(){return(await D.readdir(this.path,{withFileTypes:!0})).map(n=>n.isDirectory()?new t(W.join(this.path,n.name)):new se(W.join(this.path,n.name),n.name))}async createFile(e){$n(e),await D.mkdir(this.path,{recursive:!0});let n=new se(W.join(this.path,e));return await D.writeFile(n.path,"",{flag:"wx"}),n}async createDirectory(e){$n(e),await D.mkdir(this.path,{recursive:!0});let n=new t(W.join(this.path,e));return await D.mkdir(n.path),n}async remove(e,n){$n(e),await D.rm(W.join(this.path,e),{force:!0,recursive:n?.recursive===!0})}};Ao=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()})})}};Lo=class extends vi.RandomAccessReader{constructor(n){super();this.handle=n}handle;read(n,r,a,o,s){let d=c=>{if(c===a){s(null);return}on.read(this.handle.fd,n,r+c,a-c,o+c,(u,m)=>{u?s(u):m===0?s(new Error("Unexpected end of ZIP file")):d(c+m)})};d(0)}_readStreamForRange(n,r){let a=this.handle;return Do.from((async function*(){for(let o=n;o<r;){let s=Buffer.allocUnsafe(Math.min(65536,r-o)),{bytesRead:d}=await a.read(s,0,s.length,o);if(d===0)return;o+=d,yield s.subarray(0,d)}})())}};bl={asyncContext:{create:()=>new dl.AsyncLocalStorage},database:{open:Dk},lifecycle:{instanceId:`node-process:${Po.pid}`,isInstanceAlive:t=>{let e=/^node-process:(\d+)$/u.exec(t);if(e===null)return Promise.resolve(void 0);try{return Po.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=_o(t,"directory");return Promise.resolve(e===void 0?void 0:new Re(e))},getFile:t=>{let e=_o(t,"file");return Promise.resolve(e===void 0?void 0:new se(e))},resolveLegacyDirectory:t=>{let e=_o(t,"directory");return Promise.resolve(e===void 0?void 0:new Re(e))}},templates:{createEnvironment:t=>new Ok(new Oo,t)},zip:{open:Mk,write:qk}},Oo=class extends Nk{#e;constructor(e){super(),this.#e=e}getSource(e){let n=xi(e),r=W.join(this.#e??zk(),n);return{noCache:!1,path:n,src:on.readFileSync(r,"utf8")}}}});var Ge=i(()=>{"use strict"});function kl(t){return new TextEncoder().encode(t)}function it(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}var he=i(()=>{"use strict"});import{sha1 as Qk}from"@noble/hashes/legacy.js";import{sha256 as Xk,sha512 as Vk}from"@noble/hashes/sha2.js";function oe(t){let e=Yk(t);return{update(n){return e.update(typeof n=="string"?kl(n):n),this},digest(n){let r=e.digest();return n==="hex"?it(r):r}}}function sn(t){let e=new Uint8Array(t);return globalThis.crypto.getRandomValues(e),e}function at(){if(typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();let t=sn(16);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=it(t);return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function Yk(t){switch(t){case"sha1":return Qk.create();case"sha256":return Xk.create();case"sha512":return Vk.create()}}var M=i(()=>{"use strict";he()});var Ci=i(()=>{"use strict";M()});var El=i(()=>{"use strict";b()});var Il=i(()=>{"use strict";El()});var vl=i(()=>{"use strict"});function ot(t){return t instanceof Error}function dn(t){let e=[],n=new Set,r=t;for(;r!==void 0&&!n.has(r);){if(n.add(r),r instanceof Error){Rl(e,ix(r)),r=r.cause;continue}Rl(e,String(r));break}return e.join(": ")}function ix(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&&ax(n)?`${t.name} (${r})`:n===""?t.name:r===void 0?n:`${n} (${r})`}function ax(t){return/(?:^|[\s:'"(=])\/(?:[^\s/]+\/)*[^\s/]+/u.test(t)||/(?:^|[\s:'"(=])[A-Za-z]:[\\/]/u.test(t)||/\bfile:\/\//iu.test(t)}function Rl(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 fe=i(()=>{"use strict";b()});var Cl=i(()=>{"use strict";fe()});var Tl=i(()=>{"use strict"});import{APICallError as BA}from"ai";var _l=i(()=>{"use strict";b()});var st=i(()=>{"use strict";b()});var Rt,zn=i(()=>{"use strict";Rt=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 jo=i(()=>{"use strict";st()});var Uo=i(()=>{"use strict"});var Pl=i(()=>{"use strict";b()});var qo=i(()=>{"use strict"});import{generateText as yL,streamText as gL}from"ai";var Ll=i(()=>{"use strict";Il();vl();Cl();Tl();_l();st();Hn();zn();Ci();fe();jo();Uo();Pl();qo()});var Ol=i(()=>{"use strict";Ll()});var Ho=i(()=>{"use strict";Ol();jo();Uo();qo()});var cx,$o,Nl,cn=i(()=>{"use strict";cx=Object.freeze(["serial-generation/editor-compress","serial-generation/editor-review","serial-generation/editor-review-guide","serial-generation/reader-choice","serial-generation/reader-extraction"]),$o=Object.freeze({compress:"serial-generation/editor-compress",review:"serial-generation/editor-review",reviewGuide:"serial-generation/editor-review-guide"}),Nl=Object.freeze({choice:"serial-generation/reader-choice",extraction:"serial-generation/reader-extraction"})});var Y,je,X=i(()=>{"use strict";Y=class extends Error{code;details;constructor(e,n,r={},a={}){super(n,a),this.name="WikiGraphError",this.code=e,this.details=r}},je=class extends Y{target;actualVersion;supportedVersion;reason;constructor(e,n,r){let a=n<r?"upgrade-required":"newer-version";super("schema_version_incompatible",`Wiki Graph ${e.kind}${e.kind==="home"?"":` ${e.kind==="archive"?e.path:e.uri}`} schema v${n} is incompatible with supported v${r}.`,{actualVersion:n,supportedVersion:r,reason:a}),this.name="WikiGraphSchemaVersionError",this.target=e,this.actualVersion=n,this.supportedVersion=r,this.reason=a}}});var Jo=i(()=>{"use strict"});async function lx(t){try{return await nt(t)}catch(e){if(ot(e)&&e.code==="ENOENT")return!0;throw e}}function k(t,e){let n=t[e];if(typeof n!="number")throw new TypeError(`Expected ${e} to be a number`);return n}function T(t,e){let n=t[e];if(typeof n!="string")throw new TypeError(`Expected ${e} to be a string`);return n}var ux,z,Ko,x=i(()=>{"use strict";b();fe();ux=900*1e3;z=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 vt(e),o=r.mode==="readwrite"&&r.create&&n.trim()!==""&&await lx(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 = ${ux}`),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=>k(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 Ct(){let t=await _i();if(t===0){await px(await q(C().library,"core.sqlite"),zo);return}if(t!==zo)throw new je({kind:"home"},t,zo)}async function _i(){let t=await ee(C().library,"core.sqlite");if(t===void 0||await hx(t))return 0;let e=await z.open(t,"",{mode:"readonly"});try{if(!await fx(e,"schema_versions"))return 1;let n=await e.queryOne("SELECT version FROM schema_versions WHERE scope = ?",["home"],r=>k(r,"version"))??1;if(!Number.isInteger(n)||n<1)throw new Error("Invalid Wiki Graph home schema version marker.");return n}finally{await e.close()}}async function px(t,e){let n=await z.open(t,"",{create:!0,mode:"readwrite"});try{await n.execute(mx),await n.run(`INSERT INTO schema_versions (scope, version, updated_at)
6
+ var Rk=Object.defineProperty;var i=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ck=(t,e)=>{for(var n in e)Rk(t,n,{get:e[n],enumerable:!0})};async function bi(t){let e=await t.openReader();try{return e.size}finally{await e.close()}}async function nt(t){return await bi(t)===0}async function te(t){return new TextDecoder().decode(await It(t))}async function It(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 ce(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(K(t)){let e=0;for(let n of await t.list())e+=await Ie(n);return e}return await bi(t)}async function rt(t){return await t.getLastModified?.()}function K(t){return t.kind==="directory"}var il=i(()=>{"use strict"});function nn(t){rn().installedPlatform=t}function A(){let{installedPlatform:t}=rn();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 vt(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 ee(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 ve(t,e){let n=Co(e),r=t;for(let a of n){let o=await r.getDirectory(a);if(!o)return;r=o}return r}async function H(t,e){let n=Co(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 q(t,e){let n=Co(e),r=n.pop();if(!r)throw new TypeError("File name must remain relative");let a=await H(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 Co(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 rn(){let t=globalThis,e=t[al];if(e!==void 0)return e;let n={storageContext:new Ro};return Object.defineProperty(t,al,{configurable:!1,enumerable:!1,value:n,writable:!1}),n}function ki(t){rn().installedStorage=t}async function an(t,e){return t===void 0?await e():await rn().storageContext.run(t,e)}function C(){let{installedStorage:t,storageContext:e}=rn(),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 al,Ro,b=i(()=>{"use strict";il();al=Symbol.for("wiki-graph-core.runtime.v1");Ro=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}=rn();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 xi(t){if(_k.test(t))throw new Error(`invalid template name ${t}`);let n=t.replace(Pk,"").replace(Tk,"");if(n.split("/").includes(".."))throw new Error(`invalid template name ${t}`);return`${n}.jinja`}var Tk,_k,Pk,Hn=i(()=>{"use strict";b();Tk=/\.jinja$/iu,_k=/^\.+\//u,Pk=/^\/+/u});var To=i(()=>{"use strict";b();Hn()});import*as dl from"async_hooks";import*as cl from"crypto";import*as on from"fs";import*as D from"fs/promises";import*as ul from"os";import*as W from"path";import*as No from"process";import{Readable as Do,Writable as Ak}from"stream";import{pipeline as Lk}from"stream/promises";import*as Wo from"sqlite3";import*as vi from"yauzl";import*as ll from"yazl";import{Environment as Ok,Loader as Nk}from"nunjucks";async function ol(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 ml(t,e,n){if(pl(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 pl(t){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("File offset must be a non-negative safe integer")}function hl(t,e){return`node-${t}:${Buffer.from(W.resolve(e),"utf8").toString("base64url")}`}function _o(t,e){let n=`node-${e}:`;if(!t.startsWith(n))return W.isAbsolute(t)?t:void 0;try{return Buffer.from(t.slice(n.length),"base64url").toString("utf8")}catch{return}}function $n(t){if(t.length===0||t==="."||t===".."||W.isAbsolute(t)||t.includes("/")||t.includes("\\"))throw new TypeError(`Directory child must be a relative name: ${t}`)}async function Dk(t,e){let n=(e.mode==="readonly"?Jn.OPEN_READONLY:Jn.OPEN_READWRITE|(e.create?Jn.OPEN_CREATE:0))|Jn.OPEN_FULLMUTEX;return new Ao(await Wk(t,n))}async function Wk(t,e){let n=fl(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 Mk(t,e={}){let n=fl(t,"file");if(n===void 0)throw new TypeError("The Node ZIP adapter requires a NodeFile");let r=await D.open(n,"r"),a;try{a=(await r.stat()).size}catch(f){throw await r.close(),f}let o=()=>new Promise((f,w)=>{vi.fromRandomAccessReader(new Lo(r),a,{autoClose:!1,lazyEntries:!0},(p,S)=>{p||S===void 0?w(p??new Error("Cannot open ZIP")):f(S)})});try{(await o()).close()}catch(f){throw await r.close(),f}let s=!1,d=Promise.resolve(),c,u=f=>{if(s)return Promise.reject(new Error("Cannot read a closed ZIP archive"));let w=d.then(async()=>{let p=await o();try{return await f(p)}finally{p.close()}});return d=w.then(()=>{},()=>{}),w},m=(f,w)=>u(async p=>{let S,g,v=!1;if(await Ei(p,R=>{R.fileName===f&&(S=R),sl(R.fileName)===f&&(g!==void 0&&g.fileName!==R.fileName&&(v=!0),g=R)}),(S===void 0||e.entryNameMode==="normalized")&&v){let R=-1,U=await o();try{return await Ei(U,async O=>{if(sl(O.fileName)!==f)return;let N=await o(),V=0;try{await Ei(N,Fe=>{if(Fe.fileName===O.fileName)return!1;V++})}finally{N.close()}V>=R&&(R=V,g=O)}),await w(U,g)}finally{U.close()}}return await w(p,e.entryNameMode==="normalized"?g:S??g)});return{close:()=>(s=!0,c??=d.then(()=>r.close()),c),copyEntry:(f,w)=>m(f,async(p,S)=>S===void 0?!1:(await Fk(p,S,w),!0)),getEntrySize:f=>m(f,(w,p)=>Promise.resolve(p?.uncompressedSize)),listEntries:()=>u(async f=>{let w=new Set;return await Ei(f,p=>{w.add(p.fileName)}),[...w]}),readEntryRange:(f,w,p)=>m(f,async(S,g)=>{if(g!==void 0)return await jk(S,g,w,p)}),readEntry:f=>m(f,async(w,p)=>{if(p!==void 0)return await Gk(w,p)})}}function sl(t){let e=t.replaceAll("\\","/").trim().split("/").filter(n=>n!==""&&n!==".").join("/");return e.split("/").includes("..")?void 0:e}async function Ei(t,e){await new Promise((n,r)=>{let a=()=>{t.off("entry",d),t.off("end",s),t.off("error",o)},o=c=>{a(),r(c)},s=()=>{a(),n()},d=c=>{Promise.resolve().then(()=>c.fileName.endsWith("/")?void 0:e(c)).then(u=>{u===!1?s():t.readEntry()}).catch(u=>o(u instanceof Error?u:new Error("Cannot scan ZIP",{cause:u})))};t.on("entry",d),t.once("end",s),t.once("error",o),t.readEntry()})}async function Fk(t,e,n){let r=await n.openWriter();try{let a=await Ii(t,e);await yl(a,r),await r.commit()}catch(a){throw await r.abort().catch(()=>{}),a}}async function Gk(t,e){return await gl(await Ii(t,e))}async function jk(t,e,n,r){if(ml(n,r,e.uncompressedSize),r===0)return new Uint8Array;if(e.compressionMethod!==0){let o=await Uk(await Ii(t,e),n,r);return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}let a=await gl(await Ii(t,e,{decompress:null,decrypt:null,end:n+r,start:n}));return new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}async function Uk(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 Ii(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 qk(t,e){let n=new ll.ZipFile,r=await t.openWriter(),a=n.outputStream,o=yl(a,r),s={cancelled:!1,complete:!1},d;try{d=Jk(e);let c=Bk(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&&Kk(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 Bk(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(Hk(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($k(r.value),r.value.name,{compress:!1,size:r.value.size})}}function Hk(t){return Do.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 fl(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 $k(t){return Do.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 Jk(t){let e=t[Symbol.asyncIterator];return e===void 0?t[Symbol.iterator]():e.call(t)}function Kk(t){if(t.return!==void 0)try{Promise.resolve(t.return()).catch(()=>{})}catch{}}async function yl(t,e){await Lk(t,new Ak({write:(n,r,a)=>{e.write(n).then(()=>a(),o=>a(o instanceof Error?o:new Error("Cannot stream ZIP archive")))}}))}async function gl(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 zk(){let t=globalThis.__WIKIGRAPH_DATA_DIR__;if(typeof t=="string"&&t!=="")return t;let e=Po.cwd();for(;;){for(let r of[W.join(e,"data"),W.join(e,"packages","core","data")])try{if(on.statSync(r).isDirectory())return r}catch{}let n=W.dirname(e);if(n===e)throw new Error("Could not locate data directory");e=n}}function Fo(t=W.join(ul.homedir(),".wikigraph")){let e=typeof t=="string"?t:t.libraryRoot,n=typeof t=="string"?W.join(t,"documents"):t.documentStoreRoot;return{library:new Re(e),documentStore:new Re(n)}}function wl(t){nn(bl),ki(Fo(t))}function Sl(){try{A()}catch{nn(bl)}try{C()}catch{ki(Fo())}}async function Ri(t,e){return await an(t===void 0?void 0:Fo(t),e)}var Po,Jn,Mo,se,Re,Ao,Lo,bl,Oo,ue=i(()=>{"use strict";To();Po=No.default??No,Jn=Wo.default??Wo,Mo=Symbol.for("wiki-graph-sdk.node-resource.v1"),se=class{constructor(e,n=W.basename(e)){this.path=e;this.identity=hl("file",e),this.name=n}path;async getPhysicalIdentity(){let e=await D.stat(this.path).catch(n=>{if(!(typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT"))throw n});if(e!==void 0)return`${e.dev}:${e.ino}`}kind="file";[Mo]="file";identity;name;async openReader(){let e=await D.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");ml(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 D.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async openWriter(){await D.mkdir(W.dirname(this.path),{recursive:!0});let e=`${this.path}.tmp-${cl.randomUUID()}`,n=await D.open(e,"wx"),r=!1;return{write:async a=>{if(r)throw new Error("Cannot write to a closed FileWriter");await ol(n,a)},writeAt:async(a,o)=>{if(r)throw new Error("Cannot write to a closed FileWriter");pl(a),await ol(n,o,a)},commit:async()=>{r||(await n.close(),await D.rename(e,this.path)),r=!0},abort:async()=>{r||(await n.close(),await D.rm(e,{force:!0})),r=!0}}}};Re=class t{constructor(e){this.path=e;this.identity=hl("directory",e),this.name=W.basename(e)}path;async getPhysicalIdentity(){let e=await D.stat(this.path).catch(n=>{if(!(typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT"))throw n});if(e!==void 0)return`${e.dev}:${e.ino}`}kind="directory";[Mo]="directory";identity;name;async getFile(e){$n(e);let n=new se(W.join(this.path,e));try{return(await D.stat(n.path)).isFile()?n:void 0}catch(r){if(typeof r=="object"&&r!==null&&"code"in r&&(r.code==="ENOENT"||r.code==="ENOTDIR"))return;throw r}}async getLastModified(){try{return(await D.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async getDirectory(e){$n(e);let n=new t(W.join(this.path,e));try{return(await D.stat(n.path)).isDirectory()?n:void 0}catch(r){if(typeof r=="object"&&r!==null&&"code"in r&&(r.code==="ENOENT"||r.code==="ENOTDIR"))return;throw r}}async list(){return(await D.readdir(this.path,{withFileTypes:!0})).map(n=>n.isDirectory()?new t(W.join(this.path,n.name)):new se(W.join(this.path,n.name),n.name))}async createFile(e){$n(e),await D.mkdir(this.path,{recursive:!0});let n=new se(W.join(this.path,e));return await D.writeFile(n.path,"",{flag:"wx"}),n}async createDirectory(e){$n(e),await D.mkdir(this.path,{recursive:!0});let n=new t(W.join(this.path,e));return await D.mkdir(n.path),n}async remove(e,n){$n(e),await D.rm(W.join(this.path,e),{force:!0,recursive:n?.recursive===!0})}};Ao=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()})})}};Lo=class extends vi.RandomAccessReader{constructor(n){super();this.handle=n}handle;read(n,r,a,o,s){let d=c=>{if(c===a){s(null);return}on.read(this.handle.fd,n,r+c,a-c,o+c,(u,m)=>{u?s(u):m===0?s(new Error("Unexpected end of ZIP file")):d(c+m)})};d(0)}_readStreamForRange(n,r){let a=this.handle;return Do.from((async function*(){for(let o=n;o<r;){let s=Buffer.allocUnsafe(Math.min(65536,r-o)),{bytesRead:d}=await a.read(s,0,s.length,o);if(d===0)return;o+=d,yield s.subarray(0,d)}})())}};bl={asyncContext:{create:()=>new dl.AsyncLocalStorage},database:{open:Dk},lifecycle:{instanceId:`node-process:${Po.pid}`,isInstanceAlive:t=>{let e=/^node-process:(\d+)$/u.exec(t);if(e===null)return Promise.resolve(void 0);try{return Po.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=_o(t,"directory");return Promise.resolve(e===void 0?void 0:new Re(e))},getFile:t=>{let e=_o(t,"file");return Promise.resolve(e===void 0?void 0:new se(e))},resolveLegacyDirectory:t=>{let e=_o(t,"directory");return Promise.resolve(e===void 0?void 0:new Re(e))}},templates:{createEnvironment:t=>new Ok(new Oo,t)},zip:{open:Mk,write:qk}},Oo=class extends Nk{#e;constructor(e){super(),this.#e=e}getSource(e){let n=xi(e),r=W.join(this.#e??zk(),n);return{noCache:!1,path:n,src:on.readFileSync(r,"utf8")}}}});var Ge=i(()=>{"use strict"});function kl(t){return new TextEncoder().encode(t)}function it(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}var he=i(()=>{"use strict"});import{sha1 as Qk}from"@noble/hashes/legacy.js";import{sha256 as Xk,sha512 as Vk}from"@noble/hashes/sha2.js";function oe(t){let e=Yk(t);return{update(n){return e.update(typeof n=="string"?kl(n):n),this},digest(n){let r=e.digest();return n==="hex"?it(r):r}}}function sn(t){let e=new Uint8Array(t);return globalThis.crypto.getRandomValues(e),e}function at(){if(typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();let t=sn(16);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=it(t);return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function Yk(t){switch(t){case"sha1":return Qk.create();case"sha256":return Xk.create();case"sha512":return Vk.create()}}var M=i(()=>{"use strict";he()});var Ci=i(()=>{"use strict";M()});var El=i(()=>{"use strict";b()});var Il=i(()=>{"use strict";El()});var vl=i(()=>{"use strict"});function ot(t){return t instanceof Error}function dn(t){let e=[],n=new Set,r=t;for(;r!==void 0&&!n.has(r);){if(n.add(r),r instanceof Error){Rl(e,ix(r)),r=r.cause;continue}Rl(e,String(r));break}return e.join(": ")}function ix(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&&ax(n)?`${t.name} (${r})`:n===""?t.name:r===void 0?n:`${n} (${r})`}function ax(t){return/(?:^|[\s:'"(=])\/(?:[^\s/]+\/)*[^\s/]+/u.test(t)||/(?:^|[\s:'"(=])[A-Za-z]:[\\/]/u.test(t)||/\bfile:\/\//iu.test(t)}function Rl(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 fe=i(()=>{"use strict";b()});var Cl=i(()=>{"use strict";fe()});var Tl=i(()=>{"use strict"});import{APICallError as HA}from"ai";var _l=i(()=>{"use strict";b()});var st=i(()=>{"use strict";b()});var Rt,zn=i(()=>{"use strict";Rt=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 jo=i(()=>{"use strict";st()});var Uo=i(()=>{"use strict"});var Pl=i(()=>{"use strict";b()});var qo=i(()=>{"use strict"});import{generateText as gL,streamText as bL}from"ai";var Ll=i(()=>{"use strict";Il();vl();Cl();Tl();_l();st();Hn();zn();Ci();fe();jo();Uo();Pl();qo()});var Ol=i(()=>{"use strict";Ll()});var Ho=i(()=>{"use strict";Ol();jo();Uo();qo()});var cx,$o,Nl,cn=i(()=>{"use strict";cx=Object.freeze(["serial-generation/editor-compress","serial-generation/editor-review","serial-generation/editor-review-guide","serial-generation/reader-choice","serial-generation/reader-extraction"]),$o=Object.freeze({compress:"serial-generation/editor-compress",review:"serial-generation/editor-review",reviewGuide:"serial-generation/editor-review-guide"}),Nl=Object.freeze({choice:"serial-generation/reader-choice",extraction:"serial-generation/reader-extraction"})});var Y,je,X=i(()=>{"use strict";Y=class extends Error{code;details;constructor(e,n,r={},a={}){super(n,a),this.name="WikiGraphError",this.code=e,this.details=r}},je=class extends Y{target;actualVersion;supportedVersion;reason;constructor(e,n,r){let a=n<r?"upgrade-required":"newer-version";super("schema_version_incompatible",`Wiki Graph ${e.kind}${e.kind==="home"?"":` ${e.kind==="archive"?e.path:e.uri}`} schema v${n} is incompatible with supported v${r}.`,{actualVersion:n,supportedVersion:r,reason:a}),this.name="WikiGraphSchemaVersionError",this.target=e,this.actualVersion=n,this.supportedVersion=r,this.reason=a}}});var Jo=i(()=>{"use strict"});async function lx(t){try{return await nt(t)}catch(e){if(ot(e)&&e.code==="ENOENT")return!0;throw e}}function k(t,e){let n=t[e];if(typeof n!="number")throw new TypeError(`Expected ${e} to be a number`);return n}function T(t,e){let n=t[e];if(typeof n!="string")throw new TypeError(`Expected ${e} to be a string`);return n}var ux,z,Ko,x=i(()=>{"use strict";b();fe();ux=900*1e3;z=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 vt(e),o=r.mode==="readwrite"&&r.create&&n.trim()!==""&&await lx(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 = ${ux}`),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=>k(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 Ct(){let t=await _i();if(t===0){await px(await q(C().library,"core.sqlite"),zo);return}if(t!==zo)throw new je({kind:"home"},t,zo)}async function _i(){let t=await ee(C().library,"core.sqlite");if(t===void 0||await hx(t))return 0;let e=await z.open(t,"",{mode:"readonly"});try{if(!await fx(e,"schema_versions"))return 1;let n=await e.queryOne("SELECT version FROM schema_versions WHERE scope = ?",["home"],r=>k(r,"version"))??1;if(!Number.isInteger(n)||n<1)throw new Error("Invalid Wiki Graph home schema version marker.");return n}finally{await e.close()}}async function px(t,e){let n=await z.open(t,"",{create:!0,mode:"readwrite"});try{await n.execute(mx),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 hx(t){return await nt(t)}async function fx(t,e){return await t.queryOne("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ?",[e],()=>!0)===!0}var zo,JL,mx,Pi=i(()=>{"use strict";b();fe();X();x();zo=5,JL=300*1e3,mx=`
10
+ updated_at = excluded.updated_at`,["home",e,new Date().toISOString()])}finally{await n.close()}}async function hx(t){return await nt(t)}async function fx(t,e){return await t.queryOne("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ?",[e],()=>!0)===!0}var zo,KL,mx,Pi=i(()=>{"use strict";b();fe();X();x();zo=5,KL=300*1e3,mx=`
11
11
  CREATE TABLE IF NOT EXISTS schema_versions (
12
12
  scope TEXT PRIMARY KEY,
13
13
  version INTEGER NOT NULL,
@@ -19,7 +19,7 @@ var Rk=Object.defineProperty;var i=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ck=(t,e)=>{f
19
19
  `,U)}function f(g,v){let R=0,U=new Map;for(let O of g.children??[]){if(Xl(O)){if(d<0||d>=o.length)continue;let V=O.data??"";if(V==="")continue;let Fe=R*2+1,gi=U.get(Fe)??0;U.set(Fe,gi+V.length);let vk=Yl(v,Fe,!0);w(O,vk,gi,V.length);continue}if(!Vl(O))continue;let N=Yl(v,R,!1,O.attribs?.id??O.attribs?.["xml:id"]);R+=1,m(O,N)}}function w(g,v,R,U){if(d<0||d>=o.length)return;let O=g.data??"",N=o[d],V=N?.spineIndex;if(n&&V===void 0)throw new Error(`EPUB section ${N?.id??"unknown"} cannot produce a CFI locator.`);p(d,O,n&&V!==void 0?Zl(V,v,R,R+U):ls,n?R:void 0,n?R+U:void 0)}function p(g,v,R,U,O){let N=a.get(g);N!==void 0&&N.push({locator:R,...O===void 0?{}:{locatorEnd:O},...U===void 0?{}:{locatorStart:U},text:v})}function S(g,v,R){if(g<0||g>=o.length)return;let U=o[g],O=U?.spineIndex;if(n&&O===void 0)throw new Error(`EPUB section ${U?.id??"unknown"} cannot produce a CFI locator.`);p(g,v,n&&O!==void 0?Ux(O,R):ls)}}function Dx(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 Wx(t){let e=[];for(let c of t){let u=Array.from(c.text),m=0;for(let f=0;f<u.length;f+=1){let w=u[f],p=c.locatorStart===void 0?void 0:c.locatorStart+m;m+=w.length;let S=c.locatorEnd===void 0||c.locatorStart===void 0?void 0:c.locatorStart+m;w==="\r"&&u[f+1]===`
20
20
  `?(m+=1,S=c.locatorStart===void 0?void 0:c.locatorStart+m,e.push({baseLocator:c.locator,char:`
21
21
  `,locator:ms(c.locator,p,S),locatorEnd:S,locatorStart:p}),f+=1):e.push({baseLocator:c.locator,char:w,locator:ms(c.locator,p,S),locatorEnd:S,locatorStart:p})}}let n=[],r=0;for(let c of e){if(c.char===`
22
- `){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:ms(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 ms(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=Mx(r);if(a===void 0)throw new Error("EPUB text mapping has an invalid CFI range locator.");return{...t,cfi:`epubcfi(${a.parentPath},${Ql(a.startPath,e)},${Ql(a.endPath,n)})`}}function Mx(t){if(!t.startsWith("epubcfi(")||!t.endsWith(")"))return;let e=Fx(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 Fx(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 Ql(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 Gx(t){return t.name?.toLowerCase()}function Xl(t){return t.type==="text"}function Vl(t){return t.name!==void 0&&t.type!=="directive"}function Yl(t,e,n,r){let a=n?e:(e+1)*2,o=n||r===void 0?"":`[${Bx(r)}]`;return`${t}/${a}${o}`}function Zl(t,e,n,r){let a=im(t),{parentPath:o,textPath:s}=jx(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 jx(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 Ux(t,e){return{cfi:`epubcfi(${qx(t)}${e})`}}function qx(t){return`${im(t)}!`}function im(t){return`/6/${(t+1)*2}`}function Bx(t){return[...t].map(e=>"[]^(),;=".includes(e)?`^${e}`:e).join("")}var Ax,Lx,ls,Mi,am=i(()=>{"use strict";ct();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"]),Lx=new Set(["script","style"]),ls={},Mi=class{#e;#t;constructor(e,n){this.#e=e,this.#t=Ox(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=Dx(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 tm(this.#e,e);return nm(r,n)}}});import{SaxesParser as Hx}from"saxes";function ln(t){let e=new Hx({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 om(r)}function we(t,e){return t.children.find(n=>nr(n.name)===e)}function Be(t,e){return t.children.filter(n=>nr(n.name)===e)}function ne(t,e){return t.attributes[e]}function tr(t){let e=t.text;for(let n of t.children)e+=tr(n);return e}function nr(t){let e=t.indexOf(":");return e===-1?t:t.slice(e+1)}function om(t){return{name:t.name,attributes:Object.freeze({...t.attributes}),children:Object.freeze(t.children.map(om)),text:t.text}}var Fi=i(()=>{"use strict"});async function dm(t){let e=await Kx(t),n=ln(await t.readText(e)),r=zx(ne(n,"version")),a=we(n,"metadata"),o=we(n,"manifest"),s=we(n,"spine"),d=we(n,"guide"),c=Xx(t,e,o),u=new Map([...c.values()].map(v=>[v.path,v])),m=Vx(s,c),f=Yx(t,e,d),w=Qx(a),p=Zx(c),S=eE(c,s),g=tE(c,a);return{version:r,opfPath:e,metadata:{...w,version:Ue,sourceFormat:"epub"},manifest:c,manifestByPath:u,spine:m,navPath:p,ncxPath:S,coverPath:g?.path,coverMediaType:g?.mediaType,guideNonContentPaths:f}}async function Kx(t){let e=ln(await t.readText("META-INF/container.xml")),r=we(e,"rootfiles")?.children.find(o=>nr(o.name)==="rootfile"),a=r===void 0?void 0:ne(r,"full-path");if(a===void 0||a.trim()==="")throw new Error("EPUB container.xml does not contain an OPF rootfile");return a}function zx(t){return t?.trim().startsWith("3")===!0?3:2}function Qx(t){if(t===void 0)return sm();let e=_t(t,"title"),n=_t(t,"creator"),r=_t(t,"language"),a=_t(t,"identifier"),o=_t(t,"publisher"),s=_t(t,"date"),d=_t(t,"description");return{...sm(),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 sm(){return{version:Ue,sourceFormat:"epub",title:null,authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null}}function _t(t,e){return t.children.filter(n=>nr(n.name)===e).map(n=>rE(tr(n))).filter(n=>n!==void 0)}function Xx(t,e,n){let r=new Map;if(n===void 0)return r;for(let a of Be(n,"item")){let o=ne(a,"id"),s=ne(a,"href"),d=ne(a,"media-type")??"";o===void 0||s===void 0||r.set(o,{id:o,path:t.resolveRelativePath(e,s),mediaType:d,properties:new Set((ne(a,"properties")??"").split(/\s+/u).map(c=>c.trim().toLowerCase()).filter(c=>c!==""))})}return r}function Vx(t,e){return t===void 0?[]:Be(t,"itemref").map((n,r)=>{let a=ne(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 Yx(t,e,n){let r=new Set;if(n===void 0)return r;for(let a of Be(n,"reference")){let o=(ne(a,"type")??"").trim().toLowerCase();if(!Jx.has(o))continue;let s=ne(a,"href");s===void 0||s.trim()===""||r.add(t.resolveRelativePath(e,Zn(s).path))}return r}function Zx(t){for(let e of t.values())if(e.properties.has("nav"))return e.path}function eE(t,e){let n=e===void 0?void 0:ne(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 tE(t,e){for(let r of t.values())if(r.properties.has("cover-image")&&r.mediaType.startsWith("image/"))return r;let n=nE(e);if(n!==void 0){let r=t.get(n);if(r?.mediaType.startsWith("image/")===!0)return r}for(let r of $x){let a=t.get(r);if(a?.mediaType.startsWith("image/")===!0)return a}for(let r of t.values())if(r.mediaType.startsWith("image/")&&Qo(r.path).toLowerCase().includes("cover"))return r}function nE(t){if(t!==void 0)for(let e of Be(t,"meta")){if((ne(e,"name")??"").trim().toLowerCase()!=="cover")continue;let r=ne(e,"content");if(r!==void 0&&r.trim()!=="")return r.trim()}}function rE(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var $x,Jx,ps=i(()=>{"use strict";Tt();Yn();er();Fi();$x=["cover-image","coverimg","cover-img","cover"],Jx=new Set(["cover","titlepage","other.titlepage"])});import{parseDocument as iE}from"htmlparser2";async function um(t,e){let n=await oE(t,e)??await sE(t,e)??[];if(n.length===0)return cm(e,new Set);let r=pm(n),a=cm(e,r);return a.length===0?n:[...n,...a]}async function oE(t,e){if(e.navPath===void 0)return;let n=iE(await t.readText(e.navPath),{decodeEntities:!0}),r=hs(n,s=>lt(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=hs(r,s=>lt(s)==="ol");if(a===void 0)return;let o=rr(a).filter(s=>lt(s)==="li").map(s=>lm(t,e.navPath,s)).filter(s=>s!==void 0);return o.length===0?void 0:o}async function sE(t,e){if(e.ncxPath===void 0)return;let n=ln(await t.readText(e.ncxPath)),r=we(n,"navMap");if(r===void 0)return;let a=Be(r,"navPoint").map(o=>mm(t,e.ncxPath,o)).filter(o=>o!==void 0);return a.length===0?void 0:a}function lm(t,e,n){let r=hm(n),a=r===void 0?void 0:gm(fm(r)),o=r!==void 0&&lt(r)==="a"?r.attribs?.href:void 0,s=cE(t,e,o),d=rr(n).filter(c=>lt(c)==="ol").flatMap(c=>rr(c)).filter(c=>lt(c)==="li").map(c=>lm(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 mm(t,e,n){let r=we(n,"navLabel"),a=r===void 0?void 0:we(r,"text"),o=a===void 0?void 0:gm(tr(a)),s=we(n,"content"),d=uE(t,e,ne(s??n,"src")),c=Be(n,"navPoint").map(u=>mm(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 cm(t,e){return t.spine.filter(n=>!dE(t,n.path,e)).filter(n=>!e.has(n.path)).map(n=>({title:lE(n.path),path:n.path,fragment:void 0,children:[]}))}function dE(t,e,n){if(t.guideNonContentPaths.has(e))return!0;let r=fs(e).toLowerCase();return t.navPath===e?!0:aE.has(r)&&!n.has(e)}function pm(t){let e=new Set;for(let n of t){n.path!==void 0&&e.add(n.path);for(let r of pm(n.children))e.add(r)}return e}function cE(t,e,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Zn(n);return{path:r===""?void 0:t.resolveRelativePath(e,r),fragment:a}}function uE(t,e,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Zn(n);return{path:r===""?void 0:t.resolveRelativePath(e,r),fragment:a}}function hs(t,e){if(ym(t)&&e(t))return t;for(let n of t.children??[]){let r=hs(n,e);if(r!==void 0)return r}}function hm(t){for(let e of rr(t)){let n=lt(e);if(n==="a"||n==="span")return e}for(let e of rr(t)){if(lt(e)==="ol")continue;let n=hm(e);if(n!==void 0)return n}}function fm(t){return t.type==="text"?t.data??"":(t.children??[]).map(fm).join("")}function rr(t){return(t.children??[]).filter(ym)}function ym(t){return t.type==="tag"||t.type==="script"||t.type==="style"}function lt(t){return t.name?.toLowerCase()}function lE(t){let e=mE(t),n=fs(t).slice(0,-e.length||void 0).trim();return n===""?void 0:n}function fs(t){return t.replaceAll("\\","/").split("/").at(-1)??""}function mE(t){let e=fs(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n)}function gm(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var aE,bm=i(()=>{"use strict";er();ps();Fi();aE=new Set(["toc.xhtml","nav.xhtml","contents.xhtml","tableofcontents.xhtml","cover.xhtml","titlepage.xhtml"])});function pE(t){if(t.hasEntry("META-INF/encryption.xml"))throw new Error("Encrypted EPUB is not supported: found META-INF/encryption.xml.")}async function hE(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 fE(t,e){let n=new Map;return e.map((r,a)=>wm(t,r,[a],n))}function wm(t,e,n,r){let a=us(e.fragment),o=e.path===void 0?`toc:${n.join(".")}`:t.createSectionId(e.path,a),s=yE(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)=>wm(t,d,[...n,c],r))}}function Sm(t,e){return t.map(n=>{let r=e.get(n.id);return{...n,hasContent:r?.hasContent??!1,wordsCount:r?.wordsCount??0,children:Sm(n.children,e)}})}function yE(t,e){let n=e.get(t)??0;return e.set(t,n+1),n===0?t:`${t}~${n+1}`}function gE(t,e){let n=new Map,r=new Map(e.spine.map(a=>[a.path,a.spineIndex]));for(let a of km(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 km(t){let e=[];for(let n of t)e.push(n),e.push(...km(n.children));return e}var ys,gs,ir,bs,xm=i(()=>{"use strict";er();er();am();bm();ps();ys=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)}},gs=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){pE(e);let n=await dm(e),r={digest:e.digest,mediaType:"application/epub+zip",name:e.name,...n.metadata.identifier===null?{}:{identifier:n.metadata.identifier}},a=await um(e,n),o=fE(e,a),s=gE(o,n),d=await em(e,s),c=Sm(o,d),u=await hE(e,n);return new t(r,n,u,c,new Mi(e,s))}readMeta(){return Promise.resolve(this.#t.metadata)}readCover(){return Promise.resolve(this.#n)}readSections(){return Promise.resolve(this.#r.map(e=>new ys(this,e)))}async openSection(e){return await this.#i.openSection(e)}async openSectionWithProvenance(e){return await this.#i.openSectionWithProvenance(e,this.#e)}},ir=class{get format(){return"epub"}async openSession(e,n){let r=await Wi.open(e);try{let a=await gs.open(r);return await n(a)}finally{await r.close()}}},bs=new ir});var Em=i(()=>{"use strict";xm()});var Im=i(()=>{"use strict";b()});import{SaxesParser as nD}from"saxes";var vm=i(()=>{"use strict";ct();Fi();Im()});var Cm=i(()=>{"use strict";vm()});async function*wE(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 SE(t){let e=t.lastIndexOf("."),n=(e<=0?t:t.slice(0,e)).trim();return n===""?null:n}var bE,ws,Ss,ar,Tm,_m,Pm=i(()=>{"use strict";Yn();bE="root",ws=class{#e;#t;constructor(e,n=bE){this.#e=e,this.#t=n}get id(){return this.#t}get hasContent(){return!0}get title(){}get children(){return[]}open(){return Promise.resolve(wE(this.#e))}},Ss=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,this.#e=new ws(e)}readMeta(){return Promise.resolve({version:Ue,sourceFormat:this.#n,title:SE(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])}},ar=class{#e;constructor(e){this.#e=e}get format(){return this.#e}async openSession(e,n){return await(await e.openReader()).close(),await n(new Ss(e,this.#e))}},Tm=new ar("txt"),_m=new ar("markdown")});var or=i(()=>{"use strict"});import{z as le}from"zod";var hD,fD,Am=i(()=>{"use strict";or();hD=le.object({type:le.literal("artifact"),digest:le.string().regex(/^[0-9a-f]{64}$/iu),mediaType:le.string().min(1),name:le.string().optional(),identifier:le.string().max(1024).optional()}),fD=le.object({type:le.literal("text"),text:le.string(),locator:le.record(le.string(),le.unknown())})});var mt=i(()=>{"use strict";Yn();Em();Cm();Pm();Am();cs()});var ks=i(()=>{"use strict"});var ji=i(()=>{"use strict"});var dr=i(()=>{"use strict";mt();be();ks();ji();ji();X()});var kE,Om,xE,Nm,cr=i(()=>{"use strict";x();or();kE=`
22
+ `){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:ms(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 ms(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=Mx(r);if(a===void 0)throw new Error("EPUB text mapping has an invalid CFI range locator.");return{...t,cfi:`epubcfi(${a.parentPath},${Ql(a.startPath,e)},${Ql(a.endPath,n)})`}}function Mx(t){if(!t.startsWith("epubcfi(")||!t.endsWith(")"))return;let e=Fx(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 Fx(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 Ql(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 Gx(t){return t.name?.toLowerCase()}function Xl(t){return t.type==="text"}function Vl(t){return t.name!==void 0&&t.type!=="directive"}function Yl(t,e,n,r){let a=n?e:(e+1)*2,o=n||r===void 0?"":`[${Bx(r)}]`;return`${t}/${a}${o}`}function Zl(t,e,n,r){let a=im(t),{parentPath:o,textPath:s}=jx(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 jx(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 Ux(t,e){return{cfi:`epubcfi(${qx(t)}${e})`}}function qx(t){return`${im(t)}!`}function im(t){return`/6/${(t+1)*2}`}function Bx(t){return[...t].map(e=>"[]^(),;=".includes(e)?`^${e}`:e).join("")}var Ax,Lx,ls,Mi,am=i(()=>{"use strict";ct();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"]),Lx=new Set(["script","style"]),ls={},Mi=class{#e;#t;constructor(e,n){this.#e=e,this.#t=Ox(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=Dx(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 tm(this.#e,e);return nm(r,n)}}});import{SaxesParser as Hx}from"saxes";function ln(t){let e=new Hx({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 om(r)}function we(t,e){return t.children.find(n=>nr(n.name)===e)}function Be(t,e){return t.children.filter(n=>nr(n.name)===e)}function ne(t,e){return t.attributes[e]}function tr(t){let e=t.text;for(let n of t.children)e+=tr(n);return e}function nr(t){let e=t.indexOf(":");return e===-1?t:t.slice(e+1)}function om(t){return{name:t.name,attributes:Object.freeze({...t.attributes}),children:Object.freeze(t.children.map(om)),text:t.text}}var Fi=i(()=>{"use strict"});async function dm(t){let e=await Kx(t),n=ln(await t.readText(e)),r=zx(ne(n,"version")),a=we(n,"metadata"),o=we(n,"manifest"),s=we(n,"spine"),d=we(n,"guide"),c=Xx(t,e,o),u=new Map([...c.values()].map(v=>[v.path,v])),m=Vx(s,c),f=Yx(t,e,d),w=Qx(a),p=Zx(c),S=eE(c,s),g=tE(c,a);return{version:r,opfPath:e,metadata:{...w,version:Ue,sourceFormat:"epub"},manifest:c,manifestByPath:u,spine:m,navPath:p,ncxPath:S,coverPath:g?.path,coverMediaType:g?.mediaType,guideNonContentPaths:f}}async function Kx(t){let e=ln(await t.readText("META-INF/container.xml")),r=we(e,"rootfiles")?.children.find(o=>nr(o.name)==="rootfile"),a=r===void 0?void 0:ne(r,"full-path");if(a===void 0||a.trim()==="")throw new Error("EPUB container.xml does not contain an OPF rootfile");return a}function zx(t){return t?.trim().startsWith("3")===!0?3:2}function Qx(t){if(t===void 0)return sm();let e=_t(t,"title"),n=_t(t,"creator"),r=_t(t,"language"),a=_t(t,"identifier"),o=_t(t,"publisher"),s=_t(t,"date"),d=_t(t,"description");return{...sm(),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 sm(){return{version:Ue,sourceFormat:"epub",title:null,authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null}}function _t(t,e){return t.children.filter(n=>nr(n.name)===e).map(n=>rE(tr(n))).filter(n=>n!==void 0)}function Xx(t,e,n){let r=new Map;if(n===void 0)return r;for(let a of Be(n,"item")){let o=ne(a,"id"),s=ne(a,"href"),d=ne(a,"media-type")??"";o===void 0||s===void 0||r.set(o,{id:o,path:t.resolveRelativePath(e,s),mediaType:d,properties:new Set((ne(a,"properties")??"").split(/\s+/u).map(c=>c.trim().toLowerCase()).filter(c=>c!==""))})}return r}function Vx(t,e){return t===void 0?[]:Be(t,"itemref").map((n,r)=>{let a=ne(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 Yx(t,e,n){let r=new Set;if(n===void 0)return r;for(let a of Be(n,"reference")){let o=(ne(a,"type")??"").trim().toLowerCase();if(!Jx.has(o))continue;let s=ne(a,"href");s===void 0||s.trim()===""||r.add(t.resolveRelativePath(e,Zn(s).path))}return r}function Zx(t){for(let e of t.values())if(e.properties.has("nav"))return e.path}function eE(t,e){let n=e===void 0?void 0:ne(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 tE(t,e){for(let r of t.values())if(r.properties.has("cover-image")&&r.mediaType.startsWith("image/"))return r;let n=nE(e);if(n!==void 0){let r=t.get(n);if(r?.mediaType.startsWith("image/")===!0)return r}for(let r of $x){let a=t.get(r);if(a?.mediaType.startsWith("image/")===!0)return a}for(let r of t.values())if(r.mediaType.startsWith("image/")&&Qo(r.path).toLowerCase().includes("cover"))return r}function nE(t){if(t!==void 0)for(let e of Be(t,"meta")){if((ne(e,"name")??"").trim().toLowerCase()!=="cover")continue;let r=ne(e,"content");if(r!==void 0&&r.trim()!=="")return r.trim()}}function rE(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var $x,Jx,ps=i(()=>{"use strict";Tt();Yn();er();Fi();$x=["cover-image","coverimg","cover-img","cover"],Jx=new Set(["cover","titlepage","other.titlepage"])});import{parseDocument as iE}from"htmlparser2";async function um(t,e){let n=await oE(t,e)??await sE(t,e)??[];if(n.length===0)return cm(e,new Set);let r=pm(n),a=cm(e,r);return a.length===0?n:[...n,...a]}async function oE(t,e){if(e.navPath===void 0)return;let n=iE(await t.readText(e.navPath),{decodeEntities:!0}),r=hs(n,s=>lt(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=hs(r,s=>lt(s)==="ol");if(a===void 0)return;let o=rr(a).filter(s=>lt(s)==="li").map(s=>lm(t,e.navPath,s)).filter(s=>s!==void 0);return o.length===0?void 0:o}async function sE(t,e){if(e.ncxPath===void 0)return;let n=ln(await t.readText(e.ncxPath)),r=we(n,"navMap");if(r===void 0)return;let a=Be(r,"navPoint").map(o=>mm(t,e.ncxPath,o)).filter(o=>o!==void 0);return a.length===0?void 0:a}function lm(t,e,n){let r=hm(n),a=r===void 0?void 0:gm(fm(r)),o=r!==void 0&&lt(r)==="a"?r.attribs?.href:void 0,s=cE(t,e,o),d=rr(n).filter(c=>lt(c)==="ol").flatMap(c=>rr(c)).filter(c=>lt(c)==="li").map(c=>lm(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 mm(t,e,n){let r=we(n,"navLabel"),a=r===void 0?void 0:we(r,"text"),o=a===void 0?void 0:gm(tr(a)),s=we(n,"content"),d=uE(t,e,ne(s??n,"src")),c=Be(n,"navPoint").map(u=>mm(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 cm(t,e){return t.spine.filter(n=>!dE(t,n.path,e)).filter(n=>!e.has(n.path)).map(n=>({title:lE(n.path),path:n.path,fragment:void 0,children:[]}))}function dE(t,e,n){if(t.guideNonContentPaths.has(e))return!0;let r=fs(e).toLowerCase();return t.navPath===e?!0:aE.has(r)&&!n.has(e)}function pm(t){let e=new Set;for(let n of t){n.path!==void 0&&e.add(n.path);for(let r of pm(n.children))e.add(r)}return e}function cE(t,e,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Zn(n);return{path:r===""?void 0:t.resolveRelativePath(e,r),fragment:a}}function uE(t,e,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Zn(n);return{path:r===""?void 0:t.resolveRelativePath(e,r),fragment:a}}function hs(t,e){if(ym(t)&&e(t))return t;for(let n of t.children??[]){let r=hs(n,e);if(r!==void 0)return r}}function hm(t){for(let e of rr(t)){let n=lt(e);if(n==="a"||n==="span")return e}for(let e of rr(t)){if(lt(e)==="ol")continue;let n=hm(e);if(n!==void 0)return n}}function fm(t){return t.type==="text"?t.data??"":(t.children??[]).map(fm).join("")}function rr(t){return(t.children??[]).filter(ym)}function ym(t){return t.type==="tag"||t.type==="script"||t.type==="style"}function lt(t){return t.name?.toLowerCase()}function lE(t){let e=mE(t),n=fs(t).slice(0,-e.length||void 0).trim();return n===""?void 0:n}function fs(t){return t.replaceAll("\\","/").split("/").at(-1)??""}function mE(t){let e=fs(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n)}function gm(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var aE,bm=i(()=>{"use strict";er();ps();Fi();aE=new Set(["toc.xhtml","nav.xhtml","contents.xhtml","tableofcontents.xhtml","cover.xhtml","titlepage.xhtml"])});function pE(t){if(t.hasEntry("META-INF/encryption.xml"))throw new Error("Encrypted EPUB is not supported: found META-INF/encryption.xml.")}async function hE(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 fE(t,e){let n=new Map;return e.map((r,a)=>wm(t,r,[a],n))}function wm(t,e,n,r){let a=us(e.fragment),o=e.path===void 0?`toc:${n.join(".")}`:t.createSectionId(e.path,a),s=yE(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)=>wm(t,d,[...n,c],r))}}function Sm(t,e){return t.map(n=>{let r=e.get(n.id);return{...n,hasContent:r?.hasContent??!1,wordsCount:r?.wordsCount??0,children:Sm(n.children,e)}})}function yE(t,e){let n=e.get(t)??0;return e.set(t,n+1),n===0?t:`${t}~${n+1}`}function gE(t,e){let n=new Map,r=new Map(e.spine.map(a=>[a.path,a.spineIndex]));for(let a of km(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 km(t){let e=[];for(let n of t)e.push(n),e.push(...km(n.children));return e}var ys,gs,ir,bs,xm=i(()=>{"use strict";er();er();am();bm();ps();ys=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)}},gs=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){pE(e);let n=await dm(e),r={digest:e.digest,mediaType:"application/epub+zip",name:e.name,...n.metadata.identifier===null?{}:{identifier:n.metadata.identifier}},a=await um(e,n),o=fE(e,a),s=gE(o,n),d=await em(e,s),c=Sm(o,d),u=await hE(e,n);return new t(r,n,u,c,new Mi(e,s))}readMeta(){return Promise.resolve(this.#t.metadata)}readCover(){return Promise.resolve(this.#n)}readSections(){return Promise.resolve(this.#r.map(e=>new ys(this,e)))}async openSection(e){return await this.#i.openSection(e)}async openSectionWithProvenance(e){return await this.#i.openSectionWithProvenance(e,this.#e)}},ir=class{get format(){return"epub"}async openSession(e,n){let r=await Wi.open(e);try{let a=await gs.open(r);return await n(a)}finally{await r.close()}}},bs=new ir});var Em=i(()=>{"use strict";xm()});var Im=i(()=>{"use strict";b()});import{SaxesParser as rD}from"saxes";var vm=i(()=>{"use strict";ct();Fi();Im()});var Cm=i(()=>{"use strict";vm()});async function*wE(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 SE(t){let e=t.lastIndexOf("."),n=(e<=0?t:t.slice(0,e)).trim();return n===""?null:n}var bE,ws,Ss,ar,Tm,_m,Pm=i(()=>{"use strict";Yn();bE="root",ws=class{#e;#t;constructor(e,n=bE){this.#e=e,this.#t=n}get id(){return this.#t}get hasContent(){return!0}get title(){}get children(){return[]}open(){return Promise.resolve(wE(this.#e))}},Ss=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,this.#e=new ws(e)}readMeta(){return Promise.resolve({version:Ue,sourceFormat:this.#n,title:SE(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])}},ar=class{#e;constructor(e){this.#e=e}get format(){return this.#e}async openSession(e,n){return await(await e.openReader()).close(),await n(new Ss(e,this.#e))}},Tm=new ar("txt"),_m=new ar("markdown")});var or=i(()=>{"use strict"});import{z as le}from"zod";var fD,yD,Am=i(()=>{"use strict";or();fD=le.object({type:le.literal("artifact"),digest:le.string().regex(/^[0-9a-f]{64}$/iu),mediaType:le.string().min(1),name:le.string().optional(),identifier:le.string().max(1024).optional()}),yD=le.object({type:le.literal("text"),text:le.string(),locator:le.record(le.string(),le.unknown())})});var mt=i(()=>{"use strict";Yn();Em();Cm();Pm();Am();cs()});var ks=i(()=>{"use strict"});var ji=i(()=>{"use strict"});var dr=i(()=>{"use strict";mt();be();ks();ji();ji();X()});var kE,Om,xE,Nm,cr=i(()=>{"use strict";x();or();kE=`
23
23
  id INTEGER PRIMARY KEY AUTOINCREMENT,
24
24
  digest BLOB NOT NULL UNIQUE,
25
25
  short_uid TEXT NOT NULL UNIQUE
@@ -465,7 +465,7 @@ ${xE}
465
465
  updated_at INTEGER NOT NULL,
466
466
  PRIMARY KEY (archive_id, chapter_id)
467
467
  );
468
- `});var Pt=i(()=>{"use strict";x();Te()});var Dm=i(()=>{"use strict";x();Pt()});var Wm=i(()=>{"use strict";x()});var Mm=i(()=>{"use strict";x();Ci()});var Fm=i(()=>{"use strict";x();Te()});var Gm=i(()=>{"use strict";x();Pt()});var jm=i(()=>{"use strict";x();Pt()});var Um=i(()=>{"use strict";x();Pt()});var qm=i(()=>{"use strict";x();Pt()});var Bm=i(()=>{"use strict";x();Pt()});var Jm=i(()=>{"use strict";he();x();or()});var Km=i(()=>{"use strict";x()});var zm=i(()=>{"use strict";x()});var Qm=i(()=>{"use strict";x()});var Xm=i(()=>{"use strict";Km();zm();Qm()});var vs=i(()=>{"use strict";Dm();Wm();Mm();Fm();Gm();jm();Um();qm();Bm();Jm();Xm()});var Rs=i(()=>{"use strict"});var up=i(()=>{"use strict";b()});var lp=i(()=>{"use strict";fe();Xn()});var At=i(()=>{"use strict"});var mp=i(()=>{"use strict";b();x();cr();At()});var pp=i(()=>{"use strict";fe();Rs()});var hp=i(()=>{"use strict"});import{z as Cs}from"zod";var XM,yp=i(()=>{"use strict";b();Yn();cs();dr();x();ts();cr();vs();Te();Rs();up();lp();mp();Xn();pp();hp();XM=Cs.object({mediaType:Cs.string().min(1),path:Cs.string()})});var gp=i(()=>{"use strict"});var _s=i(()=>{"use strict";yp();gp()});var wp=i(()=>{"use strict";as()});var P=i(()=>{"use strict";x();Dl();ts();as();_s();wp();cr();or();vs();Te()});var As=i(()=>{"use strict"});var $e=i(()=>{"use strict";As()});async function xp(t){let e=await _E(t);try{return await TE(e,t),await e.queryOne(`
468
+ `});var Pt=i(()=>{"use strict";x();Te()});var Dm=i(()=>{"use strict";x();Pt()});var Wm=i(()=>{"use strict";x()});var Mm=i(()=>{"use strict";x();Ci()});var Fm=i(()=>{"use strict";x();Te()});var Gm=i(()=>{"use strict";x();Pt()});var jm=i(()=>{"use strict";x();Pt()});var Um=i(()=>{"use strict";x();Pt()});var qm=i(()=>{"use strict";x();Pt()});var Bm=i(()=>{"use strict";x();Pt()});var Jm=i(()=>{"use strict";he();x();or()});var Km=i(()=>{"use strict";x()});var zm=i(()=>{"use strict";x()});var Qm=i(()=>{"use strict";x()});var Xm=i(()=>{"use strict";Km();zm();Qm()});var vs=i(()=>{"use strict";Dm();Wm();Mm();Fm();Gm();jm();Um();qm();Bm();Jm();Xm()});var Rs=i(()=>{"use strict"});var up=i(()=>{"use strict";b()});var lp=i(()=>{"use strict";fe();Xn()});var At=i(()=>{"use strict"});var mp=i(()=>{"use strict";b();x();cr();At()});var pp=i(()=>{"use strict";fe();Rs()});var hp=i(()=>{"use strict"});import{z as Cs}from"zod";var VM,yp=i(()=>{"use strict";b();Yn();cs();dr();x();ts();cr();vs();Te();Rs();up();lp();mp();Xn();pp();hp();VM=Cs.object({mediaType:Cs.string().min(1),path:Cs.string()})});var gp=i(()=>{"use strict"});var _s=i(()=>{"use strict";yp();gp()});var wp=i(()=>{"use strict";as()});var P=i(()=>{"use strict";x();Dl();ts();as();_s();wp();cr();or();vs();Te()});var As=i(()=>{"use strict"});var $e=i(()=>{"use strict";As()});async function xp(t){let e=await _E(t);try{return await TE(e,t),await e.queryOne(`
469
469
  SELECT 1 AS active
470
470
  FROM state_locks
471
471
  WHERE scope = ? AND resource_key = ?
@@ -503,14 +503,14 @@ ${xE}
503
503
  heartbeat_at INTEGER NOT NULL,
504
504
  created_at INTEGER NOT NULL
505
505
  );
506
- `,NE="library",Ep=300*1e3});var DF,Wt=i(()=>{"use strict";b();x();P();$e();he();M();Ot();As();DF=Promise.resolve()});var MF,mr=i(()=>{"use strict";MF=new RegExp("\\p{Script=Han}","u")});var Os=i(()=>{"use strict";he()});var Cp=i(()=>{"use strict"});async function Pp(){let t=await Q("cache/search-index-query-hits.sqlite",_p),e=C().library,n=Ns.get(e);n===void 0&&(n=t.transaction(async()=>await jE(t)).catch(r=>{throw Ns.delete(e),r}),Ns.set(e,n));try{await n}catch(r){throw await t.close(),r}return t}async function jE(t){await t.queryOne("SELECT value FROM query_cache_metadata WHERE key = 'schema_version'",void 0,n=>String(n.value))!==Tp&&await t.execute(`
506
+ `,NE="library",Ep=300*1e3});var WF,Wt=i(()=>{"use strict";b();x();P();$e();he();M();Ot();As();WF=Promise.resolve()});var FF,mr=i(()=>{"use strict";FF=new RegExp("\\p{Script=Han}","u")});var Os=i(()=>{"use strict";he()});var Cp=i(()=>{"use strict"});async function Pp(){let t=await Q("cache/search-index-query-hits.sqlite",_p),e=C().library,n=Ns.get(e);n===void 0&&(n=t.transaction(async()=>await jE(t)).catch(r=>{throw Ns.delete(e),r}),Ns.set(e,n));try{await n}catch(r){throw await t.close(),r}return t}async function jE(t){await t.queryOne("SELECT value FROM query_cache_metadata WHERE key = 'schema_version'",void 0,n=>String(n.value))!==Tp&&await t.execute(`
507
507
  DROP TABLE IF EXISTS query_dense_segment_hits;
508
508
  DROP TABLE IF EXISTS query_text_hits;
509
509
  DROP TABLE IF EXISTS query_object_hits;
510
510
  DROP TABLE IF EXISTS query_runs;
511
511
  DROP TABLE IF EXISTS query_cache_metadata;
512
512
  ${_p}
513
- `)}async function Ap(t){if(t.length===0)return;let e=await Pp();try{await e.transaction(async()=>{for(let n of t)await Lp(e,n)})}finally{await e.close()}}async function Lp(t,e){await UE(t,e),await t.run("DELETE FROM query_runs WHERE query_id = ?",[e])}async function UE(t,e){await t.run("DELETE FROM query_dense_segment_hits WHERE query_id = ?",[e]),await t.run("DELETE FROM query_text_hits WHERE query_id = ?",[e]),await t.run("DELETE FROM query_object_hits WHERE query_id = ?",[e])}var Tp,GE,KF,_p,Ns,Ds=i(()=>{"use strict";x();P();b();Cp();Tp="4",GE=-1,KF=Date.now(),_p=`
513
+ `)}async function Ap(t){if(t.length===0)return;let e=await Pp();try{await e.transaction(async()=>{for(let n of t)await Lp(e,n)})}finally{await e.close()}}async function Lp(t,e){await UE(t,e),await t.run("DELETE FROM query_runs WHERE query_id = ?",[e])}async function UE(t,e){await t.run("DELETE FROM query_dense_segment_hits WHERE query_id = ?",[e]),await t.run("DELETE FROM query_text_hits WHERE query_id = ?",[e]),await t.run("DELETE FROM query_object_hits WHERE query_id = ?",[e])}var Tp,GE,zF,_p,Ns,Ds=i(()=>{"use strict";x();P();b();Cp();Tp="4",GE=-1,zF=Date.now(),_p=`
514
514
  CREATE TABLE IF NOT EXISTS query_cache_metadata (
515
515
  key TEXT PRIMARY KEY,
516
516
  value TEXT NOT NULL
@@ -718,16 +718,16 @@ ON search_sessions(accessed_at DESC, created_at DESC, session_id);
718
718
  FROM search_sessions
719
719
  ORDER BY accessed_at DESC, created_at DESC, session_id
720
720
  LIMIT -1 OFFSET ?
721
- `,[500],e=>T(e,"session_id"))}async function Mp(t){let e=await t.queryOne("PRAGMA page_count",void 0,r=>k(r,"page_count"))??0,n=await t.queryOne("PRAGMA page_size",void 0,r=>k(r,"page_size"))??0;return e*n}var Fp=i(()=>{"use strict";x();Ds();pn();Mt();Ws()});var Ms=i(()=>{"use strict"});var Gp=i(()=>{"use strict";Mt();Ms()});var Hi=i(()=>{"use strict"});var pr=i(()=>{"use strict";x();pn();qi();Gp();Hi()});var jp=i(()=>{"use strict";M();Mt()});var Up=i(()=>{"use strict";x();Os();pn();pr();jp();qi();Mt();Ws()});var qp=i(()=>{"use strict";x();pn();pr()});var Gt=i(()=>{"use strict";Os();Fp();pr();Up();qp();Hi()});var $i=i(()=>{"use strict"});var Ji=i(()=>{"use strict";mt()});var js=i(()=>{"use strict";he()});var Ki=i(()=>{"use strict"});var Us=i(()=>{"use strict";Ki()});var qs=i(()=>{"use strict";Ms();Ki()});var zi=i(()=>{"use strict";$i();js();Us();qs()});var eh=i(()=>{"use strict";$e()});var th=i(()=>{"use strict";$i();Ji();js();Ki();zi();Us();qs();eh()});var F=i(()=>{"use strict";th()});var $s=i(()=>{"use strict"});var Js=i(()=>{"use strict";X();dr();ks();$s()});var nh=i(()=>{"use strict";Js()});var $=i(()=>{"use strict";Js();nh();$s();ji()});var f0,y0,jt=i(()=>{"use strict";M();f0=new RegExp("\\p{Script=Han}+","gu"),y0=new RegExp("^\\p{Script=Han}+$","u")});var Qi=i(()=>{"use strict";M()});var Qs=i(()=>{"use strict";At()});var Xi=i(()=>{"use strict";x();Qs()});var ah=i(()=>{"use strict";jt();Qi();Xi();At()});var sh=i(()=>{"use strict";At()});var dh=i(()=>{"use strict";jt()});var ch=i(()=>{"use strict"});var ed=i(()=>{"use strict";x();ch();Qi()});var lh=i(()=>{"use strict";x();jt();dh();Qs();At();ed();Xi();Ds()});var mh=i(()=>{"use strict";ah();sh();Qi();lh();ed();At();Xi()});var Ke=i(()=>{"use strict";mh();jt()});var Ut=i(()=>{"use strict";$();Ke();jt();Ji()});var br=i(()=>{"use strict"});var ie=i(()=>{"use strict";be();$e();F()});var ke=i(()=>{"use strict";$e();F()});var Pe=i(()=>{"use strict";$();ct();F();ie()});var Le=i(()=>{"use strict";$();Ke();F();ie();ke();Pe();F();Ut()});var bn=i(()=>{"use strict";br();Gt();Ke();Le();ke()});var dd=i(()=>{"use strict";$();mr();F();ie();Pe();ke()});var Sr=i(()=>{"use strict";X()});var Oe=i(()=>{"use strict";$();Sr();F();ie();Pe()});var na=i(()=>{"use strict"});var kr=i(()=>{"use strict";br()});var xr=i(()=>{"use strict";Pe();Oe()});var cd=i(()=>{"use strict";F();Oe();kr();xr()});var vh=i(()=>{"use strict";br();Ke();Ut();F();Le();na();Oe();kr();cd();xr();xr();kr()});var Rh=i(()=>{"use strict";vh();cd();kr();xr()});var Ir=i(()=>{"use strict";Rh()});var Th=i(()=>{"use strict";br();Gt();pr();Hi();F();ie();Pe();Oe();ke();Ir()});var vr=i(()=>{"use strict";ie();Oe();F();ke();Ir();Th()});var md=i(()=>{"use strict";$();F();ie();Pe();Oe();vr();Rr();ke()});var Rr=i(()=>{"use strict";F();ie();Pe();ke();md()});var sa=i(()=>{"use strict";F();Le();ke()});var da=i(()=>{"use strict";F();Ke()});var ca=i(()=>{"use strict";$();mr();Gt();Ke();F();bn();dd();vr();Rr();Le();sa();da()});var wn=i(()=>{"use strict";Ke()});var Wh=i(()=>{"use strict";mr();Gt();F();Ut();bn();dd();vr();Rr();ca();Le();wn()});var Mh=i(()=>{"use strict";Wh();sa();da();ca();bn();Le()});var ua=i(()=>{"use strict";Oe();Ir();ie()});var Cr=i(()=>{"use strict";F()});var ma=i(()=>{"use strict";F();Ut();ie();Le();bn();Ke();Cr()});var hd=i(()=>{"use strict";F();ke();ua();ma();Cr()});var fd=i(()=>{"use strict"});var jh=i(()=>{"use strict";Sr();F();Oe();ua();hd();ma();Cr();fd();ie();na()});var fa=i(()=>{"use strict";jh();hd();ua();ma();Cr();fd()});var yd=i(()=>{"use strict";P();$e();$();Sr();F();Oe();Ir();Rr();ke();fa();ie();Pe()});var Uh=i(()=>{"use strict";P();$();be();$e();he();F();Pe()});var qh=i(()=>{"use strict";yd();fa();ie()});var Ed=i(()=>{"use strict";Mh();yd();fa();Ut();ie();md();vr();Uh();qh()});var Jh=i(()=>{"use strict";Ed()});var tv,Kh=i(()=>{"use strict";he();M();x();P();tv=10080*60*1e3});var zh=i(()=>{"use strict"});var Qh=i(()=>{"use strict";x();Kh();zh()});var Xh=i(()=>{"use strict"});var Vh=i(()=>{"use strict";Qh();Xh()});var yt=i(()=>{"use strict";Jh();Vh();Gt()});var Ne=i(()=>{"use strict"});var ze=i(()=>{"use strict";Ne()});import{z as Td}from"zod";var Dr,ka,_d,qJ,Qe=i(()=>{"use strict";Ne();Dr=1,ka=5,_d=`${JSON.stringify({formatVersion:Dr,schemaVersion:ka})}
722
- `,qJ=Td.object({formatVersion:Td.literal(Dr),schemaVersion:Td.number().int().positive().optional()})});var nf=i(()=>{"use strict";b();ze();Ne();Qe()});var xn=i(()=>{"use strict";b();ze()});var xa=i(()=>{"use strict";b();Ne();Qe();ze();xn();X()});var rf=i(()=>{"use strict";Ne()});var of=i(()=>{"use strict";b();Ne();rf();Qe();ze()});var lf=i(()=>{"use strict";nf();xa();Qe();of()});var pf=i(()=>{"use strict";$e()});var hf=i(()=>{"use strict";X()});var Ra=i(()=>{"use strict"});var Fr=i(()=>{"use strict";Jo();Hn()});var jd=i(()=>{"use strict";b();Ra();Fr()});var ff=i(()=>{"use strict";Fr()});var yf=i(()=>{"use strict";Ra();Fr()});var Ud=i(()=>{"use strict";Fr()});var gf=i(()=>{"use strict";jd();ff();yf();Ud();Ra();X()});var bf=i(()=>{"use strict";jd();gf();Ud()});var wf=i(()=>{"use strict";hf();bf()});var Ca=i(()=>{"use strict";$();X();b();wf();Xe()});var gt=i(()=>{"use strict"});var Ez,Gr=i(()=>{"use strict";b();x();zn();gt();Ez=new Rt(1)});var Bd=i(()=>{"use strict";x();M();gt();Gr()});var Ta=i(()=>{"use strict";b();M()});var Hd=i(()=>{"use strict";M();Gr();Ta()});var Kd=i(()=>{"use strict";b();Qe();Ne();ze();xa();gt();Bd();Hd();Gr();xn()});var vf=i(()=>{"use strict";gt();ze()});var zd=i(()=>{"use strict";b();M();Gr()});var Qd=i(()=>{"use strict";b();M();xa();Qe();ze();gt();Ne();Kd();vf();Bd();zd();Hd();Ta();Lt();xn()});var Rf=i(()=>{"use strict";M();Qd();Kd();zd();gt()});async function _a(t){let e=C().documentStore,n=0,r=0,a=0,o;try{o=await e.list()}catch(d){if(ot(d)&&d.code==="ENOENT")return{freedBytes:a,removed:r,scanned:n};throw d}for(let d of o){if(!K(d)||!d.name.startsWith(".wikg-session-"))continue;n+=1;let c=await rt(d);!t.force&&(c===void 0||t.now-c<vv)||(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())K(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 vv,Cf=i(()=>{"use strict";b();fe();vv=3600*1e3});var Tf=i(()=>{"use strict";x();b();M();gt();Ta()});var Vd=i(()=>{"use strict";Rf();Qd();Cf();Tf()});var Yd=i(()=>{"use strict";Vd()});var _f=i(()=>{"use strict";P();Ca();yt();Yd()});var Pf=i(()=>{"use strict"});var Xe=i(()=>{"use strict";lf();pf();_f();Pf();Yd()});var Af=i(()=>{"use strict"});var Lf=i(()=>{"use strict"});import{sha256 as RX}from"@noble/hashes/sha2.js";var CX,TX,ec=i(()=>{"use strict";CX=new RegExp("\\p{Script=Han}+","gu"),TX=new RegExp("^\\p{Script=Han}+$","u")});var tc=i(()=>{"use strict";ec()});import{z as l}from"zod";function Of(){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:L,sentenceIndexes:l.array(L),type:l.literal("reading-chunk"),weight:l.number(),wordsCount:L})}function Nf(){return l.object({fromChunkId:l.string(),strength:l.string().optional(),toChunkId:l.string(),type:l.literal("reading-edge"),weight:l.number()})}function Df(){return l.object({endSentenceIndex:L,groupId:L,startSentenceIndex:L,type:l.literal("fragment-group")})}function Wf(){return l.object({firstLabel:l.string(),groupId:L,id:l.string(),lastLabel:l.string(),localSnakeId:L,size:L,type:l.literal("snake"),weight:l.number(),wordsCount:L})}function Mf(){return l.object({chunkId:l.string(),position:L,snakeId:l.string(),type:l.literal("snake-chunk")})}function Ff(){return l.object({fromSnakeId:l.string(),toSnakeId:l.string(),type:l.literal("snake-edge"),weight:l.number()})}function Gf(){return l.object({confidence:l.number().optional(),fragmentId:L.optional(),id:l.string(),note:l.string().optional(),qid:l.string(),rangeEnd:L,rangeStart:L,sentenceIndex:L.optional(),surface:l.string(),type:l.literal("mention")})}function Tv(){return l.object({confidence:l.number().optional(),evidenceSentenceIndexes:l.array(L),id:l.string(),note:l.string().optional(),predicate:l.string(),sourceMentionId:l.string(),targetMentionId:l.string(),type:l.literal("mention-link")})}var L,nc,NX,DX,$t=i(()=>{"use strict";L=l.number().int().nonnegative(),nc={sentenceIndex:L,text:l.string(),wordsCount:L},NX=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string().optional(),type:l.literal("job-options")}),l.object({...nc,fragmentId:L.optional(),type:l.literal("source-text")}),l.object({fragmentId:L,summary:l.string(),type:l.literal("source-fragment")}),l.object({...nc,fragmentId:L.optional(),type:l.literal("source-sentence")}),l.object({...nc,type:l.literal("summary-sentence")}),l.object({chapterId:l.number().int(),title:l.string(),type:l.literal("chapter-title")}),Of(),Nf(),Df(),Wf(),Mf(),Ff(),Gf()]),DX=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string(),scope:l.enum(["knowledge-graph","reading-graph"]),type:l.literal("job-parameter")}),Of(),Nf(),Df(),Wf(),Mf(),Ff(),Gf(),Tv(),l.object({position:L,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:L.optional(),text:l.string(),tokens:l.array(l.string()),type:l.literal("lexical-row")}),l.object({dimensions:L,identity:l.string().optional(),model:l.string(),source:l.enum(["source","summary"]),type:l.literal("embedding-metadata"),version:l.literal(1)}),l.object({endSentenceIndex:L,segmentIndex:L,startSentenceIndex:L,text:l.string(),type:l.literal("embedding-segment"),vector:l.array(l.number()),wordsCount:L})])});var rc=i(()=>{"use strict";$t()});var ic=i(()=>{"use strict"});var Jt,ac=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(`
723
- `)});import{jsonrepair as qX}from"jsonrepair";var jf=i(()=>{"use strict"});var Uf=i(()=>{"use strict";ac();ic();jf()});var me=i(()=>{"use strict";ic();ac();Uf()});var Hf=i(()=>{"use strict"});var jr=i(()=>{"use strict"});import{z as Ye}from"zod";var Lv,Ov,hV,sc=i(()=>{"use strict";me();jr();Lv=Ye.object({candidateId:Ye.string().min(1),decision:Ye.enum(["continue","recall","skip_this_time","never_recall"]),qid:Ye.string().nullable().optional()}).strict(),Ov=Ye.object({decisions:Ye.array(Lv),groupId:Ye.string().min(1)}).strict(),hV=Ye.object({groups:Ye.array(Ov)}).strict()});import{z as Ur}from"zod";var Dv,xV,Jf=i(()=>{"use strict";me();jr();sc();Dv=Ur.object({decision:Ur.enum(["keep","reject"]),qid:Ur.string().regex(/^Q[1-9][0-9]*$/)}).strict(),xV=Ur.object({qids:Ur.array(Dv)}).strict()});var dc=i(()=>{"use strict"});import{z as qr}from"zod";var Wv,CV,Kf=i(()=>{"use strict";me();Wv=qr.object({note:qr.string().max(24).optional(),surfaceId:qr.string().min(1)}).strict(),CV=qr.object({protectedSurfaces:qr.array(Wv)}).strict()});var zf=i(()=>{"use strict";dc()});var Qf=i(()=>{"use strict"});var cc=i(()=>{"use strict"});var Xf=i(()=>{"use strict";cc();jr()});var Br=i(()=>{"use strict";Hf();Jf();jr();sc();dc();Kf();zf();Qf();Xf();cc()});var Aa=i(()=>{"use strict"});var Vf=i(()=>{"use strict";Br();Aa()});var Yf=i(()=>{"use strict";Br()});var uc=i(()=>{"use strict"});var Zf=i(()=>{"use strict";Br();Aa();Yf();uc()});function La(t){let e=t.trim();return e===""?[]:Array.from(Gv.segment(e)).map(n=>n.segment.trim()).filter(n=>n!=="")}function xe(t){let e=t.replace(/\s+/gu," ").trim(),n=jv(e),r="";for(let a of n)if(!Uv(a)){if(!Hr(a)){r+=a;continue}r+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return r}function jv(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&&Fv.has(e[e.length-1]??"")&&Hr(e[e.length-2]??"")&&n<t.length-1&&Hr(t[n+1]??"")){e.pop(),n+=1;continue}let a=e[e.length-1]??"",o=t[n+1]??"";a!==""&&o!==""&&Hr(a)&&Hr(o)&&e.push(r),n+=1}return e}function Hr(t){return t!==""&&new RegExp("\\p{Script=Latin}","u").test(t)&&new RegExp("\\p{L}","u").test(t)}function Uv(t){return/[\p{P}\p{S}]/u.test(t)}var Fv,Gv,$r=i(()=>{"use strict";Fv=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),Gv=new Intl.Segmenter(void 0,{granularity:"sentence"})});function mc(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function ty(t,e){let n=Oa(t,2),r=Oa(e,2),a=Oa(t,3),o=Oa(e,3);return(ey(n,r)+ey(a,o))/2}function Oa(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 ey(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 ny(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,f=(n[d]??0)+(s===c?0:1);r[d+1]=Math.min(u,m,f)}[n,r]=[r,n]}return 1-(n[e.length]??Math.max(t.length,e.length))/Math.max(t.length,e.length)}function ry(t,e){return 1-Math.abs(t.length-e.length)/Math.max(t.length,e.length)}function iy(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 ay(t){return` - ${t.occurrenceId} score=${t.score.toFixed(3)}
721
+ `,[500],e=>T(e,"session_id"))}async function Mp(t){let e=await t.queryOne("PRAGMA page_count",void 0,r=>k(r,"page_count"))??0,n=await t.queryOne("PRAGMA page_size",void 0,r=>k(r,"page_size"))??0;return e*n}var Fp=i(()=>{"use strict";x();Ds();pn();Mt();Ws()});var Ms=i(()=>{"use strict"});var Gp=i(()=>{"use strict";Mt();Ms()});var Hi=i(()=>{"use strict"});var pr=i(()=>{"use strict";x();pn();qi();Gp();Hi()});var jp=i(()=>{"use strict";M();Mt()});var Up=i(()=>{"use strict";x();Os();pn();pr();jp();qi();Mt();Ws()});var qp=i(()=>{"use strict";x();pn();pr()});var Gt=i(()=>{"use strict";Os();Fp();pr();Up();qp();Hi()});var $i=i(()=>{"use strict"});var Ji=i(()=>{"use strict";mt()});var js=i(()=>{"use strict";he()});var Ki=i(()=>{"use strict"});var Us=i(()=>{"use strict";Ki()});var qs=i(()=>{"use strict";Ms();Ki()});var zi=i(()=>{"use strict";$i();js();Us();qs()});var eh=i(()=>{"use strict";$e()});var th=i(()=>{"use strict";$i();Ji();js();Ki();zi();Us();qs();eh()});var F=i(()=>{"use strict";th()});var $s=i(()=>{"use strict"});var Js=i(()=>{"use strict";X();dr();ks();$s()});var nh=i(()=>{"use strict";Js()});var $=i(()=>{"use strict";Js();nh();$s();ji()});var y0,g0,jt=i(()=>{"use strict";M();y0=new RegExp("\\p{Script=Han}+","gu"),g0=new RegExp("^\\p{Script=Han}+$","u")});var Qi=i(()=>{"use strict";M()});var Qs=i(()=>{"use strict";At()});var Xi=i(()=>{"use strict";x();Qs()});var ah=i(()=>{"use strict";jt();Qi();Xi();At()});var sh=i(()=>{"use strict";At()});var dh=i(()=>{"use strict";jt()});var ch=i(()=>{"use strict"});var ed=i(()=>{"use strict";x();ch();Qi()});var lh=i(()=>{"use strict";x();jt();dh();Qs();At();ed();Xi();Ds()});var mh=i(()=>{"use strict";ah();sh();Qi();lh();ed();At();Xi()});var Ke=i(()=>{"use strict";mh();jt()});var Ut=i(()=>{"use strict";$();Ke();jt();Ji()});var br=i(()=>{"use strict"});var ie=i(()=>{"use strict";be();$e();F()});var ke=i(()=>{"use strict";$e();F()});var Pe=i(()=>{"use strict";$();ct();F();ie()});var Le=i(()=>{"use strict";$();Ke();F();ie();ke();Pe();F();Ut()});var bn=i(()=>{"use strict";br();Gt();Ke();Le();ke()});var dd=i(()=>{"use strict";$();mr();F();ie();Pe();ke()});var Sr=i(()=>{"use strict";X()});var Oe=i(()=>{"use strict";$();Sr();F();ie();Pe()});var na=i(()=>{"use strict"});var kr=i(()=>{"use strict";br()});var xr=i(()=>{"use strict";Pe();Oe()});var cd=i(()=>{"use strict";F();Oe();kr();xr()});var vh=i(()=>{"use strict";br();Ke();Ut();F();Le();na();Oe();kr();cd();xr();xr();kr()});var Rh=i(()=>{"use strict";vh();cd();kr();xr()});var Ir=i(()=>{"use strict";Rh()});var Th=i(()=>{"use strict";br();Gt();pr();Hi();F();ie();Pe();Oe();ke();Ir()});var vr=i(()=>{"use strict";ie();Oe();F();ke();Ir();Th()});var md=i(()=>{"use strict";$();F();ie();Pe();Oe();vr();Rr();ke()});var Rr=i(()=>{"use strict";F();ie();Pe();ke();md()});var sa=i(()=>{"use strict";F();Le();ke()});var da=i(()=>{"use strict";F();Ke()});var ca=i(()=>{"use strict";$();mr();Gt();Ke();F();bn();dd();vr();Rr();Le();sa();da()});var wn=i(()=>{"use strict";Ke()});var Wh=i(()=>{"use strict";mr();Gt();F();Ut();bn();dd();vr();Rr();ca();Le();wn()});var Mh=i(()=>{"use strict";Wh();sa();da();ca();bn();Le()});var ua=i(()=>{"use strict";Oe();Ir();ie()});var Cr=i(()=>{"use strict";F()});var ma=i(()=>{"use strict";F();Ut();ie();Le();bn();Ke();Cr()});var hd=i(()=>{"use strict";F();ke();ua();ma();Cr()});var fd=i(()=>{"use strict"});var jh=i(()=>{"use strict";Sr();F();Oe();ua();hd();ma();Cr();fd();ie();na()});var fa=i(()=>{"use strict";jh();hd();ua();ma();Cr();fd()});var yd=i(()=>{"use strict";P();$e();$();Sr();F();Oe();Ir();Rr();ke();fa();ie();Pe()});var Uh=i(()=>{"use strict";P();$();be();$e();he();F();Pe()});var qh=i(()=>{"use strict";yd();fa();ie()});var Ed=i(()=>{"use strict";Mh();yd();fa();Ut();ie();md();vr();Uh();qh()});var Jh=i(()=>{"use strict";Ed()});var tv,Kh=i(()=>{"use strict";he();M();x();P();tv=10080*60*1e3});var zh=i(()=>{"use strict"});var Qh=i(()=>{"use strict";x();Kh();zh()});var Xh=i(()=>{"use strict"});var Vh=i(()=>{"use strict";Qh();Xh()});var yt=i(()=>{"use strict";Jh();Vh();Gt()});var Ne=i(()=>{"use strict"});var ze=i(()=>{"use strict";Ne()});import{z as Td}from"zod";var Dr,ka,_d,BJ,Qe=i(()=>{"use strict";Ne();Dr=1,ka=5,_d=`${JSON.stringify({formatVersion:Dr,schemaVersion:ka})}
722
+ `,BJ=Td.object({formatVersion:Td.literal(Dr),schemaVersion:Td.number().int().positive().optional()})});var nf=i(()=>{"use strict";b();ze();Ne();Qe()});var xn=i(()=>{"use strict";b();ze()});var xa=i(()=>{"use strict";b();Ne();Qe();ze();xn();X()});var rf=i(()=>{"use strict";Ne()});var of=i(()=>{"use strict";b();Ne();rf();Qe();ze()});var lf=i(()=>{"use strict";nf();xa();Qe();of()});var pf=i(()=>{"use strict";$e()});var hf=i(()=>{"use strict";X()});var Ra=i(()=>{"use strict"});var Fr=i(()=>{"use strict";Jo();Hn()});var jd=i(()=>{"use strict";b();Ra();Fr()});var ff=i(()=>{"use strict";Fr()});var yf=i(()=>{"use strict";Ra();Fr()});var Ud=i(()=>{"use strict";Fr()});var gf=i(()=>{"use strict";jd();ff();yf();Ud();Ra();X()});var bf=i(()=>{"use strict";jd();gf();Ud()});var wf=i(()=>{"use strict";hf();bf()});var Ca=i(()=>{"use strict";$();X();b();wf();Xe()});var gt=i(()=>{"use strict"});var Iz,Gr=i(()=>{"use strict";b();x();zn();gt();Iz=new Rt(1)});var Bd=i(()=>{"use strict";x();M();gt();Gr()});var Ta=i(()=>{"use strict";b();M()});var Hd=i(()=>{"use strict";M();Gr();Ta()});var Kd=i(()=>{"use strict";b();Qe();Ne();ze();xa();gt();Bd();Hd();Gr();xn()});var vf=i(()=>{"use strict";gt();ze()});var zd=i(()=>{"use strict";b();M();Gr()});var Qd=i(()=>{"use strict";b();M();xa();Qe();ze();gt();Ne();Kd();vf();Bd();zd();Hd();Ta();Lt();xn()});var Rf=i(()=>{"use strict";M();Qd();Kd();zd();gt()});async function _a(t){let e=C().documentStore,n=0,r=0,a=0,o;try{o=await e.list()}catch(d){if(ot(d)&&d.code==="ENOENT")return{freedBytes:a,removed:r,scanned:n};throw d}for(let d of o){if(!K(d)||!d.name.startsWith(".wikg-session-"))continue;n+=1;let c=await rt(d);!t.force&&(c===void 0||t.now-c<vv)||(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())K(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 vv,Cf=i(()=>{"use strict";b();fe();vv=3600*1e3});var Tf=i(()=>{"use strict";x();b();M();gt();Ta()});var Vd=i(()=>{"use strict";Rf();Qd();Cf();Tf()});var Yd=i(()=>{"use strict";Vd()});var _f=i(()=>{"use strict";P();Ca();yt();Yd()});var Pf=i(()=>{"use strict"});var Xe=i(()=>{"use strict";lf();pf();_f();Pf();Yd()});var Af=i(()=>{"use strict"});var Lf=i(()=>{"use strict"});import{sha256 as CX}from"@noble/hashes/sha2.js";var TX,_X,ec=i(()=>{"use strict";TX=new RegExp("\\p{Script=Han}+","gu"),_X=new RegExp("^\\p{Script=Han}+$","u")});var tc=i(()=>{"use strict";ec()});import{z as l}from"zod";function Of(){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:L,sentenceIndexes:l.array(L),type:l.literal("reading-chunk"),weight:l.number(),wordsCount:L})}function Nf(){return l.object({fromChunkId:l.string(),strength:l.string().optional(),toChunkId:l.string(),type:l.literal("reading-edge"),weight:l.number()})}function Df(){return l.object({endSentenceIndex:L,groupId:L,startSentenceIndex:L,type:l.literal("fragment-group")})}function Wf(){return l.object({firstLabel:l.string(),groupId:L,id:l.string(),lastLabel:l.string(),localSnakeId:L,size:L,type:l.literal("snake"),weight:l.number(),wordsCount:L})}function Mf(){return l.object({chunkId:l.string(),position:L,snakeId:l.string(),type:l.literal("snake-chunk")})}function Ff(){return l.object({fromSnakeId:l.string(),toSnakeId:l.string(),type:l.literal("snake-edge"),weight:l.number()})}function Gf(){return l.object({confidence:l.number().optional(),fragmentId:L.optional(),id:l.string(),note:l.string().optional(),qid:l.string(),rangeEnd:L,rangeStart:L,sentenceIndex:L.optional(),surface:l.string(),type:l.literal("mention")})}function Tv(){return l.object({confidence:l.number().optional(),evidenceSentenceIndexes:l.array(L),id:l.string(),note:l.string().optional(),predicate:l.string(),sourceMentionId:l.string(),targetMentionId:l.string(),type:l.literal("mention-link")})}var L,nc,DX,WX,$t=i(()=>{"use strict";L=l.number().int().nonnegative(),nc={sentenceIndex:L,text:l.string(),wordsCount:L},DX=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string().optional(),type:l.literal("job-options")}),l.object({...nc,fragmentId:L.optional(),type:l.literal("source-text")}),l.object({fragmentId:L,summary:l.string(),type:l.literal("source-fragment")}),l.object({...nc,fragmentId:L.optional(),type:l.literal("source-sentence")}),l.object({...nc,type:l.literal("summary-sentence")}),l.object({chapterId:l.number().int(),title:l.string(),type:l.literal("chapter-title")}),Of(),Nf(),Df(),Wf(),Mf(),Ff(),Gf()]),WX=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string(),scope:l.enum(["knowledge-graph","reading-graph"]),type:l.literal("job-parameter")}),Of(),Nf(),Df(),Wf(),Mf(),Ff(),Gf(),Tv(),l.object({position:L,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:L.optional(),text:l.string(),tokens:l.array(l.string()),type:l.literal("lexical-row")}),l.object({dimensions:L,identity:l.string().optional(),model:l.string(),source:l.enum(["source","summary"]),type:l.literal("embedding-metadata"),version:l.literal(1)}),l.object({endSentenceIndex:L,segmentIndex:L,startSentenceIndex:L,text:l.string(),type:l.literal("embedding-segment"),vector:l.array(l.number()),wordsCount:L})])});var rc=i(()=>{"use strict";$t()});var ic=i(()=>{"use strict"});var Jt,ac=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(`
723
+ `)});import{jsonrepair as BX}from"jsonrepair";var jf=i(()=>{"use strict"});var Uf=i(()=>{"use strict";ac();ic();jf()});var me=i(()=>{"use strict";ic();ac();Uf()});var Hf=i(()=>{"use strict"});var jr=i(()=>{"use strict"});import{z as Ye}from"zod";var Lv,Ov,fV,sc=i(()=>{"use strict";me();jr();Lv=Ye.object({candidateId:Ye.string().min(1),decision:Ye.enum(["continue","recall","skip_this_time","never_recall"]),qid:Ye.string().nullable().optional()}).strict(),Ov=Ye.object({decisions:Ye.array(Lv),groupId:Ye.string().min(1)}).strict(),fV=Ye.object({groups:Ye.array(Ov)}).strict()});import{z as Ur}from"zod";var Dv,EV,Jf=i(()=>{"use strict";me();jr();sc();Dv=Ur.object({decision:Ur.enum(["keep","reject"]),qid:Ur.string().regex(/^Q[1-9][0-9]*$/)}).strict(),EV=Ur.object({qids:Ur.array(Dv)}).strict()});var dc=i(()=>{"use strict"});import{z as qr}from"zod";var Wv,TV,Kf=i(()=>{"use strict";me();Wv=qr.object({note:qr.string().max(24).optional(),surfaceId:qr.string().min(1)}).strict(),TV=qr.object({protectedSurfaces:qr.array(Wv)}).strict()});var zf=i(()=>{"use strict";dc()});var Qf=i(()=>{"use strict"});var cc=i(()=>{"use strict"});var Xf=i(()=>{"use strict";cc();jr()});var Br=i(()=>{"use strict";Hf();Jf();jr();sc();dc();Kf();zf();Qf();Xf();cc()});var Aa=i(()=>{"use strict"});var Vf=i(()=>{"use strict";Br();Aa()});var Yf=i(()=>{"use strict";Br()});var uc=i(()=>{"use strict"});var Zf=i(()=>{"use strict";Br();Aa();Yf();uc()});function La(t){let e=t.trim();return e===""?[]:Array.from(Gv.segment(e)).map(n=>n.segment.trim()).filter(n=>n!=="")}function xe(t){let e=t.replace(/\s+/gu," ").trim(),n=jv(e),r="";for(let a of n)if(!Uv(a)){if(!Hr(a)){r+=a;continue}r+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return r}function jv(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&&Fv.has(e[e.length-1]??"")&&Hr(e[e.length-2]??"")&&n<t.length-1&&Hr(t[n+1]??"")){e.pop(),n+=1;continue}let a=e[e.length-1]??"",o=t[n+1]??"";a!==""&&o!==""&&Hr(a)&&Hr(o)&&e.push(r),n+=1}return e}function Hr(t){return t!==""&&new RegExp("\\p{Script=Latin}","u").test(t)&&new RegExp("\\p{L}","u").test(t)}function Uv(t){return/[\p{P}\p{S}]/u.test(t)}var Fv,Gv,$r=i(()=>{"use strict";Fv=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),Gv=new Intl.Segmenter(void 0,{granularity:"sentence"})});function mc(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function ty(t,e){let n=Oa(t,2),r=Oa(e,2),a=Oa(t,3),o=Oa(e,3);return(ey(n,r)+ey(a,o))/2}function Oa(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 ey(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 ny(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,f=(n[d]??0)+(s===c?0:1);r[d+1]=Math.min(u,m,f)}[n,r]=[r,n]}return 1-(n[e.length]??Math.max(t.length,e.length))/Math.max(t.length,e.length)}function ry(t,e){return 1-Math.abs(t.length-e.length)/Math.max(t.length,e.length)}function iy(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 ay(t){return` - ${t.occurrenceId} score=${t.score.toFixed(3)}
724
724
  prev: ${lc(t.prevText)}
725
725
  text: ${lc(t.text,120)}
726
726
  next: ${lc(t.nextText)}`}function lc(t,e=80){let n=t.replace(/\s+/gu," ").trim();return n===""?"(none)":n.length<=e?n:`${n.slice(0,e-3)}...`}var pc=i(()=>{"use strict"});var hc=i(()=>{"use strict"});function sy(t,e,n){return t.mode==="head_tail"?Hv(t,e):fc(t.text??"",e,n)}function Hv(t,e){let n=t.head??"",r=t.tail??"",a=xe(e),o=xe(n),s=xe(r);if(o===""||s==="")return mc();let d=a.indexOf(o),c=a.lastIndexOf(s);if(d!==-1&&c!==-1&&d<=c){let w=o.length+s.length,p=Math.min(1,w/Math.max(1,a.length));return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:c+s.length,matchStart:d,score:.82+.18*p}}let u=fc(n,e,"start_anchor"),m=fc(r,e,"end_anchor"),f=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*f}}function fc(t,e,n){let r=t.trim(),a=e.trim(),o=xe(r),s=xe(a);if(o===""||s==="")return mc();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 p=s.indexOf(o),S=o.length/Math.max(1,s.length),g=oy({candidateNormalized:s,label:n,matchEnd:p+o.length,matchStart:p,queryNormalized:o});return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:p+o.length,matchStart:p,score:Math.min(1,.75+.25*S+g)}}if(o.includes(s)){let p=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*p)}}let d=0,c=-1,u=-1,m=Math.min(s.length,Math.max(o.length,Math.floor(o.length*1.2))),f=Math.min(m,Math.max(1,Math.floor(o.length*.8))),w=new Set(o);for(let p=f;p<=m;p+=1)for(let S=0;S<=s.length-p;S+=1){let g=s.slice(S,S+p),v=new Set(g),R=new Set([...w,...v]).size,U=[...w].filter(V=>v.has(V)).length;if((R===0?0:U/R)<.35)continue;let N=.35*ty(o,g)+.35*iy(o,g)+.2*ny(o,g)+.1*ry(o,g)+oy({candidateNormalized:s,label:n,matchEnd:S+p,matchStart:S,queryNormalized:o});N>d&&(d=Math.min(1,N),c=S,u=S+p)}return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:u,matchStart:c,score:d}}function oy(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 dy=i(()=>{"use strict";$r();pc();hc()});function cy(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 uy(t,e){if(t===void 0)return;if(t.mode==="head_tail"){let r=e==="end_anchor"?yc(t.tail??"","end_anchor"):yc(t.head??"","start_anchor");return r===""?void 0:{mode:"full",text:r}}return{mode:"full",text:yc(t.text??"",e)}}function gc(t){return t.mode==="head_tail"?xe(t.head??"").length+xe(t.tail??"").length:xe(t.text??"").length}function yc(t,e){let n=La(t);return n.length<=1?t.trim():e==="end_anchor"?n[n.length-1]??t.trim():n[0]??t.trim()}var ly=i(()=>{"use strict";$r()});var In,fy=i(()=>{"use strict";dy();ly();pc();hc();In=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,v]=this.parseAnchor(o,"end_anchor");if(v!==void 0)return[void 0,v];c=g}let[u,m,f]=this.resolveAnchor({anchor:s,candidateSentenceIds:n,candidateTexts:r,label:"start_anchor"});if(f!==void 0)return[void 0,f];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[w,p,S]=this.resolveAnchor({anchor:c,candidateSentenceIds:n,candidateTexts:r,label:"end_anchor",minIndex:u.index});return S!==void 0?[void 0,S]:w===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:w.index<u.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${u.occurrenceId} -> ${w.occurrenceId}).`}]:[{confidence:Math.min(u.score,w.score),sentenceIds:n.slice(u.index,w.index+1),strategy:`${m}+${p}`},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,f]=this.parseAnchor(r,"end_anchor");if(f!==void 0)return[void 0,f];let w=e.overrides.end_anchor,[p,S,g]=w===void 0?this.resolveAnchor({anchor:m,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"end_anchor",minIndex:d.index}):[w,"choice_final",void 0];return g!==void 0?[void 0,g]:p===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:p.index<d.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${d.occurrenceId} -> ${p.occurrenceId}).`}]:[{confidence:Math.min(d.score,p.score),sentenceIds:e.candidateSentenceIds.slice(d.index,p.index+1),strategy:`${c}+${S}`},void 0]}parseAnchor(e,n){let[r,a]=cy(e);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:n,message:`Invalid evidence.${n}: ${a}`}]:[uy(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&&gc(e.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&gc(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]??"":"",f=sy(e,c,a);o.push({exactNormalized:f.exactNormalized,exactRaw:f.exactRaw,exactSubstring:f.exactSubstring,index:s,nextText:m,occurrenceId:`S${s+1}`,prevText:u,score:f.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=>ay(s)).join(`
727
727
  `);return{candidates:a,code:n,fieldName:e,message:`${e} is ambiguous. Top candidates:
728
728
  ${o}
729
729
  Please provide a more specific anchor or surrounding context.`}}}});var yy=i(()=>{"use strict"});var gy=i(()=>{"use strict";fy();yy()});var bc,by=i(()=>{"use strict";bc=["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(`
730
- `)});var wc=i(()=>{"use strict"});var wy=i(()=>{"use strict";wc();$r()});var Na=i(()=>{"use strict";gy();by();wc();wy();$r()});var ky=i(()=>{"use strict"});import{z as G}from"zod";var xy,zv,Qv,Xv,n2,r2,Ey=i(()=>{"use strict";me();Na();ky();xy=G.object({head:G.string().optional(),mode:G.enum(["full","head_tail"]).optional(),tail:G.string().optional(),text:G.string().optional()}).strict(),zv=G.object({quote:G.string().optional(),sentence_id:G.string().optional()}).strict(),Qv=G.union([G.object({end_anchor:G.union([G.string(),xy]).optional(),quote:G.string().optional(),sentence_id:G.string().optional(),start_anchor:G.union([G.string(),xy]).optional()}).strict(),G.array(zv)]),Xv=G.object({confidence:G.number().min(0).max(1).optional(),evidence:Qv,predicate:G.string().min(1).max(64),sourceMentionId:G.string().min(1),targetMentionId:G.string().min(1)}).strict(),n2=G.object({relations:G.array(Xv)}).strict(),r2=new In});var Iy=i(()=>{"use strict"});var vy=i(()=>{"use strict"});var Ry=i(()=>{"use strict";Ey();Iy();vy()});var Cy=i(()=>{"use strict";Ry();Aa();uc()});var Jr,vn=i(()=>{"use strict";Jr=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 A2,kc=i(()=>{"use strict";me();$t();Vf();Zf();Cy();Br();vn();A2=["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 Ty=i(()=>{"use strict"});var _y=i(()=>{"use strict"});var Py=i(()=>{"use strict";Ty();_y()});var zt=i(()=>{"use strict"});var Kr=i(()=>{"use strict";me()});var Ly=i(()=>{"use strict";zt();Kr()});var Oy=i(()=>{"use strict";Kr()});var Ny=i(()=>{"use strict"});import{z as E}from"zod";var Dy,eR,Wy,tR,nR,rR,iR,aR,oR,Da=i(()=>{"use strict";zt();Dy=E.object({from:E.union([E.number().int(),E.string()]),strength:E.string().optional(),to:E.union([E.number().int(),E.string()])}),eR=E.object({quote:E.string().optional(),sentence_id:E.string().optional()}).passthrough(),Wy=E.union([E.record(E.string(),E.unknown()),E.array(eR)]),tR=E.object({content:E.string(),evidence:Wy.nullish(),label:E.string(),retention:E.enum(["verbatim","detailed","focused","relevant"]),temp_id:E.string()}).passthrough(),nR=E.object({chunks:E.array(tR),fragment_summary:E.string(),links:E.array(Dy)}),rR=E.object({content:E.string(),evidence:Wy.nullish(),importance:E.enum(["critical","important","helpful"]),label:E.string(),temp_id:E.string()}).passthrough(),iR=E.object({chunk_id:E.number().int(),importance:E.enum(["critical","important","helpful"])}),aR=E.object({chunks:E.array(rR),importance_annotations:E.array(iR),links:E.array(Dy)}),oR=E.object({choice:E.string()})});var My=i(()=>{"use strict";me();Na();Ny();Kr();Da()});var Fy=i(()=>{"use strict";me();zt();Ly();Kr();Oy();My();Da()});var Gy=i(()=>{"use strict";Fy();Da()});var Ec=i(()=>{"use strict"});import{detect as L3,validateISO2 as O3}from"tinyld";var jy=i(()=>{"use strict"});var Uy=i(()=>{"use strict"});import{z as zr}from"zod";var cR,Y3,qy=i(()=>{"use strict";me();Na();Gy();Ec();Ec();jy();Uy();cR=zr.object({content:zr.string(),id:zr.number(),label:zr.string()}),Y3=zr.array(cR)});var By=i(()=>{"use strict";qy()});var Hy=i(()=>{"use strict";Py();By()});var $y=i(()=>{"use strict";Hy()});var Jy=i(()=>{"use strict"});var Ky=i(()=>{"use strict"});var Ic=i(()=>{"use strict";Jy();me();vn();Ky()});var zy=i(()=>{"use strict"});var Qy=i(()=>{"use strict"});var Xy=i(()=>{"use strict";zy();Qy()});var Qr=i(()=>{"use strict"});var W8,M8,Rn=i(()=>{"use strict";zt();W8={critical:9,helpful:1,important:3},M8={detailed:9,focused:3,relevant:1,verbatim:27}});var Cn=i(()=>{"use strict"});var Xr=i(()=>{"use strict"});var vc=i(()=>{"use strict";Cn()});var Rc=i(()=>{"use strict";Rn();Cn();Qr();Xr();vc()});var Cc=i(()=>{"use strict";Qr();Rc();Xr()});var Yy=i(()=>{"use strict";Rn();Cn();Xr()});var Zy=i(()=>{"use strict";Rn();Cn();Qr();Xr();vc()});var eg=i(()=>{"use strict";Cc();Cn();Qr();Yy();Rc();Zy()});var tg=i(()=>{"use strict";eg();Cc()});var ng=i(()=>{"use strict";Rn()});var rg=i(()=>{"use strict";tg();ng()});var ig=i(()=>{"use strict";Xy();rg();Rn()});var Tc=i(()=>{"use strict";$t();vn();$y();Ic();ig()});var ag=i(()=>{"use strict"});var Ma=i(()=>{"use strict"});var og=i(()=>{"use strict";Ma()});var Fa=i(()=>{"use strict"});var l4,dg=i(()=>{"use strict";Ma();Fa();l4=Object.freeze({critical:9,major:3,minor:1})});import{detect as h4,validateISO2 as f4}from"tinyld";var cg=i(()=>{"use strict";Fa()});var ug=i(()=>{"use strict"});var lg=i(()=>{"use strict";zt()});var _c=i(()=>{"use strict";lg()});var mg=i(()=>{"use strict"});import{z as Tn}from"zod";var wR,SR,O4,pg=i(()=>{"use strict";me();Ma();_c();Fa();wR=["critical","major","minor"],SR=Tn.object({problem:Tn.string(),severity:Tn.enum(wR),suggestion:Tn.string().default("")}),O4=Tn.object({issues:Tn.array(SR)})});var hg=i(()=>{"use strict";ag();og();dg();cg();ug();_c();mg();pg()});var Pc=i(()=>{"use strict";$t();vn();zt();Ic();hg()});var fg=i(()=>{"use strict";tc();$t();rc();kc();Tc();Pc()});import{z as B}from"zod";var _n,kR,xR,ER,IR,IZ,yg=i(()=>{"use strict";_n=B.number().finite().nonnegative(),kR=B.enum(["committing","enrichment","grounding","indexing","matching","narrowing","relation-discovery","reading-extraction","screening","summary-compression"]),xR=B.enum(["candidate","char","item","page","qid","record","sentence","window"]),ER=B.object({cacheReadTokens:_n.optional(),inputTokens:_n.optional(),outputTokens:_n.optional()}),IR=B.object({done:_n,force:B.boolean().optional(),phase:kR,phaseDetail:B.string().optional(),total:_n,unit:xR}),IZ=B.discriminatedUnion("event",[B.object({characters:_n,event:B.literal("output-characters")}),B.object({event:B.literal("token-usage"),usage:ER}),B.object({event:B.literal("progress"),progress:IR}),B.object({event:B.literal("artifact"),record:B.unknown()}),B.object({event:B.literal("complete"),revision:B.number().int().nonnegative()}),B.object({event:B.literal("error"),message:B.string()})])});var gg=i(()=>{"use strict"});var bg=i(()=>{"use strict"});var Vr=i(()=>{"use strict";Af();Lf();fg();rc();tc();$t();kc();Tc();Pc();vn();yg();gg();bg();ec()});var wg=i(()=>{"use strict";Vr();wn()});import{z as _}from"zod";var vR,RR,zZ,QZ,XZ,Sg=i(()=>{"use strict";b();vR="wikg-index-output/v1",RR=_.enum(["fts","embedding-source","embedding-summary"]),zZ=_.object({artifactKind:RR,chapterId:_.number().int().nonnegative(),embedding:_.object({dimensions:_.number().int().nonnegative(),identity:_.string().optional(),model:_.string()}).optional(),inputRevision:_.number().int().nonnegative(),protocol:_.literal(vR),type:_.literal("manifest")}),QZ=_.object({metadata:_.record(_.string(),_.unknown()).optional(),objectId:_.string().min(1),objectKind:_.string().min(1),rowId:_.string().min(1),sentenceIndex:_.number().int().nonnegative().optional(),text:_.string(),tokens:_.array(_.string()),type:_.literal("lexical-row")}),XZ=_.object({endSentenceIndex:_.number().int().nonnegative(),segmentIndex:_.number().int().nonnegative(),startSentenceIndex:_.number().int().nonnegative(),text:_.string(),vector:_.array(_.number()),wordsCount:_.number().int().nonnegative(),type:_.literal("segment")})});var Qt=i(()=>{"use strict";wg();Sg()});var Ga=i(()=>{"use strict";P();dr();Ni();Pi();Qt();b();ct();Ne();Qe();ze();xn();Vd();Lt();X();Pi()});var Ac,Lc=i(()=>{"use strict";Ac=["queued","running","canceling","paused","succeeded","failed","canceled"]});async function xg(){return await H(C().library,"jobs/work")}async function Eg(t){let e=await C().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 Yr=i(()=>{"use strict";b()});var Zr=i(()=>{"use strict";M()});var Oc=i(()=>{"use strict"});var ei=i(()=>{"use strict";b()});var Ig,vg=i(()=>{"use strict";Ig=`
730
+ `)});var wc=i(()=>{"use strict"});var wy=i(()=>{"use strict";wc();$r()});var Na=i(()=>{"use strict";gy();by();wc();wy();$r()});var ky=i(()=>{"use strict"});import{z as G}from"zod";var xy,zv,Qv,Xv,r2,i2,Ey=i(()=>{"use strict";me();Na();ky();xy=G.object({head:G.string().optional(),mode:G.enum(["full","head_tail"]).optional(),tail:G.string().optional(),text:G.string().optional()}).strict(),zv=G.object({quote:G.string().optional(),sentence_id:G.string().optional()}).strict(),Qv=G.union([G.object({end_anchor:G.union([G.string(),xy]).optional(),quote:G.string().optional(),sentence_id:G.string().optional(),start_anchor:G.union([G.string(),xy]).optional()}).strict(),G.array(zv)]),Xv=G.object({confidence:G.number().min(0).max(1).optional(),evidence:Qv,predicate:G.string().min(1).max(64),sourceMentionId:G.string().min(1),targetMentionId:G.string().min(1)}).strict(),r2=G.object({relations:G.array(Xv)}).strict(),i2=new In});var Iy=i(()=>{"use strict"});var vy=i(()=>{"use strict"});var Ry=i(()=>{"use strict";Ey();Iy();vy()});var Cy=i(()=>{"use strict";Ry();Aa();uc()});var Jr,vn=i(()=>{"use strict";Jr=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 L2,kc=i(()=>{"use strict";me();$t();Vf();Zf();Cy();Br();vn();L2=["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 Ty=i(()=>{"use strict"});var _y=i(()=>{"use strict"});var Py=i(()=>{"use strict";Ty();_y()});var zt=i(()=>{"use strict"});var Kr=i(()=>{"use strict";me()});var Ly=i(()=>{"use strict";zt();Kr()});var Oy=i(()=>{"use strict";Kr()});var Ny=i(()=>{"use strict"});import{z as E}from"zod";var Dy,eR,Wy,tR,nR,rR,iR,aR,oR,Da=i(()=>{"use strict";zt();Dy=E.object({from:E.union([E.number().int(),E.string()]),strength:E.string().optional(),to:E.union([E.number().int(),E.string()])}),eR=E.object({quote:E.string().optional(),sentence_id:E.string().optional()}).passthrough(),Wy=E.union([E.record(E.string(),E.unknown()),E.array(eR)]),tR=E.object({content:E.string(),evidence:Wy.nullish(),label:E.string(),retention:E.enum(["verbatim","detailed","focused","relevant"]),temp_id:E.string()}).passthrough(),nR=E.object({chunks:E.array(tR),fragment_summary:E.string(),links:E.array(Dy)}),rR=E.object({content:E.string(),evidence:Wy.nullish(),importance:E.enum(["critical","important","helpful"]),label:E.string(),temp_id:E.string()}).passthrough(),iR=E.object({chunk_id:E.number().int(),importance:E.enum(["critical","important","helpful"])}),aR=E.object({chunks:E.array(rR),importance_annotations:E.array(iR),links:E.array(Dy)}),oR=E.object({choice:E.string()})});var My=i(()=>{"use strict";me();Na();Ny();Kr();Da()});var Fy=i(()=>{"use strict";me();zt();Ly();Kr();Oy();My();Da()});var Gy=i(()=>{"use strict";Fy();Da()});var Ec=i(()=>{"use strict"});import{detect as O3,validateISO2 as N3}from"tinyld";var jy=i(()=>{"use strict"});var Uy=i(()=>{"use strict"});import{z as zr}from"zod";var cR,Z3,qy=i(()=>{"use strict";me();Na();Gy();Ec();Ec();jy();Uy();cR=zr.object({content:zr.string(),id:zr.number(),label:zr.string()}),Z3=zr.array(cR)});var By=i(()=>{"use strict";qy()});var Hy=i(()=>{"use strict";Py();By()});var $y=i(()=>{"use strict";Hy()});var Jy=i(()=>{"use strict"});var Ky=i(()=>{"use strict"});var Ic=i(()=>{"use strict";Jy();me();vn();Ky()});var zy=i(()=>{"use strict"});var Qy=i(()=>{"use strict"});var Xy=i(()=>{"use strict";zy();Qy()});var Qr=i(()=>{"use strict"});var M8,F8,Rn=i(()=>{"use strict";zt();M8={critical:9,helpful:1,important:3},F8={detailed:9,focused:3,relevant:1,verbatim:27}});var Cn=i(()=>{"use strict"});var Xr=i(()=>{"use strict"});var vc=i(()=>{"use strict";Cn()});var Rc=i(()=>{"use strict";Rn();Cn();Qr();Xr();vc()});var Cc=i(()=>{"use strict";Qr();Rc();Xr()});var Yy=i(()=>{"use strict";Rn();Cn();Xr()});var Zy=i(()=>{"use strict";Rn();Cn();Qr();Xr();vc()});var eg=i(()=>{"use strict";Cc();Cn();Qr();Yy();Rc();Zy()});var tg=i(()=>{"use strict";eg();Cc()});var ng=i(()=>{"use strict";Rn()});var rg=i(()=>{"use strict";tg();ng()});var ig=i(()=>{"use strict";Xy();rg();Rn()});var Tc=i(()=>{"use strict";$t();vn();$y();Ic();ig()});var ag=i(()=>{"use strict"});var Ma=i(()=>{"use strict"});var og=i(()=>{"use strict";Ma()});var Fa=i(()=>{"use strict"});var m4,dg=i(()=>{"use strict";Ma();Fa();m4=Object.freeze({critical:9,major:3,minor:1})});import{detect as f4,validateISO2 as y4}from"tinyld";var cg=i(()=>{"use strict";Fa()});var ug=i(()=>{"use strict"});var lg=i(()=>{"use strict";zt()});var _c=i(()=>{"use strict";lg()});var mg=i(()=>{"use strict"});import{z as Tn}from"zod";var wR,SR,N4,pg=i(()=>{"use strict";me();Ma();_c();Fa();wR=["critical","major","minor"],SR=Tn.object({problem:Tn.string(),severity:Tn.enum(wR),suggestion:Tn.string().default("")}),N4=Tn.object({issues:Tn.array(SR)})});var hg=i(()=>{"use strict";ag();og();dg();cg();ug();_c();mg();pg()});var Pc=i(()=>{"use strict";$t();vn();zt();Ic();hg()});var fg=i(()=>{"use strict";tc();$t();rc();kc();Tc();Pc()});import{z as B}from"zod";var _n,kR,xR,ER,IR,vZ,yg=i(()=>{"use strict";_n=B.number().finite().nonnegative(),kR=B.enum(["committing","enrichment","grounding","indexing","matching","narrowing","relation-discovery","reading-extraction","screening","summary-compression"]),xR=B.enum(["candidate","char","item","page","qid","record","sentence","window"]),ER=B.object({cacheReadTokens:_n.optional(),inputTokens:_n.optional(),outputTokens:_n.optional()}),IR=B.object({done:_n,force:B.boolean().optional(),phase:kR,phaseDetail:B.string().optional(),total:_n,unit:xR}),vZ=B.discriminatedUnion("event",[B.object({characters:_n,event:B.literal("output-characters")}),B.object({event:B.literal("token-usage"),usage:ER}),B.object({event:B.literal("progress"),progress:IR}),B.object({event:B.literal("artifact"),record:B.unknown()}),B.object({event:B.literal("complete"),revision:B.number().int().nonnegative()}),B.object({event:B.literal("error"),message:B.string()})])});var gg=i(()=>{"use strict"});var bg=i(()=>{"use strict"});var Vr=i(()=>{"use strict";Af();Lf();fg();rc();tc();$t();kc();Tc();Pc();vn();yg();gg();bg();ec()});var wg=i(()=>{"use strict";Vr();wn()});import{z as _}from"zod";var vR,RR,QZ,XZ,VZ,Sg=i(()=>{"use strict";b();vR="wikg-index-output/v1",RR=_.enum(["fts","embedding-source","embedding-summary"]),QZ=_.object({artifactKind:RR,chapterId:_.number().int().nonnegative(),embedding:_.object({dimensions:_.number().int().nonnegative(),identity:_.string().optional(),model:_.string()}).optional(),inputRevision:_.number().int().nonnegative(),protocol:_.literal(vR),type:_.literal("manifest")}),XZ=_.object({metadata:_.record(_.string(),_.unknown()).optional(),objectId:_.string().min(1),objectKind:_.string().min(1),rowId:_.string().min(1),sentenceIndex:_.number().int().nonnegative().optional(),text:_.string(),tokens:_.array(_.string()),type:_.literal("lexical-row")}),VZ=_.object({endSentenceIndex:_.number().int().nonnegative(),segmentIndex:_.number().int().nonnegative(),startSentenceIndex:_.number().int().nonnegative(),text:_.string(),vector:_.array(_.number()),wordsCount:_.number().int().nonnegative(),type:_.literal("segment")})});var Qt=i(()=>{"use strict";wg();Sg()});var Ga=i(()=>{"use strict";P();dr();Ni();Pi();Qt();b();ct();Ne();Qe();ze();xn();Vd();Lt();X();Pi()});var Ac,Lc=i(()=>{"use strict";Ac=["queued","running","canceling","paused","succeeded","failed","canceled"]});async function xg(){return await H(C().library,"jobs/work")}async function Eg(t){let e=await C().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 Yr=i(()=>{"use strict";b()});var Zr=i(()=>{"use strict";M()});var Oc=i(()=>{"use strict"});var ei=i(()=>{"use strict";b()});var Ig,vg=i(()=>{"use strict";Ig=`
731
731
  CREATE TABLE IF NOT EXISTS build_jobs (
732
732
  job_id TEXT PRIMARY KEY,
733
733
  archive_key TEXT NOT NULL,
@@ -801,7 +801,7 @@ SELECT *
801
801
  FROM build_jobs
802
802
  WHERE state IN ('succeeded', 'failed', 'canceled')
803
803
  AND updated_at <= ?
804
- `,[n],Vt),o=await Promise.all(a.map(ni)),s=t.dryRun?{freedBytes:0,removed:0,scanned:0}:await Lg(await xg()),d=0;for(let c of o)d+=await bt(c.workspace),d+=await bt(c.cache),d+=await bt(c.log),d+=await bt(c.events),t.dryRun||(await Eg(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 Og=i(()=>{"use strict";Wc();Yr();Ln();Yt()});var Xc=i(()=>{"use strict";Lc();Dc();Pg();Ag();ei();Og()});var Ja=i(()=>{"use strict";Xe();X();On();Wt()});async function Fg(t){let n=await(await C().library.getDirectory("staging"))?.getDirectory("library");if(n===void 0)return{freedBytes:0,removed:0,scanned:0};let r=await XR();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(!K(u)||(s+=1,a.has(u.name)))continue;let m=Number(u.name);if(Number.isInteger(m)&&await Ip(m))continue;let f=await Ie(u);t.dryRun||await n.remove(u.name,{recursive:!0}),d+=1,c+=f}return{freedBytes:c,removed:d,scanned:s}}async function XR(){let t=await Q("core.sqlite","");try{return await t.queryAll("SELECT id FROM libraries",void 0,e=>k(e,"id"))}catch{return}finally{await t.close()}}var Nn=i(()=>{"use strict";M();b();x();$();cr();P();Ja();Ut();wn();jt();On();Wt();Ot();X()});var Gg=i(()=>{"use strict"});var Yc=i(()=>{"use strict";b();he();M()});var YR,X7,On=i(()=>{"use strict";b();x();P();$e();Xe();Qe();Ga();xn();Xe();Lt();Xc();yt();he();M();Wt();Nn();Ot();Gg();Yc();YR=`
804
+ `,[n],Vt),o=await Promise.all(a.map(ni)),s=t.dryRun?{freedBytes:0,removed:0,scanned:0}:await Lg(await xg()),d=0;for(let c of o)d+=await bt(c.workspace),d+=await bt(c.cache),d+=await bt(c.log),d+=await bt(c.events),t.dryRun||(await Eg(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 Og=i(()=>{"use strict";Wc();Yr();Ln();Yt()});var Xc=i(()=>{"use strict";Lc();Dc();Pg();Ag();ei();Og()});var Ja=i(()=>{"use strict";Xe();X();On();Wt()});async function Fg(t){let n=await(await C().library.getDirectory("staging"))?.getDirectory("library");if(n===void 0)return{freedBytes:0,removed:0,scanned:0};let r=await XR();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(!K(u)||(s+=1,a.has(u.name)))continue;let m=Number(u.name);if(Number.isInteger(m)&&await Ip(m))continue;let f=await Ie(u);t.dryRun||await n.remove(u.name,{recursive:!0}),d+=1,c+=f}return{freedBytes:c,removed:d,scanned:s}}async function XR(){let t=await Q("core.sqlite","");try{return await t.queryAll("SELECT id FROM libraries",void 0,e=>k(e,"id"))}catch{return}finally{await t.close()}}var Nn=i(()=>{"use strict";M();b();x();$();cr();P();Ja();Ut();wn();jt();On();Wt();Ot();X()});var Gg=i(()=>{"use strict"});var Yc=i(()=>{"use strict";b();he();M()});var YR,V7,On=i(()=>{"use strict";b();x();P();$e();Xe();Qe();Ga();xn();Xe();Lt();Xc();yt();he();M();Wt();Nn();Ot();Gg();Yc();YR=`
805
805
  id INTEGER PRIMARY KEY AUTOINCREMENT,
806
806
  library_id INTEGER NOT NULL,
807
807
  public_id TEXT NOT NULL,
@@ -815,7 +815,7 @@ WHERE state IN ('succeeded', 'failed', 'canceled')
815
815
  created_at TEXT NOT NULL,
816
816
  updated_at TEXT NOT NULL,
817
817
  UNIQUE(library_id, public_id)
818
- `,X7=`
818
+ `,V7=`
819
819
  CREATE TABLE IF NOT EXISTS library_archives (
820
820
  ${YR}
821
821
  );
@@ -834,7 +834,7 @@ ${YR}
834
834
  `);return{candidates:a,code:n,fieldName:e,message:`${e} is ambiguous. Top candidates:
835
835
  ${o}
836
836
  Please provide a more specific anchor or surrounding context.`}}}});var cb=i(()=>{"use strict"});var ub=i(()=>{"use strict";db();cb()});var Va,lb=i(()=>{"use strict";Va=["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(`
837
- `)});var su=i(()=>{"use strict"});var mb=i(()=>{"use strict";su();ii()});var Wn=i(()=>{"use strict";ub();lb();su();mb();ii()});import{z as ai}from"zod";var Ete,hb=i(()=>{"use strict";Ete=ai.object({meanings:ai.array(ai.object({information:ai.string(),qid:ai.string().regex(/^Q[1-9][0-9]*$/u)}).strict())}).strict()});var oi=i(()=>{"use strict"});var gb=i(()=>{"use strict";oi()});var Za=i(()=>{"use strict"});var Ate,Sb=i(()=>{"use strict";Za();oi();Ate=336*60*60*1e3});var kb=i(()=>{"use strict";Za();oi()});var xb=i(()=>{"use strict";hb();gb();Sb();oi();Za();kb()});async function cu(t){let e=await si.open();try{return await e.gc(t)}finally{await e.close()}}function _C(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 PC(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 CC,TC,si,Eb=i(()=>{"use strict";xb();P();CC=`
837
+ `)});var su=i(()=>{"use strict"});var mb=i(()=>{"use strict";su();ii()});var Wn=i(()=>{"use strict";ub();lb();su();mb();ii()});import{z as ai}from"zod";var Ite,hb=i(()=>{"use strict";Ite=ai.object({meanings:ai.array(ai.object({information:ai.string(),qid:ai.string().regex(/^Q[1-9][0-9]*$/u)}).strict())}).strict()});var oi=i(()=>{"use strict"});var gb=i(()=>{"use strict";oi()});var Za=i(()=>{"use strict"});var Lte,Sb=i(()=>{"use strict";Za();oi();Lte=336*60*60*1e3});var kb=i(()=>{"use strict";Za();oi()});var xb=i(()=>{"use strict";hb();gb();Sb();oi();Za();kb()});async function cu(t){let e=await si.open();try{return await e.gc(t)}finally{await e.close()}}function PC(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 AC(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 TC,_C,si,Eb=i(()=>{"use strict";xb();P();TC=`
838
838
  CREATE TABLE IF NOT EXISTS wikimedia_qid_cache_v2 (
839
839
  qid TEXT PRIMARY KEY,
840
840
  record_json TEXT NOT NULL,
@@ -852,31 +852,31 @@ CREATE TABLE IF NOT EXISTS wikimedia_disambiguation_cache_v2 (
852
852
  record_json TEXT NOT NULL,
853
853
  PRIMARY KEY(qid,wiki,page_id,revision_id,normalizer_version,model_id)
854
854
  );
855
- `,TC=336*60*60*1e3,si=class t{#e;constructor(e){this.#e=e}static async open(){return new t(await Q("cache/cache.sqlite",CC))}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
856
- WHERE qid IN (${e.map(()=>"?").join(",")})`,e,o=>String(o.record_json)),a=new Map;for(let o of r){let s=_C(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)
855
+ `,_C=336*60*60*1e3,si=class t{#e;constructor(e){this.#e=e}static async open(){return new t(await Q("cache/cache.sqlite",TC))}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
856
+ WHERE qid IN (${e.map(()=>"?").join(",")})`,e,o=>String(o.record_json)),a=new Map;for(let o of r){let s=PC(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)
857
857
  VALUES(?,?,?)
858
858
  ON CONFLICT(qid) DO UPDATE SET
859
859
  record_json=excluded.record_json,
860
860
  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
861
861
  WHERE normalizer_version=? AND model_id=?
862
- AND (${a.join(" OR ")})`,[n.normalizerVersion,n.modelId,...o],d=>String(d.record_json))).flatMap(d=>{let c=PC(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(
862
+ AND (${a.join(" OR ")})`,[n.normalizerVersion,n.modelId,...o],d=>String(d.record_json))).flatMap(d=>{let c=AC(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(
863
863
  qid,wiki,page_id,revision_id,normalizer_version,model_id,record_json
864
864
  ) VALUES(?,?,?,?,?,?,?)
865
865
  ON CONFLICT(qid,wiki,page_id,revision_id,normalizer_version,model_id)
866
- 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-TC).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 lu=i(()=>{"use strict";Eb()});var mu=i(()=>{"use strict"});var pu=i(()=>{"use strict"});import{jsonrepair as tne}from"jsonrepair";var Ib=i(()=>{"use strict"});var vb=i(()=>{"use strict";pu();mu();Ib()});var Me=i(()=>{"use strict";mu();pu();vb()});var di=i(()=>{"use strict"});import{z as et}from"zod";var DC,WC,Rne,yu=i(()=>{"use strict";Me();di();DC=et.object({candidateId:et.string().min(1),decision:et.enum(["continue","recall","skip_this_time","never_recall"]),qid:et.string().nullable().optional()}).strict(),WC=et.object({decisions:et.array(DC),groupId:et.string().min(1)}).strict(),Rne=et.object({groups:et.array(WC)}).strict()});import{z as ci}from"zod";var GC,Lne,Tb=i(()=>{"use strict";Me();di();yu();GC=ci.object({decision:ci.enum(["keep","reject"]),qid:ci.string().regex(/^Q[1-9][0-9]*$/)}).strict(),Lne=ci.object({qids:ci.array(GC)}).strict()});var _b=i(()=>{"use strict"});import{z as ui}from"zod";var jC,Mne,Pb=i(()=>{"use strict";Me();jC=ui.object({note:ui.string().max(24).optional(),surfaceId:ui.string().min(1)}).strict(),Mne=ui.object({protectedSurfaces:ui.array(jC)}).strict()});var gu=i(()=>{"use strict"});var Ab=i(()=>{"use strict";gu()});var Lb=i(()=>{"use strict"});var bu=i(()=>{"use strict"});var Ob=i(()=>{"use strict";bu();di()});var St=i(()=>{"use strict";yu();Tb();di();_b();Pb();Ab();gu();Lb();Ob();bu()});var hre,Su=i(()=>{"use strict";cn();hre=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 ku=i(()=>{"use strict";st()});var Fb=i(()=>{"use strict";ku()});var Gb=i(()=>{"use strict";Fb();ku()});var jb=i(()=>{"use strict"});var Ub=i(()=>{"use strict"});var qb=i(()=>{"use strict";jb();Ub()});var li=i(()=>{"use strict";Me()});var Bb=i(()=>{"use strict";P();li()});var Hb=i(()=>{"use strict";li()});var $b=i(()=>{"use strict"});import{z as I}from"zod";var Jb,eT,Kb,tT,nT,rT,iT,aT,oT,eo=i(()=>{"use strict";P();Jb=I.object({from:I.union([I.number().int(),I.string()]),strength:I.string().optional(),to:I.union([I.number().int(),I.string()])}),eT=I.object({quote:I.string().optional(),sentence_id:I.string().optional()}).passthrough(),Kb=I.union([I.record(I.string(),I.unknown()),I.array(eT)]),tT=I.object({content:I.string(),evidence:Kb.nullish(),label:I.string(),retention:I.enum(["verbatim","detailed","focused","relevant"]),temp_id:I.string()}).passthrough(),nT=I.object({chunks:I.array(tT),fragment_summary:I.string(),links:I.array(Jb)}),rT=I.object({content:I.string(),evidence:Kb.nullish(),importance:I.enum(["critical","important","helpful"]),label:I.string(),temp_id:I.string()}).passthrough(),iT=I.object({chunk_id:I.number().int(),importance:I.enum(["critical","important","helpful"])}),aT=I.object({chunks:I.array(rT),importance_annotations:I.array(iT),links:I.array(Jb)}),oT=I.object({choice:I.string()})});var zb=i(()=>{"use strict";Me();Wn();$b();li();eo()});var Qb=i(()=>{"use strict";Me();P();Bb();li();Hb();zb();eo()});var Xb=i(()=>{"use strict";Qb();eo()});var to=i(()=>{"use strict"});import{detect as Iie,validateISO2 as vie}from"tinyld";var xu=i(()=>{"use strict";Ge()});var Vb=i(()=>{"use strict";xu();Ge()});var Yb=i(()=>{"use strict"});import{z as mi}from"zod";var lT,Kie,ew=i(()=>{"use strict";Me();Wn();Xb();to();to();Vb();Yb();lT=mi.object({content:mi.string(),id:mi.number(),label:mi.string()}),Kie=mi.array(lT)});var Eu=i(()=>{"use strict";ew()});var tw=i(()=>{"use strict";ct()});var Iu=i(()=>{"use strict";tw()});var nw=i(()=>{"use strict";qb();Eu();Iu()});var no=i(()=>{"use strict";nw();Iu()});var ro=i(()=>{"use strict"});var io=i(()=>{"use strict";no();ro()});var rw=i(()=>{"use strict";io()});var iw=i(()=>{"use strict"});var ao=i(()=>{"use strict"});var aw=i(()=>{"use strict";ao()});var Fn,Eae,gT,oo=i(()=>{"use strict";Xo();Fn=(r=>(r.Critical="critical",r.Major="major",r.Minor="minor",r))(Fn||{}),Eae=un(Fn),gT=Vn(Fn,"review severity")});var Tae,Ru=i(()=>{"use strict";ao();oo();Tae=Object.freeze({critical:9,major:3,minor:1})});var ow=i(()=>{"use strict";xu();Ge();oo()});var sw=i(()=>{"use strict";b();st();Ru()});var Cu=i(()=>{"use strict";P()});var dw=i(()=>{"use strict"});import{z as Gn}from"zod";var bT,wT,Yae,cw=i(()=>{"use strict";st();Me();ao();Cu();oo();bT=["critical","major","minor"],wT=Gn.object({problem:Gn.string(),severity:Gn.enum(bT),suggestion:Gn.string().default("")}),Yae=Gn.object({issues:Gn.array(wT)})});var uw=i(()=>{"use strict";iw();aw();Ru();ow();sw();Cu();dw();cw()});var Tu=i(()=>{"use strict";uw()});var mw=i(()=>{"use strict"});var pw=i(()=>{"use strict"});var hw=i(()=>{"use strict";mw();pw()});var pi=i(()=>{"use strict"});var Loe,Ooe,jn=i(()=>{"use strict";P();Loe={critical:9,helpful:1,important:3},Ooe={detailed:9,focused:3,relevant:1,verbatim:27}});var Un=i(()=>{"use strict"});var hi=i(()=>{"use strict"});var _u=i(()=>{"use strict";Un()});var Pu=i(()=>{"use strict";jn();Un();pi();hi();_u()});var Au=i(()=>{"use strict";pi();Pu();hi()});var yw=i(()=>{"use strict";jn();Un();hi()});var gw=i(()=>{"use strict";jn();Un();pi();hi();_u()});var bw=i(()=>{"use strict";Au();Un();pi();yw();Pu();gw()});var ww=i(()=>{"use strict";bw();Au()});var Sw=i(()=>{"use strict";jn()});var kw=i(()=>{"use strict";ww();Sw()});var xw=i(()=>{"use strict";hw();kw();jn()});var Ew=i(()=>{"use strict";xw()});var Lu=i(()=>{"use strict";X()});var Iw=i(()=>{"use strict"});var Ou=i(()=>{"use strict";io()});var co=i(()=>{"use strict"});var vw=i(()=>{"use strict";zn();cn();Tu();no();Ew();io();ro();Lu();Iw();Ou();co()});var Rw=i(()=>{"use strict";Lu();co();X()});var Cw=i(()=>{"use strict";rw();vw();ro();Rw();Ou();co()});var qn=i(()=>{"use strict";Cw()});var Tw=i(()=>{"use strict";be();zn();qn();mt()});var _w=i(()=>{"use strict";mt();mt();P();be();Gb();qn();Tw();Ca();b()});var Wu,kt=i(()=>{"use strict";Wu=["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 Mu=i(()=>{"use strict";kt()});var Lw=i(()=>{"use strict";st();Ho();_w();Su();Xe();Mu();b()});var uo=i(()=>{"use strict"});import{z as h}from"zod";var Ow,Z,AT,LT,Nw,OT,NT,DT,WT,MT,FT,GT,jT,UT,qT,BT,HT,$T,JT,Sce,Bn=i(()=>{"use strict";b();Te();uo();Ow=1,Z=h.number().int().nonnegative(),AT=h.literal(Ow),LT=h.string().regex(/^Q[1-9][0-9]*$/u),Nw=h.number().min(0).max(1).optional(),OT=h.object({text:h.string(),wordsCount:Z}).strict(),NT=h.object({type:h.literal("meta"),schemaVersion:AT,chapterId:h.number().int(),stream:h.enum(["knowledge-graph","reading-graph","summary"])}).strict(),DT=h.object({type:h.literal("parameter"),scope:h.enum(["knowledge-graph","reading-graph","summary"]),language:h.string().optional(),prompt:h.string()}).strict(),WT=h.object({type:h.literal("source-fragment"),fragmentId:Z,summary:h.string(),sentences:h.array(OT)}).strict(),MT=h.object({type:h.literal("reading-chunk"),id:h.string().min(1),generation:h.number().int(),sentenceIndex:Z,label:h.string(),content:h.string(),sentenceIndexes:h.array(Z).min(1),retention:h.enum(ye).optional(),importance:h.enum(Ce).optional(),wordsCount:Z,weight:h.number()}).strict(),FT=h.object({type:h.literal("reading-edge"),fromChunkId:h.string().min(1),toChunkId:h.string().min(1),strength:h.string().optional(),weight:h.number()}).strict(),GT=h.object({type:h.literal("fragment-group"),groupId:Z,startSentenceIndex:Z,endSentenceIndex:Z}).strict(),jT=h.object({type:h.literal("snake"),id:h.string().min(1),groupId:Z,localSnakeId:Z,size:Z,firstLabel:h.string(),lastLabel:h.string(),wordsCount:Z,weight:h.number()}).strict(),UT=h.object({type:h.literal("snake-chunk"),snakeId:h.string().min(1),chunkId:h.string().min(1),position:Z}).strict(),qT=h.object({type:h.literal("snake-edge"),fromSnakeId:h.string().min(1),toSnakeId:h.string().min(1),weight:h.number()}).strict(),BT=h.object({type:h.literal("summary"),text:h.string()}).strict(),HT=h.object({type:h.literal("mention"),id:h.string().min(1),fragmentId:Z.optional(),sentenceIndex:Z.optional(),rangeStart:Z,rangeEnd:Z,surface:h.string().min(1),qid:LT,confidence:Nw,note:h.string().optional()}).strict(),$T=h.object({type:h.literal("mention-link"),id:h.string().min(1),sourceMentionId:h.string().min(1),targetMentionId:h.string().min(1),predicate:h.string().min(1),evidenceSentenceIndexes:h.array(Z).min(1),confidence:Nw,note:h.string().optional()}).strict(),JT=h.object({type:h.literal("end")}).strict(),Sce=h.discriminatedUnion("type",[NT,DT,WT,MT,FT,GT,jT,UT,qT,BT,HT,$T,JT])});var Dw=i(()=>{"use strict";Ge();kt()});var Ww=i(()=>{"use strict";P();no()});var Fw=i(()=>{"use strict";b();P();$();qn();Bn();Qt();Dw();Ww()});var lo=i(()=>{"use strict"});var Gw=i(()=>{"use strict";lo()});var jw=i(()=>{"use strict"});var Uw=i(()=>{"use strict";lo()});var qw=i(()=>{"use strict";lo()});var Bw=i(()=>{"use strict";Gw();jw();Uw();qw()});import{z as y}from"zod";var Hw,QT,XT,VT,YT,ZT,e_,t_,n_,r_,i_,$w=i(()=>{"use strict";Te();Hw=y.tuple([y.number(),y.number()]),QT=y.object({text:y.string(),wordsCount:y.number()}),XT=y.object({serialId:y.number(),fragmentId:y.number(),summary:y.string(),sentences:y.array(QT)}),VT=y.object({documentOrder:y.number().optional(),id:y.number(),knowledgeGraphReady:y.boolean(),knowledgeGraphParameterHash:y.string().optional(),revision:y.number().optional(),topologyParameterHash:y.string().optional(),topologyReady:y.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}})),YT=y.object({id:y.number(),generation:y.number(),sentenceId:Hw,label:y.string(),content:y.string(),sentenceIds:y.array(Hw),retention:y.enum(ye).optional(),importance:y.enum(Ce).optional(),wordsCount:y.number(),weight:y.number()}),ZT=y.object({fromId:y.number(),toId:y.number(),strength:y.string().optional(),weight:y.number()}),e_=y.object({id:y.number(),serialId:y.number(),groupId:y.number(),localSnakeId:y.number(),size:y.number(),firstLabel:y.string(),lastLabel:y.string(),wordsCount:y.number(),weight:y.number()}),t_=y.object({snakeId:y.number(),chunkId:y.number(),position:y.number()}),n_=y.object({fromSnakeId:y.number(),toSnakeId:y.number(),weight:y.number()}),r_=y.object({serialId:y.number(),groupId:y.number(),startSentenceIndex:y.number(),endSentenceIndex:y.number()}),i_=y.object({chunks:y.array(YT),fragmentGroups:y.array(r_),fragments:y.array(XT),readingEdges:y.array(ZT),serial:VT,snakeChunks:y.array(t_),snakeEdges:y.array(n_),snakes:y.array(e_)})});var Jw=i(()=>{"use strict";b();$w()});var Kw=i(()=>{"use strict";cn();Tu();X()});var zw=i(()=>{"use strict";b();P();$();Bw();Jw();uo();Kw();Bn();Qt()});var Qw=i(()=>{"use strict"});var mo=i(()=>{"use strict";zw();uo();Qw()});var Xw=i(()=>{"use strict";$();mo()});var Vw=i(()=>{"use strict"});var Yw=i(()=>{"use strict";Fw();Xw();Vw()});var Zw=i(()=>{"use strict";Vr()});var tS=i(()=>{"use strict";Vr();P();$();Qt();mo()});var nS=i(()=>{"use strict";Vr();St();cn()});var rS=i(()=>{"use strict";Yw();mo();Zw();tS();nS()});import{z as J}from"zod";var Ale,o_,Lle,Uu=i(()=>{"use strict";b();Ale=J.object({id:J.string().min(1),chapterId:J.number().int(),sentenceIndex:J.number().int().nonnegative().optional(),rangeStart:J.number().int().nonnegative(),rangeEnd:J.number().int().nonnegative(),surface:J.string().min(1),qid:J.string().regex(/^Q[1-9][0-9]*$/),confidence:J.number().min(0).max(1).optional(),note:J.string().optional()}),o_=J.tuple([J.number().int().nonnegative(),J.number().int().nonnegative()]).readonly(),Lle=J.object({id:J.string().min(1),sourceMentionId:J.string().min(1),targetMentionId:J.string().min(1),predicate:J.string().min(1),evidenceSentenceIds:J.array(o_).min(1),confidence:J.number().min(0).max(1).optional(),note:J.string().optional()})});var qu=i(()=>{"use strict";b();Ge();Bn();Uu()});var aS=i(()=>{"use strict";Bn();Qt();Uu()});var po=i(()=>{"use strict"});var oS=i(()=>{"use strict";St();po()});var Bu=i(()=>{"use strict"});var sS=i(()=>{"use strict";St()});var Hu=i(()=>{"use strict"});var $u=i(()=>{"use strict";St();po();sS();Hu()});var cS=i(()=>{"use strict";$u()});var uS=i(()=>{"use strict";Ge()});var lS=i(()=>{"use strict";Eu();Wn();to()});import{z as j}from"zod";var mS,u_,l_,m_,xme,Eme,pS=i(()=>{"use strict";Me();Wn();lS();mS=j.object({head:j.string().optional(),mode:j.enum(["full","head_tail"]).optional(),tail:j.string().optional(),text:j.string().optional()}).strict(),u_=j.object({quote:j.string().optional(),sentence_id:j.string().optional()}).strict(),l_=j.union([j.object({end_anchor:j.union([j.string(),mS]).optional(),quote:j.string().optional(),sentence_id:j.string().optional(),start_anchor:j.union([j.string(),mS]).optional()}).strict(),j.array(u_)]),m_=j.object({confidence:j.number().min(0).max(1).optional(),evidence:l_,predicate:j.string().min(1).max(64),sourceMentionId:j.string().min(1),targetMentionId:j.string().min(1)}).strict(),xme=j.object({relations:j.array(m_)}).strict(),Eme=new Zt});var hS=i(()=>{"use strict"});var fS=i(()=>{"use strict";pS();hS()});var yS=i(()=>{"use strict";fS();po();Hu()});var Ju=i(()=>{"use strict";$();Bu()});var wS=i(()=>{"use strict";St();kt();qu();oS();Bu();cS();uS();yS();Ju()});var SS=i(()=>{"use strict"});var kS=i(()=>{"use strict";qu();aS();wS();$u();Ju();SS()});var xS=i(()=>{"use strict";kS()});var fi=i(()=>{"use strict";$()});var Ku=i(()=>{"use strict";kt()});var zu=i(()=>{"use strict";Ge();kt();qn();fi();Ku()});var vS=i(()=>{"use strict";kt();fi();zu()});var Qu=i(()=>{"use strict";be();X()});var CS=i(()=>{"use strict";be();dr();mt();Qu();$();$();X()});var TS=i(()=>{"use strict";qn();be();fi();CS();Qu();X()});import{z as tn}from"zod";var _S,ohe,PS=i(()=>{"use strict";_S=tn.object({children:tn.lazy(()=>tn.array(_S)),uri:tn.string().min(1),title:tn.string().nullable().optional()}).strict(),ohe=tn.object({chapters:tn.array(_S)}).strict()});var AS=i(()=>{"use strict";$()});var LS=i(()=>{"use strict";vS();fi();zu();TS();Ku();PS();AS()});var OS=i(()=>{"use strict";Sr()});var tt=i(()=>{"use strict";Lw();yt();Xc();rS();xS();yt();Mu();LS();OS();Ca()});import{AsyncLocalStorage as dP}from"async_hooks";function cP(){let t=globalThis,e=t[VS];if(e!==void 0)return e;let n=new dP;return Object.defineProperty(t,VS,{configurable:!1,enumerable:!1,value:n,writable:!1}),n}async function yi(t,e){return await YS.run(t,e)}function bo(){return YS.getStore()??{cwd:process.cwd(),env:process.env,envPolicy:"production",providers:{}}}var VS,YS,pe=i(()=>{"use strict";VS=Symbol.for("wiki-graph-sdk.runtime-context.v1"),YS=cP()});function ak(t){if(t?.platform===void 0){Sl();return}nn(t.platform)}function ok(t){if(t.host?.storage!==void 0&&t.host.stateDir===void 0)throw new TypeError("Wiki Graph SDK host.storage requires host.stateDir so SDK configuration cannot fall back to the default user state directory.");if(t.stateDir!==void 0&&(t.host?.stateDir!==void 0||t.host?.storage!==void 0))throw new TypeError("Wiki Graph SDK host state/storage and top-level stateDir cannot be used together. Put the state directory in host.stateDir when providing host.storage.")}async function Eo(t,e){let n=bo(),r={...t.host===void 0?n.host===void 0?{}:{host:n.host}:{host:t.host},...t.stateDir===void 0?n.stateDir===void 0?{}:{stateDir:n.stateDir}:{stateDir:t.stateDir}};ok(r),ak(r.host);let a=async()=>await yi({...n,...r.host===void 0?{}:{host:r.host},...r.stateDir===void 0?{}:{stateDir:r.stateDir}},e);return r.host?.storage!==void 0?await an(r.host.storage,a):await Ri(r.host?.stateDir??r.stateDir,a)}var Io=i(()=>{"use strict";To();ue();pe()});async function yk(t="global"){let e=await nl(),n=at(),r=Date.now(),a=!1;try{await e.transaction(async()=>{await FP(e),await e.run(`
866
+ 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-_C).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 lu=i(()=>{"use strict";Eb()});var mu=i(()=>{"use strict"});var pu=i(()=>{"use strict"});import{jsonrepair as tne}from"jsonrepair";var Ib=i(()=>{"use strict"});var vb=i(()=>{"use strict";pu();mu();Ib()});var Me=i(()=>{"use strict";mu();pu();vb()});var di=i(()=>{"use strict"});import{z as et}from"zod";var WC,MC,Rne,yu=i(()=>{"use strict";Me();di();WC=et.object({candidateId:et.string().min(1),decision:et.enum(["continue","recall","skip_this_time","never_recall"]),qid:et.string().nullable().optional()}).strict(),MC=et.object({decisions:et.array(WC),groupId:et.string().min(1)}).strict(),Rne=et.object({groups:et.array(MC)}).strict()});import{z as ci}from"zod";var jC,Lne,Tb=i(()=>{"use strict";Me();di();yu();jC=ci.object({decision:ci.enum(["keep","reject"]),qid:ci.string().regex(/^Q[1-9][0-9]*$/)}).strict(),Lne=ci.object({qids:ci.array(jC)}).strict()});var _b=i(()=>{"use strict"});import{z as ui}from"zod";var UC,Mne,Pb=i(()=>{"use strict";Me();UC=ui.object({note:ui.string().max(24).optional(),surfaceId:ui.string().min(1)}).strict(),Mne=ui.object({protectedSurfaces:ui.array(UC)}).strict()});var gu=i(()=>{"use strict"});var Ab=i(()=>{"use strict";gu()});var Lb=i(()=>{"use strict"});var bu=i(()=>{"use strict"});var Ob=i(()=>{"use strict";bu();di()});var St=i(()=>{"use strict";yu();Tb();di();_b();Pb();Ab();gu();Lb();Ob();bu()});var hre,Su=i(()=>{"use strict";cn();hre=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 ku=i(()=>{"use strict";st()});var Fb=i(()=>{"use strict";ku()});var Gb=i(()=>{"use strict";Fb();ku()});var jb=i(()=>{"use strict"});var Ub=i(()=>{"use strict"});var qb=i(()=>{"use strict";jb();Ub()});var li=i(()=>{"use strict";Me()});var Bb=i(()=>{"use strict";P();li()});var Hb=i(()=>{"use strict";li()});var $b=i(()=>{"use strict"});import{z as I}from"zod";var Jb,tT,Kb,nT,rT,iT,aT,oT,sT,eo=i(()=>{"use strict";P();Jb=I.object({from:I.union([I.number().int(),I.string()]),strength:I.string().optional(),to:I.union([I.number().int(),I.string()])}),tT=I.object({quote:I.string().optional(),sentence_id:I.string().optional()}).passthrough(),Kb=I.union([I.record(I.string(),I.unknown()),I.array(tT)]),nT=I.object({content:I.string(),evidence:Kb.nullish(),label:I.string(),retention:I.enum(["verbatim","detailed","focused","relevant"]),temp_id:I.string()}).passthrough(),rT=I.object({chunks:I.array(nT),fragment_summary:I.string(),links:I.array(Jb)}),iT=I.object({content:I.string(),evidence:Kb.nullish(),importance:I.enum(["critical","important","helpful"]),label:I.string(),temp_id:I.string()}).passthrough(),aT=I.object({chunk_id:I.number().int(),importance:I.enum(["critical","important","helpful"])}),oT=I.object({chunks:I.array(iT),importance_annotations:I.array(aT),links:I.array(Jb)}),sT=I.object({choice:I.string()})});var zb=i(()=>{"use strict";Me();Wn();$b();li();eo()});var Qb=i(()=>{"use strict";Me();P();Bb();li();Hb();zb();eo()});var Xb=i(()=>{"use strict";Qb();eo()});var to=i(()=>{"use strict"});import{detect as Iie,validateISO2 as vie}from"tinyld";var xu=i(()=>{"use strict";Ge()});var Vb=i(()=>{"use strict";xu();Ge()});var Yb=i(()=>{"use strict"});import{z as mi}from"zod";var mT,Kie,ew=i(()=>{"use strict";Me();Wn();Xb();to();to();Vb();Yb();mT=mi.object({content:mi.string(),id:mi.number(),label:mi.string()}),Kie=mi.array(mT)});var Eu=i(()=>{"use strict";ew()});var tw=i(()=>{"use strict";ct()});var Iu=i(()=>{"use strict";tw()});var nw=i(()=>{"use strict";qb();Eu();Iu()});var no=i(()=>{"use strict";nw();Iu()});var ro=i(()=>{"use strict"});var io=i(()=>{"use strict";no();ro()});var rw=i(()=>{"use strict";io()});var iw=i(()=>{"use strict"});var ao=i(()=>{"use strict"});var aw=i(()=>{"use strict";ao()});var Fn,Eae,bT,oo=i(()=>{"use strict";Xo();Fn=(r=>(r.Critical="critical",r.Major="major",r.Minor="minor",r))(Fn||{}),Eae=un(Fn),bT=Vn(Fn,"review severity")});var Tae,Ru=i(()=>{"use strict";ao();oo();Tae=Object.freeze({critical:9,major:3,minor:1})});var ow=i(()=>{"use strict";xu();Ge();oo()});var sw=i(()=>{"use strict";b();st();Ru()});var Cu=i(()=>{"use strict";P()});var dw=i(()=>{"use strict"});import{z as Gn}from"zod";var wT,ST,Yae,cw=i(()=>{"use strict";st();Me();ao();Cu();oo();wT=["critical","major","minor"],ST=Gn.object({problem:Gn.string(),severity:Gn.enum(wT),suggestion:Gn.string().default("")}),Yae=Gn.object({issues:Gn.array(ST)})});var uw=i(()=>{"use strict";iw();aw();Ru();ow();sw();Cu();dw();cw()});var Tu=i(()=>{"use strict";uw()});var mw=i(()=>{"use strict"});var pw=i(()=>{"use strict"});var hw=i(()=>{"use strict";mw();pw()});var pi=i(()=>{"use strict"});var Loe,Ooe,jn=i(()=>{"use strict";P();Loe={critical:9,helpful:1,important:3},Ooe={detailed:9,focused:3,relevant:1,verbatim:27}});var Un=i(()=>{"use strict"});var hi=i(()=>{"use strict"});var _u=i(()=>{"use strict";Un()});var Pu=i(()=>{"use strict";jn();Un();pi();hi();_u()});var Au=i(()=>{"use strict";pi();Pu();hi()});var yw=i(()=>{"use strict";jn();Un();hi()});var gw=i(()=>{"use strict";jn();Un();pi();hi();_u()});var bw=i(()=>{"use strict";Au();Un();pi();yw();Pu();gw()});var ww=i(()=>{"use strict";bw();Au()});var Sw=i(()=>{"use strict";jn()});var kw=i(()=>{"use strict";ww();Sw()});var xw=i(()=>{"use strict";hw();kw();jn()});var Ew=i(()=>{"use strict";xw()});var Lu=i(()=>{"use strict";X()});var Iw=i(()=>{"use strict"});var Ou=i(()=>{"use strict";io()});var co=i(()=>{"use strict"});var vw=i(()=>{"use strict";zn();cn();Tu();no();Ew();io();ro();Lu();Iw();Ou();co()});var Rw=i(()=>{"use strict";Lu();co();X()});var Cw=i(()=>{"use strict";rw();vw();ro();Rw();Ou();co()});var qn=i(()=>{"use strict";Cw()});var Tw=i(()=>{"use strict";be();zn();qn();mt()});var _w=i(()=>{"use strict";mt();mt();P();be();Gb();qn();Tw();Ca();b()});var Wu,kt=i(()=>{"use strict";Wu=["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 Mu=i(()=>{"use strict";kt()});var Lw=i(()=>{"use strict";st();Ho();_w();Su();Xe();Mu();b()});var uo=i(()=>{"use strict"});import{z as h}from"zod";var Ow,Z,LT,OT,Nw,NT,DT,WT,MT,FT,GT,jT,UT,qT,BT,HT,$T,JT,KT,Sce,Bn=i(()=>{"use strict";b();Te();uo();Ow=1,Z=h.number().int().nonnegative(),LT=h.literal(Ow),OT=h.string().regex(/^Q[1-9][0-9]*$/u),Nw=h.number().min(0).max(1).optional(),NT=h.object({text:h.string(),wordsCount:Z}).strict(),DT=h.object({type:h.literal("meta"),schemaVersion:LT,chapterId:h.number().int(),stream:h.enum(["knowledge-graph","reading-graph","summary"])}).strict(),WT=h.object({type:h.literal("parameter"),scope:h.enum(["knowledge-graph","reading-graph","summary"]),language:h.string().optional(),prompt:h.string()}).strict(),MT=h.object({type:h.literal("source-fragment"),fragmentId:Z,summary:h.string(),sentences:h.array(NT)}).strict(),FT=h.object({type:h.literal("reading-chunk"),id:h.string().min(1),generation:h.number().int(),sentenceIndex:Z,label:h.string(),content:h.string(),sentenceIndexes:h.array(Z).min(1),retention:h.enum(ye).optional(),importance:h.enum(Ce).optional(),wordsCount:Z,weight:h.number()}).strict(),GT=h.object({type:h.literal("reading-edge"),fromChunkId:h.string().min(1),toChunkId:h.string().min(1),strength:h.string().optional(),weight:h.number()}).strict(),jT=h.object({type:h.literal("fragment-group"),groupId:Z,startSentenceIndex:Z,endSentenceIndex:Z}).strict(),UT=h.object({type:h.literal("snake"),id:h.string().min(1),groupId:Z,localSnakeId:Z,size:Z,firstLabel:h.string(),lastLabel:h.string(),wordsCount:Z,weight:h.number()}).strict(),qT=h.object({type:h.literal("snake-chunk"),snakeId:h.string().min(1),chunkId:h.string().min(1),position:Z}).strict(),BT=h.object({type:h.literal("snake-edge"),fromSnakeId:h.string().min(1),toSnakeId:h.string().min(1),weight:h.number()}).strict(),HT=h.object({type:h.literal("summary"),text:h.string()}).strict(),$T=h.object({type:h.literal("mention"),id:h.string().min(1),fragmentId:Z.optional(),sentenceIndex:Z.optional(),rangeStart:Z,rangeEnd:Z,surface:h.string().min(1),qid:OT,confidence:Nw,note:h.string().optional()}).strict(),JT=h.object({type:h.literal("mention-link"),id:h.string().min(1),sourceMentionId:h.string().min(1),targetMentionId:h.string().min(1),predicate:h.string().min(1),evidenceSentenceIndexes:h.array(Z).min(1),confidence:Nw,note:h.string().optional()}).strict(),KT=h.object({type:h.literal("end")}).strict(),Sce=h.discriminatedUnion("type",[DT,WT,MT,FT,GT,jT,UT,qT,BT,HT,$T,JT,KT])});var Dw=i(()=>{"use strict";Ge();kt()});var Ww=i(()=>{"use strict";P();no()});var Fw=i(()=>{"use strict";b();P();$();qn();Bn();Qt();Dw();Ww()});var lo=i(()=>{"use strict"});var Gw=i(()=>{"use strict";lo()});var jw=i(()=>{"use strict"});var Uw=i(()=>{"use strict";lo()});var qw=i(()=>{"use strict";lo()});var Bw=i(()=>{"use strict";Gw();jw();Uw();qw()});import{z as y}from"zod";var Hw,XT,VT,YT,ZT,e_,t_,n_,r_,i_,a_,$w=i(()=>{"use strict";Te();Hw=y.tuple([y.number(),y.number()]),XT=y.object({text:y.string(),wordsCount:y.number()}),VT=y.object({serialId:y.number(),fragmentId:y.number(),summary:y.string(),sentences:y.array(XT)}),YT=y.object({documentOrder:y.number().optional(),id:y.number(),knowledgeGraphReady:y.boolean(),knowledgeGraphParameterHash:y.string().optional(),revision:y.number().optional(),topologyParameterHash:y.string().optional(),topologyReady:y.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}})),ZT=y.object({id:y.number(),generation:y.number(),sentenceId:Hw,label:y.string(),content:y.string(),sentenceIds:y.array(Hw),retention:y.enum(ye).optional(),importance:y.enum(Ce).optional(),wordsCount:y.number(),weight:y.number()}),e_=y.object({fromId:y.number(),toId:y.number(),strength:y.string().optional(),weight:y.number()}),t_=y.object({id:y.number(),serialId:y.number(),groupId:y.number(),localSnakeId:y.number(),size:y.number(),firstLabel:y.string(),lastLabel:y.string(),wordsCount:y.number(),weight:y.number()}),n_=y.object({snakeId:y.number(),chunkId:y.number(),position:y.number()}),r_=y.object({fromSnakeId:y.number(),toSnakeId:y.number(),weight:y.number()}),i_=y.object({serialId:y.number(),groupId:y.number(),startSentenceIndex:y.number(),endSentenceIndex:y.number()}),a_=y.object({chunks:y.array(ZT),fragmentGroups:y.array(i_),fragments:y.array(VT),readingEdges:y.array(e_),serial:YT,snakeChunks:y.array(n_),snakeEdges:y.array(r_),snakes:y.array(t_)})});var Jw=i(()=>{"use strict";b();$w()});var Kw=i(()=>{"use strict";cn();Tu();X()});var zw=i(()=>{"use strict";b();P();$();Bw();Jw();uo();Kw();Bn();Qt()});var Qw=i(()=>{"use strict"});var mo=i(()=>{"use strict";zw();uo();Qw()});var Xw=i(()=>{"use strict";$();mo()});var Vw=i(()=>{"use strict"});var Yw=i(()=>{"use strict";Fw();Xw();Vw()});var Zw=i(()=>{"use strict";Vr()});var tS=i(()=>{"use strict";Vr();P();$();Qt();mo()});var nS=i(()=>{"use strict";Vr();St();cn()});var rS=i(()=>{"use strict";Yw();mo();Zw();tS();nS()});import{z as J}from"zod";var Ale,s_,Lle,Uu=i(()=>{"use strict";b();Ale=J.object({id:J.string().min(1),chapterId:J.number().int(),sentenceIndex:J.number().int().nonnegative().optional(),rangeStart:J.number().int().nonnegative(),rangeEnd:J.number().int().nonnegative(),surface:J.string().min(1),qid:J.string().regex(/^Q[1-9][0-9]*$/),confidence:J.number().min(0).max(1).optional(),note:J.string().optional()}),s_=J.tuple([J.number().int().nonnegative(),J.number().int().nonnegative()]).readonly(),Lle=J.object({id:J.string().min(1),sourceMentionId:J.string().min(1),targetMentionId:J.string().min(1),predicate:J.string().min(1),evidenceSentenceIds:J.array(s_).min(1),confidence:J.number().min(0).max(1).optional(),note:J.string().optional()})});var qu=i(()=>{"use strict";b();Ge();Bn();Uu()});var aS=i(()=>{"use strict";Bn();Qt();Uu()});var po=i(()=>{"use strict"});var oS=i(()=>{"use strict";St();po()});var Bu=i(()=>{"use strict"});var sS=i(()=>{"use strict";St()});var Hu=i(()=>{"use strict"});var $u=i(()=>{"use strict";St();po();sS();Hu()});var cS=i(()=>{"use strict";$u()});var uS=i(()=>{"use strict";Ge()});var lS=i(()=>{"use strict";Eu();Wn();to()});import{z as j}from"zod";var mS,l_,m_,p_,xme,Eme,pS=i(()=>{"use strict";Me();Wn();lS();mS=j.object({head:j.string().optional(),mode:j.enum(["full","head_tail"]).optional(),tail:j.string().optional(),text:j.string().optional()}).strict(),l_=j.object({quote:j.string().optional(),sentence_id:j.string().optional()}).strict(),m_=j.union([j.object({end_anchor:j.union([j.string(),mS]).optional(),quote:j.string().optional(),sentence_id:j.string().optional(),start_anchor:j.union([j.string(),mS]).optional()}).strict(),j.array(l_)]),p_=j.object({confidence:j.number().min(0).max(1).optional(),evidence:m_,predicate:j.string().min(1).max(64),sourceMentionId:j.string().min(1),targetMentionId:j.string().min(1)}).strict(),xme=j.object({relations:j.array(p_)}).strict(),Eme=new Zt});var hS=i(()=>{"use strict"});var fS=i(()=>{"use strict";pS();hS()});var yS=i(()=>{"use strict";fS();po();Hu()});var Ju=i(()=>{"use strict";$();Bu()});var wS=i(()=>{"use strict";St();kt();qu();oS();Bu();cS();uS();yS();Ju()});var SS=i(()=>{"use strict"});var kS=i(()=>{"use strict";qu();aS();wS();$u();Ju();SS()});var xS=i(()=>{"use strict";kS()});var fi=i(()=>{"use strict";$()});var Ku=i(()=>{"use strict";kt()});var zu=i(()=>{"use strict";Ge();kt();qn();fi();Ku()});var vS=i(()=>{"use strict";kt();fi();zu()});var Qu=i(()=>{"use strict";be();X()});var CS=i(()=>{"use strict";be();dr();mt();Qu();$();$();X()});var TS=i(()=>{"use strict";qn();be();fi();CS();Qu();X()});import{z as tn}from"zod";var _S,ohe,PS=i(()=>{"use strict";_S=tn.object({children:tn.lazy(()=>tn.array(_S)),uri:tn.string().min(1),title:tn.string().nullable().optional()}).strict(),ohe=tn.object({chapters:tn.array(_S)}).strict()});var AS=i(()=>{"use strict";$()});var LS=i(()=>{"use strict";vS();fi();zu();TS();Ku();PS();AS()});var OS=i(()=>{"use strict";Sr()});var tt=i(()=>{"use strict";Lw();yt();Xc();rS();xS();yt();Mu();LS();OS();Ca()});import{AsyncLocalStorage as cP}from"async_hooks";function uP(){let t=globalThis,e=t[VS];if(e!==void 0)return e;let n=new cP;return Object.defineProperty(t,VS,{configurable:!1,enumerable:!1,value:n,writable:!1}),n}async function yi(t,e){return await YS.run(t,e)}function bo(){return YS.getStore()??{cwd:process.cwd(),env:process.env,envPolicy:"production",providers:{}}}var VS,YS,pe=i(()=>{"use strict";VS=Symbol.for("wiki-graph-sdk.runtime-context.v1"),YS=uP()});function ak(t){if(t?.platform===void 0){Sl();return}nn(t.platform)}function ok(t){if(t.host?.storage!==void 0&&t.host.stateDir===void 0)throw new TypeError("Wiki Graph SDK host.storage requires host.stateDir so SDK configuration cannot fall back to the default user state directory.");if(t.stateDir!==void 0&&(t.host?.stateDir!==void 0||t.host?.storage!==void 0))throw new TypeError("Wiki Graph SDK host state/storage and top-level stateDir cannot be used together. Put the state directory in host.stateDir when providing host.storage.")}async function Eo(t,e){let n=bo(),r={...t.host===void 0?n.host===void 0?{}:{host:n.host}:{host:t.host},...t.stateDir===void 0?n.stateDir===void 0?{}:{stateDir:n.stateDir}:{stateDir:t.stateDir}};ok(r),ak(r.host);let a=async()=>await yi({...n,...r.host===void 0?{}:{host:r.host},...r.stateDir===void 0?{}:{stateDir:r.stateDir}},e);return r.host?.storage!==void 0?await an(r.host.storage,a):await Ri(r.host?.stateDir??r.stateDir,a)}var Io=i(()=>{"use strict";To();ue();pe()});async function yk(t="global"){let e=await nl(),n=at(),r=Date.now(),a=!1;try{await e.transaction(async()=>{await GP(e),await e.run(`
867
867
  INSERT OR IGNORE INTO gc_locks (
868
868
  scope, owner_id, owner_pid, heartbeat_at, created_at
869
869
  ) VALUES (?, ?, ?, ?, ?)
870
- `,[t,n,0,r,r]),a=await e.queryOne("SELECT owner_id FROM gc_locks WHERE scope = ?",[t],s=>T(s,"owner_id"))===n})}finally{await e.close()}if(!a)return;let o=setInterval(()=>{MP(t,n).catch(()=>{})},WP);return async()=>{clearInterval(o);let s=await nl();try{await s.run("DELETE FROM gc_locks WHERE scope = ? AND owner_id = ?",[t,n])}finally{await s.close()}}}async function MP(t,e){let n=await nl();try{await n.run(`
870
+ `,[t,n,0,r,r]),a=await e.queryOne("SELECT owner_id FROM gc_locks WHERE scope = ?",[t],s=>T(s,"owner_id"))===n})}finally{await e.close()}if(!a)return;let o=setInterval(()=>{FP(t,n).catch(()=>{})},MP);return async()=>{clearInterval(o);let s=await nl();try{await s.run("DELETE FROM gc_locks WHERE scope = ? AND owner_id = ?",[t,n])}finally{await s.close()}}}async function FP(t,e){let n=await nl();try{await n.run(`
871
871
  UPDATE gc_locks
872
872
  SET heartbeat_at = ?, owner_pid = ?
873
873
  WHERE scope = ? AND owner_id = ?
874
- `,[Date.now(),0,t,e])}finally{await n.close()}}async function FP(t){let e=await t.queryAll("SELECT * FROM gc_locks",void 0,UP);for(let{lock:n,scope:r}of e.filter(({lock:a})=>GP(a)))await t.run(`
874
+ `,[Date.now(),0,t,e])}finally{await n.close()}}async function GP(t){let e=await t.queryAll("SELECT * FROM gc_locks",void 0,qP);for(let{lock:n,scope:r}of e.filter(({lock:a})=>jP(a)))await t.run(`
875
875
  DELETE FROM gc_locks
876
876
  WHERE scope = ?
877
877
  AND owner_id = ?
878
878
  AND heartbeat_at = ?
879
- `,[r,n.ownerId,n.heartbeatAt])}function GP(t){return!(Date.now()-t.heartbeatAt<DP)}async function nl(){return await Q("tmp/gc.sqlite",NP)}function jP(t){return{createdAt:k(t,"created_at"),heartbeatAt:k(t,"heartbeat_at"),ownerId:T(t,"owner_id"),ownerPid:k(t,"owner_pid")}}function UP(t){return{lock:jP(t),scope:T(t,"scope")}}var NP,DP,WP,gk=i(()=>{"use strict";M();x();P();NP=`
879
+ `,[r,n.ownerId,n.heartbeatAt])}function jP(t){return!(Date.now()-t.heartbeatAt<WP)}async function nl(){return await Q("tmp/gc.sqlite",DP)}function UP(t){return{createdAt:k(t,"created_at"),heartbeatAt:k(t,"heartbeat_at"),ownerId:T(t,"owner_id"),ownerPid:k(t,"owner_pid")}}function qP(t){return{lock:UP(t),scope:T(t,"scope")}}var DP,WP,MP,gk=i(()=>{"use strict";M();x();P();DP=`
880
880
  CREATE TABLE IF NOT EXISTS gc_locks (
881
881
  scope TEXT PRIMARY KEY,
882
882
  owner_id TEXT NOT NULL,
@@ -884,8 +884,8 @@ CREATE TABLE IF NOT EXISTS gc_locks (
884
884
  heartbeat_at INTEGER NOT NULL,
885
885
  created_at INTEGER NOT NULL
886
886
  );
887
- `,DP=6e4,WP=2e4});async function bk(t){let e=await C().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 BP(e)){n+=1;let s=await rt(o.value);if(!t.force&&(s===void 0||t.now-s<qP))continue;let d=await bt(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 BP(t){let e=[];for(let n of await t.list())if(K(n))for(let r of await n.list())e.push({parent:n,value:r});return e}var qP,wk=i(()=>{"use strict";b();Wc();qP=3600*1e3});async function vo(t={}){let e=Date.now(),n=await yk();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 KP(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 HP)a.push(await JP(s,r));let o={finishedAt:Date.now(),freedBytes:rl(a,"freedBytes"),jobs:a,removed:rl(a,"removed"),scanned:rl(a,"scanned"),skipped:!1,startedAt:e};return await zP(o.finishedAt).catch(()=>{}),o}finally{await n()}}async function JP(t,e){try{return{name:t.name,...await t.run(e)}}catch(n){return{error:dn(n),freedBytes:0,name:t.name,removed:0,scanned:0}}}function rl(t,e){return t.reduce((n,r)=>{let a=r[e];return n+(typeof a=="number"?a:0)},0)}async function KP(t){let e=await ee(C().library,"tmp/gc.last-run"),n=Number((e===void 0?"":await te(e).catch(()=>"")).trim());return!Number.isFinite(n)||t-n>=$P}async function zP(t){let e=await q(C().library,"tmp/gc.last-run");await ce(e,`${t}
888
- `)}var HP,$P,Sk=i(()=>{"use strict";b();yt();tt();Xe();za();lu();fe();gk();wk();HP=[{name:"wikg-coordinator",run:_a},{name:"search-cache",run:Bi},{name:"library-index",run:Fg},{name:"build-queue",run:qa},{name:"wikimedia-cache",run:cu},{name:"tmp",run:bk}],$P=600*1e3});var kk=i(()=>{"use strict";Sk()});var xk=i(()=>{"use strict";kk()});var Ek={};Ck(Ek,{tryRunWikiGraphGc:()=>QP});async function QP(t={}){let{host:e,stateDir:n,...r}=t;return await Eo({...e===void 0?{}:{host:e},...n===void 0?{}:{stateDir:n}},async()=>await vo(r))}var Ik=i(()=>{"use strict";xk();Io()});ue();import{AsyncLocalStorage as CP}from"async_hooks";import{randomUUID as nbe}from"crypto";import{link as ibe,mkdtemp as abe,rename as obe,rm as sbe,stat as dbe}from"fs/promises";import{tmpdir as ube}from"os";import{basename as mbe,dirname as pbe,join as hbe}from"path";import{Readable as ybe}from"stream";Ge();b();Ci();import{z as Kn}from"zod";var Zk=1,RA=Kn.object({completedAt:Kn.string().optional(),startedAt:Kn.string(),status:Kn.enum(["running","succeeded"]),version:Kn.literal(Zk)});Ho();cn();st();X();Jo();Hn();za();Wn();lu();St();Su();tt();be();Xe();P();mt();yt();Ga();za();Yc();Ga();wn();Qt();P();b();Xe();b();x();x();b();x();b();_s();b();fe();tt();tt();tt();tt();tt();kt();St();P();Bn();b();import{createHash as fge}from"crypto";import{createReadStream as gge}from"fs";import{rm as wge}from"fs/promises";import{basename as kge}from"path";import{createAnthropic as xye}from"@ai-sdk/anthropic";import{createGoogleGenerativeAI as Iye}from"@ai-sdk/google";import{createOpenAI as Rye}from"@ai-sdk/openai";import{createOpenAICompatible as Tye}from"@ai-sdk/openai-compatible";ue();import{z as ae}from"zod";pe();ue();import{mkdir as Mye}from"fs/promises";import{join as Gye}from"path";import{homedir as Uye}from"os";pe();var uP=["anthropic","google","openai","openai-compatible"],ZS=ae.enum(uP),Jye=ae.object({apiKey:ae.string().min(1).optional(),baseURL:ae.string().min(1).optional(),baseUrl:ae.string().min(1).optional(),chatCompletionsUrl:ae.string().min(1).optional(),llm:ae.object({apiKey:ae.string().min(1).optional(),baseURL:ae.string().min(1).optional(),baseUrl:ae.string().min(1).optional(),chatCompletionsUrl:ae.string().min(1).optional(),model:ae.string().min(1).optional(),name:ae.string().min(1).optional(),provider:ZS.optional()}).optional(),model:ae.string().min(1).optional(),name:ae.string().min(1).optional(),provider:ZS.optional()});pe();pe();import{homedir as Xye}from"os";import{isAbsolute as Yye,resolve as Zye}from"path";import{realpath as rge,stat as ige}from"fs/promises";import{basename as oge,dirname as sge,join as dge,resolve as cge}from"path";ue();ue();import{embed as Lge,embedMany as Oge}from"ai";import{createOpenAI as Dge}from"@ai-sdk/openai";import{createOpenAICompatible as Mge}from"@ai-sdk/openai-compatible";pe();import{spawn as Lbe}from"child_process";import{streamText as Kbe}from"ai";tt();pe();ue();Io();pe();var vP=["WIKIGRAPH_DEV","WIKIGRAPH_ENV_POLICY","WIKIGRAPH_QUEUE_DISABLE_AUTOSTART","WIKIGRAPH_STATE_DIR"];function dk(t){let e=RP(t.env);if(t.envPolicy==="production"){let o=vP.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=sk(t.stateDir??n);if(r===void 0)throw new Error("Wiki Graph development entries require an explicit runtime state directory.");let a=sk(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 RP(t){return t===void 0?{...process.env}:{...process.env,...t}}function sk(t){if(!(t===void 0||t.trim()===""))return t}ue();pe();ue();import{mkdir as eSe,mkdtemp as tSe,rm as nSe}from"fs/promises";import{tmpdir as iSe}from"os";import{join as oSe}from"path";var mSe=64*1024;ue();import{basename as ySe}from"path";ue();pe();Io();pe();var TP=new CP;async function ck(t,e){return await TP.run(t,async()=>await yi({cwd:t.cwd,env:t.env,envPolicy:t.envPolicy,providers:{},...t.stateDir===void 0?{}:{stateDir:t.stateDir}},e))}var uk="--wikigraph-internal-child",lk="--wikigraph-dev-project-root",mk="--wikigraph-env-policy",pk="--wikigraph-state-dir";async function hk(t,e){let n=_P(process.argv.slice(2));if(n.internalChild!==t)throw new Error("This Wiki Graph worker entry is internal.");let r=dk({argv:n.argv,devProjectRoot:n.devProjectRoot,envPolicy:n.envPolicy,stateDir:n.stateDir});return await Ri(r.stateDir,async()=>ck({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 _P(t){let e=[],n,r,a="production",o;for(let s=0;s<t.length;s+=1){let d=t[s];if(d===uk){if(s+1>=t.length)throw new Error(`${uk} requires a value.`);n=t[s+1],s+=1;continue}if(d===mk){let c=t[s+1];if(c!=="development"&&c!=="production")throw new Error(`${mk} requires development or production.`);a=c,s+=1;continue}if(d===lk){let c=t[s+1];if(c===void 0||c.trim()==="")throw new Error(`${lk} requires a value.`);r=c,s+=1;continue}if(d!==pk){e.push(d);continue}if(s+1>=t.length)throw new Error(`${pk} requires a value.`);o=t[s+1],s+=1}return{argv:e,devProjectRoot:r,envPolicy:a,internalChild:n??"",stateDir:o}}var PP={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 Ike}from"path";import{createReadStream as Lke}from"fs";import{mkdtemp as Nke,rm as Dke}from"fs/promises";import{join as Mke}from"path";import{tmpdir as Gke}from"os";var AP=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 fk(t){return`${JSON.stringify(tl(t),null,2)}
889
- `}function tl(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>tl(e)??null);if(typeof t=="object")return LP(t)}function LP(t){let e=Object.entries(t).map(([r,a],o)=>({index:o,key:r,priority:AP.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=tl(r.value);a!==void 0&&(n[r.key]=a)}return n}import{homedir as zke}from"os";import{isAbsolute as Xke,relative as Vke,resolve as Yke}from"path";import{existsSync as rxe,readFileSync as ixe}from"fs";import{dirname as oxe,join as sxe,parse as dxe,resolve as cxe}from"path";wl();var{tryRunWikiGraphGc:XP}=await Promise.resolve().then(()=>(Ik(),Ek));async function VP(){await hk("gc-worker",async({argv:t})=>{let e=YP(t);process.stdout.write(fk(await XP({dryRun:e.dryRun,force:e.force})))})}function YP(t){return{dryRun:t.includes("--dry-run"),force:t.includes("--force")}}VP().catch(t=>{process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}
887
+ `,WP=6e4,MP=2e4});async function bk(t){let e=await C().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 HP(e)){n+=1;let s=await rt(o.value);if(!t.force&&(s===void 0||t.now-s<BP))continue;let d=await bt(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 HP(t){let e=[];for(let n of await t.list())if(K(n))for(let r of await n.list())e.push({parent:n,value:r});return e}var BP,wk=i(()=>{"use strict";b();Wc();BP=3600*1e3});async function vo(t={}){let e=Date.now(),n=await yk();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 zP(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 $P)a.push(await KP(s,r));let o={finishedAt:Date.now(),freedBytes:rl(a,"freedBytes"),jobs:a,removed:rl(a,"removed"),scanned:rl(a,"scanned"),skipped:!1,startedAt:e};return await QP(o.finishedAt).catch(()=>{}),o}finally{await n()}}async function KP(t,e){try{return{name:t.name,...await t.run(e)}}catch(n){return{error:dn(n),freedBytes:0,name:t.name,removed:0,scanned:0}}}function rl(t,e){return t.reduce((n,r)=>{let a=r[e];return n+(typeof a=="number"?a:0)},0)}async function zP(t){let e=await ee(C().library,"tmp/gc.last-run"),n=Number((e===void 0?"":await te(e).catch(()=>"")).trim());return!Number.isFinite(n)||t-n>=JP}async function QP(t){let e=await q(C().library,"tmp/gc.last-run");await ce(e,`${t}
888
+ `)}var $P,JP,Sk=i(()=>{"use strict";b();yt();tt();Xe();za();lu();fe();gk();wk();$P=[{name:"wikg-coordinator",run:_a},{name:"search-cache",run:Bi},{name:"library-index",run:Fg},{name:"build-queue",run:qa},{name:"wikimedia-cache",run:cu},{name:"tmp",run:bk}],JP=600*1e3});var kk=i(()=>{"use strict";Sk()});var xk=i(()=>{"use strict";kk()});var Ek={};Ck(Ek,{tryRunWikiGraphGc:()=>XP});async function XP(t={}){let{host:e,stateDir:n,...r}=t;return await Eo({...e===void 0?{}:{host:e},...n===void 0?{}:{stateDir:n}},async()=>await vo(r))}var Ik=i(()=>{"use strict";xk();Io()});ue();import{AsyncLocalStorage as TP}from"async_hooks";import{randomUUID as nbe}from"crypto";import{link as ibe,mkdtemp as abe,rename as obe,rm as sbe,stat as dbe}from"fs/promises";import{tmpdir as ube}from"os";import{basename as mbe,dirname as pbe,join as hbe}from"path";import{Readable as ybe}from"stream";Ge();b();Ci();import{z as Kn}from"zod";var Zk=1,CA=Kn.object({completedAt:Kn.string().optional(),startedAt:Kn.string(),status:Kn.enum(["running","succeeded"]),version:Kn.literal(Zk)});Ho();cn();st();X();Jo();Hn();za();Wn();lu();St();Su();tt();be();Xe();P();mt();yt();Ga();za();Yc();Ga();wn();Qt();P();b();Xe();b();x();x();b();x();b();_s();b();fe();tt();tt();tt();tt();tt();kt();St();P();Bn();b();import{createHash as fge}from"crypto";import{createReadStream as gge}from"fs";import{rm as wge}from"fs/promises";import{basename as kge}from"path";import{createAnthropic as xye}from"@ai-sdk/anthropic";import{createGoogleGenerativeAI as Iye}from"@ai-sdk/google";import{createOpenAI as Rye}from"@ai-sdk/openai";import{createOpenAICompatible as Tye}from"@ai-sdk/openai-compatible";ue();import{z as ae}from"zod";pe();ue();import{mkdir as Mye}from"fs/promises";import{join as Gye}from"path";import{homedir as Uye}from"os";pe();var lP=["anthropic","google","openai","openai-compatible"],ZS=ae.enum(lP),Jye=ae.object({apiKey:ae.string().min(1).optional(),baseURL:ae.string().min(1).optional(),baseUrl:ae.string().min(1).optional(),chatCompletionsUrl:ae.string().min(1).optional(),llm:ae.object({apiKey:ae.string().min(1).optional(),baseURL:ae.string().min(1).optional(),baseUrl:ae.string().min(1).optional(),chatCompletionsUrl:ae.string().min(1).optional(),model:ae.string().min(1).optional(),name:ae.string().min(1).optional(),provider:ZS.optional()}).optional(),model:ae.string().min(1).optional(),name:ae.string().min(1).optional(),provider:ZS.optional()});pe();pe();import{homedir as Xye}from"os";import{isAbsolute as Yye,resolve as Zye}from"path";import{realpath as rge,stat as ige}from"fs/promises";import{basename as oge,dirname as sge,join as dge,resolve as cge}from"path";ue();ue();import{embed as Lge,embedMany as Oge}from"ai";import{createOpenAI as Dge}from"@ai-sdk/openai";import{createOpenAICompatible as Mge}from"@ai-sdk/openai-compatible";pe();import{spawn as Lbe}from"child_process";import{streamText as Kbe}from"ai";tt();pe();ue();Io();pe();var RP=["WIKIGRAPH_DEV","WIKIGRAPH_ENV_POLICY","WIKIGRAPH_QUEUE_DISABLE_AUTOSTART","WIKIGRAPH_STATE_DIR"];function dk(t){let e=CP(t.env);if(t.envPolicy==="production"){let o=RP.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=sk(t.stateDir??n);if(r===void 0)throw new Error("Wiki Graph development entries require an explicit runtime state directory.");let a=sk(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 CP(t){return t===void 0?{...process.env}:{...process.env,...t}}function sk(t){if(!(t===void 0||t.trim()===""))return t}ue();pe();ue();import{mkdir as eSe,mkdtemp as tSe,rm as nSe}from"fs/promises";import{tmpdir as iSe}from"os";import{join as oSe}from"path";var mSe=64*1024;ue();import{basename as ySe}from"path";ue();pe();Io();pe();var _P=new TP;async function ck(t,e){return await _P.run(t,async()=>await yi({cwd:t.cwd,env:t.env,envPolicy:t.envPolicy,providers:{},...t.stateDir===void 0?{}:{stateDir:t.stateDir}},e))}var uk="--wikigraph-internal-child",lk="--wikigraph-dev-project-root",mk="--wikigraph-env-policy",pk="--wikigraph-state-dir";async function hk(t,e){let n=PP(process.argv.slice(2));if(n.internalChild!==t)throw new Error("This Wiki Graph worker entry is internal.");let r=dk({argv:n.argv,devProjectRoot:n.devProjectRoot,envPolicy:n.envPolicy,stateDir:n.stateDir});return await Ri(r.stateDir,async()=>ck({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 PP(t){let e=[],n,r,a="production",o;for(let s=0;s<t.length;s+=1){let d=t[s];if(d===uk){if(s+1>=t.length)throw new Error(`${uk} requires a value.`);n=t[s+1],s+=1;continue}if(d===mk){let c=t[s+1];if(c!=="development"&&c!=="production")throw new Error(`${mk} requires development or production.`);a=c,s+=1;continue}if(d===lk){let c=t[s+1];if(c===void 0||c.trim()==="")throw new Error(`${lk} requires a value.`);r=c,s+=1;continue}if(d!==pk){e.push(d);continue}if(s+1>=t.length)throw new Error(`${pk} requires a value.`);o=t[s+1],s+=1}return{argv:e,devProjectRoot:r,envPolicy:a,internalChild:n??"",stateDir:o}}var AP={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 Ike}from"path";import{createReadStream as Lke}from"fs";import{mkdtemp as Nke,rm as Dke}from"fs/promises";import{join as Mke}from"path";import{tmpdir as Gke}from"os";var LP=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 fk(t){return`${JSON.stringify(tl(t),null,2)}
889
+ `}function tl(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>tl(e)??null);if(typeof t=="object")return OP(t)}function OP(t){let e=Object.entries(t).map(([r,a],o)=>({index:o,key:r,priority:LP.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=tl(r.value);a!==void 0&&(n[r.key]=a)}return n}import{homedir as zke}from"os";import{isAbsolute as Xke,relative as Vke,resolve as Yke}from"path";import{existsSync as rxe,readFileSync as ixe}from"fs";import{dirname as oxe,join as sxe,parse as dxe,resolve as cxe}from"path";wl();var{tryRunWikiGraphGc:VP}=await Promise.resolve().then(()=>(Ik(),Ek));async function YP(){await hk("gc-worker",async({argv:t})=>{let e=ZP(t);process.stdout.write(fk(await VP({dryRun:e.dryRun,force:e.force})))})}function ZP(t){return{dryRun:t.includes("--dry-run"),force:t.includes("--force")}}YP().catch(t=>{process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}
890
890
  `),process.exitCode=1});
891
891
  //# sourceMappingURL=gc-worker.js.map