@aiquants/markdown-explorer 0.6.0 → 0.7.0
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/CHANGELOG.md +30 -0
- package/README.md +57 -8
- package/dist/EditSurface-BCB-0vUK.js +371 -0
- package/dist/EditSurface-BZ98L7hy.cjs +2 -0
- package/dist/ExplorerSplit-BTRTah7R.cjs +1 -0
- package/dist/{ExplorerSplit-CN5TvRj6.js → ExplorerSplit-DpoMtzq3.js} +391 -417
- package/dist/MultiLayout-B7OiXgWH.cjs +1 -0
- package/dist/MultiLayout-BD2LiwOe.js +947 -0
- package/dist/{NativeScrollBar-CHEQgaVx.cjs → NativeScrollBar-B4j3Vigb.cjs} +1 -1
- package/dist/{NativeScrollBar-DYEv2GLV.js → NativeScrollBar-EXOKhHP4.js} +1 -1
- package/dist/TreeLayout-B9dF2A3h.cjs +1 -0
- package/dist/TreeLayout-hn2bfU22.js +29 -0
- package/dist/client/MarkdownExplorer.d.cts +2 -1
- package/dist/client/MarkdownExplorer.d.ts +2 -1
- package/dist/client/storage.d.cts +1 -0
- package/dist/client/storage.d.ts +1 -0
- package/dist/core/contracts.d.cts +58 -0
- package/dist/core/contracts.d.ts +58 -0
- package/dist/core/labels.d.cts +49 -0
- package/dist/core/labels.d.ts +49 -0
- package/dist/core/location.d.cts +7 -0
- package/dist/core/location.d.ts +7 -0
- package/dist/dataRoute-CcZ8PK00.cjs +1 -0
- package/dist/dataRoute-D1vE1wFW.js +270 -0
- package/dist/index-C0gh_dRY.js +3188 -0
- package/dist/index-CCc6qUbM.cjs +5 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +31 -30
- package/dist/location-DmzVAFvo.cjs +1 -0
- package/dist/{location-CtM94G0O.js → location-Q4sgRrUm.js} +202 -193
- package/dist/merge-0W6xtIxj.cjs +5 -0
- package/dist/merge-Bi41vtSe.js +20 -0
- package/dist/sanitizeWorker.cjs +1 -1
- package/dist/sanitizeWorker.js +173 -172
- package/dist/server/errors.d.cts +1 -1
- package/dist/server/errors.d.ts +1 -1
- package/dist/server/ports.d.cts +33 -1
- package/dist/server/ports.d.ts +33 -1
- package/dist/server.cjs +1 -1
- package/dist/server.d.cts +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.js +882 -751
- package/dist/{storage-DA4ItHzl.js → storage-BSthKLSG.js} +14 -13
- package/dist/storage-Dgi4JXaB.cjs +1 -0
- package/dist/storage.cjs +1 -1
- package/dist/storage.js +1 -1
- package/dist/styles/markdown-explorer.css +1 -1
- package/docs/behavior/dom-hooks.md +17 -3
- package/docs/behavior/layout.md +6 -1
- package/docs/behavior/security.md +11 -1
- package/docs/behavior/url-contract.md +13 -4
- package/package.json +11 -3
- package/dist/ExplorerSplit-CUIbSLQm.cjs +0 -1
- package/dist/MultiLayout-BDcQSpa6.cjs +0 -1
- package/dist/MultiLayout-hPmV-bae.js +0 -922
- package/dist/TreeLayout-BDaIyoGT.cjs +0 -1
- package/dist/TreeLayout-CqzxLpoM.js +0 -23
- package/dist/dataRoute-CUXlMhUJ.cjs +0 -1
- package/dist/dataRoute-Ce6EIuu4.js +0 -206
- package/dist/index-B3nShkkt.cjs +0 -3
- package/dist/index-gJp1iXTc.js +0 -2238
- package/dist/location-FavgY_gB.cjs +0 -1
- package/dist/storage-Bkb2Axdi.cjs +0 -1
package/dist/server/ports.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ActionFunctionArgs, data, HeadersFunction, LoaderFunctionArgs } from "react-router";
|
|
2
2
|
import { ExplorerConfig } from "../core/config.js";
|
|
3
|
-
import { ExplorerEntry, ExplorerFailureDocument, ExplorerHeading, ExplorerMediaType, ExplorerNotice, ExplorerPageData } from "../core/contracts.js";
|
|
3
|
+
import { ExplorerDocumentEdit, ExplorerEntry, ExplorerFailureDocument, ExplorerGrantRequired, ExplorerHeading, ExplorerMediaType, ExplorerNotice, ExplorerPageData, ExplorerRevision } from "../core/contracts.js";
|
|
4
4
|
import { ExplorerPathRules } from "../core/paths.js";
|
|
5
5
|
import { ExplorerLogger } from "./errors.js";
|
|
6
6
|
import { HtmlSanitizerOptions } from "./sanitizer.js";
|
|
@@ -62,6 +62,7 @@ export type ExplorerHostDocument = {
|
|
|
62
62
|
readonly name: string;
|
|
63
63
|
readonly htmlContent: string;
|
|
64
64
|
readonly headings: readonly ExplorerHeading[];
|
|
65
|
+
readonly edit: ExplorerDocumentEdit | null;
|
|
65
66
|
} | {
|
|
66
67
|
readonly kind: "text";
|
|
67
68
|
readonly name: string;
|
|
@@ -82,6 +83,35 @@ export type ExplorerHostDocument = {
|
|
|
82
83
|
readonly name: string;
|
|
83
84
|
readonly version: string;
|
|
84
85
|
} | ExplorerFailureDocument;
|
|
86
|
+
export type ExplorerHostEditSource = {
|
|
87
|
+
readonly kind: "edit";
|
|
88
|
+
readonly text: string;
|
|
89
|
+
readonly version: string;
|
|
90
|
+
readonly history: boolean;
|
|
91
|
+
} | ExplorerGrantRequired;
|
|
92
|
+
export type ExplorerDraft = {
|
|
93
|
+
readonly text: string;
|
|
94
|
+
readonly baseVersion: string;
|
|
95
|
+
};
|
|
96
|
+
export type ExplorerHostSaveResult = {
|
|
97
|
+
readonly kind: "saved";
|
|
98
|
+
readonly version: string;
|
|
99
|
+
} | {
|
|
100
|
+
readonly kind: "conflict";
|
|
101
|
+
readonly version: string;
|
|
102
|
+
readonly text: string;
|
|
103
|
+
} | ExplorerGrantRequired;
|
|
104
|
+
export type ExplorerHostPreview = {
|
|
105
|
+
readonly htmlContent: string;
|
|
106
|
+
readonly headings: readonly ExplorerHeading[];
|
|
107
|
+
};
|
|
108
|
+
export type ExplorerEditPorts<P> = {
|
|
109
|
+
readonly source: (context: ExplorerSourceContext<P>, path: string, readPath: string) => Promise<ExplorerHostEditSource>;
|
|
110
|
+
readonly save: (context: ExplorerSourceContext<P>, path: string, readPath: string, draft: ExplorerDraft) => Promise<ExplorerHostSaveResult>;
|
|
111
|
+
readonly preview: (context: ExplorerSourceContext<P>, path: string, readPath: string, text: string) => Promise<ExplorerHostPreview>;
|
|
112
|
+
readonly revisions: (context: ExplorerSourceContext<P>, path: string, readPath: string) => Promise<readonly ExplorerRevision[]>;
|
|
113
|
+
readonly revision: (context: ExplorerSourceContext<P>, path: string, readPath: string, revisionId: string) => Promise<string>;
|
|
114
|
+
};
|
|
85
115
|
export type MarkdownExplorerServerConfig<P> = {
|
|
86
116
|
readonly config: ExplorerConfig;
|
|
87
117
|
readonly authenticate: (request: Request, mode: ExplorerAuthenticationMode) => Promise<ExplorerAuthentication<P>>;
|
|
@@ -102,6 +132,8 @@ export type MarkdownExplorerServerConfig<P> = {
|
|
|
102
132
|
readonly sanitizer?: HtmlSanitizerOptions;
|
|
103
133
|
readonly deferredTimeoutMs?: number;
|
|
104
134
|
readonly textMaxBytes?: number;
|
|
135
|
+
readonly edit?: ExplorerEditPorts<P>;
|
|
136
|
+
readonly editMaxBytes?: number;
|
|
105
137
|
readonly logger?: ExplorerLogger;
|
|
106
138
|
readonly onTreeRefreshed?: (key: string) => void;
|
|
107
139
|
};
|
package/dist/server.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("./dataRoute-CUXlMhUJ.cjs"),dt=require("node:crypto"),Pt=require("@aiquants/markdown/server"),ze=require("@aiquants/request-isolation"),Se=require("react-router"),se=require("./location-FavgY_gB.cjs"),ae=require("node:fs"),re=require("node:path"),xe=require("node:url"),It=require("node:worker_threads"),me=require("node:fs/promises"),Mt=require("node:stream");var Oe=typeof document<"u"?document.currentScript:null;const Ce=Object.freeze({kind:"anonymous"}),vt=Object.freeze({authenticate:async()=>({status:"signed-in",principal:Ce}),principalKey:()=>Ce.kind,signedOutPage:(e,t)=>new Response(null,{status:401,headers:t})}),Lt="application/octet-stream",ft="application/pdf",$t=new Set(["image/png","image/apng","image/jpeg","image/gif","image/webp","image/avif","image/bmp","image/x-icon","image/vnd.microsoft.icon","audio/mpeg","audio/mp4","audio/aac","audio/ogg","audio/opus","audio/wav","audio/wave","audio/x-wav","audio/webm","audio/flac","audio/x-flac","audio/x-m4a","video/mp4","video/webm","video/ogg","video/quicktime",ft]),mt="default-src 'none'; media-src 'self'; style-src 'unsafe-inline'",Dt=`${mt}; sandbox`,jt=`${mt}; sandbox allow-same-origin`,He=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,zt=/^[\t\n\r ]+|[\t\n\r ]+$/gu,Pe=/^[\t ]+|[\t ]+$/gu,Ct=e=>{const t=[];let r="",n=0;for(;;){for(;n<e.length&&e[n]!=='"'&&e[n]!==",";)r+=e[n],n+=1;if(n<e.length&&e[n]==='"'){const a=n;for(n+=1;n<e.length&&e[n]!=='"';)n+=e[n]==="\\"?2:1;if(n=Math.min(n+1,e.length),r+=e.slice(a,n),n<e.length)continue}if(t.push(r.replace(Pe,"")),r="",n>=e.length)return t;n+=1}},Ht=e=>{const t=e.replace(zt,""),r=t.indexOf("/");if(r<0)return null;const n=t.slice(0,r),a=t.indexOf(";",r+1),s=t.slice(r+1,a<0?t.length:a).replace(/[\t\n\r ]+$/u,"");return He.test(n)&&He.test(s)?`${n}/${s}`.toLowerCase():null},Bt=e=>{let t=null;for(const r of Ct(e)){const n=Ht(r);n!==null&&n!=="*/*"&&(t=n)}return t},Ft=/['()*]/gu,Ut=e=>encodeURIComponent(e).replace(Ft,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Xt=Object.freeze({"Cache-Control":"private, max-age=60, stale-while-revalidate=600, no-transform",Vary:"Cookie"}),Gt=(e,t)=>{const r=Bt(e),n=r!==null&&$t.has(r),a=n&&(r.startsWith("audio/")||r.startsWith("video/"));return{contentType:r===null?Lt:r,inline:n,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`${n?"inline":"attachment"}; filename*=UTF-8''${Ut(t)}`,...r===ft?{}:{"Content-Security-Policy":a?jt:Dt},"Cross-Origin-Resource-Policy":"same-origin"}}},Jt=/^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu,ge=Object.freeze({kind:"whole"}),Be=Object.freeze({kind:"unsatisfiable"}),Yt=(e,t,r)=>{const n=e.get("Range");if(n===null)return ge;const a=e.get("If-Range");if(a!==null&&a!==r)return ge;const s=Jt.exec(n);if(s===null)return ge;const[,c,f,E]=s;if(E!==void 0){const w=Number(E);if(w===0)return Be;const O=Math.max(0,t-w);return{kind:"partial",range:{offset:O,length:t-O}}}const k=Number(c),p=f===""?Number.POSITIVE_INFINITY:Number(f);return p<k?ge:k>=t?Be:{kind:"partial",range:{offset:k,length:Math.min(p,t-1)-k+1}}},Fe="W/",Wt=e=>{const t=[];let r=0,n=!1;for(let a=0;a<e.length;a+=1)e[a]==='"'?n=!n:e[a]===","&&!n&&(t.push(e.slice(r,a).replace(Pe,"")),r=a+1);return t.push(e.slice(r).replace(Pe,"")),t},Ue=e=>e.startsWith(Fe)?e.slice(Fe.length):e,Kt=(e,t)=>{if(e===null)return!1;const r=Wt(e);if(r.length===1&&r[0]==="*")return!0;const n=Ue(t);return r.some(a=>Ue(a)===n)},Vt=(e,t)=>{let r=t;return e.pipeThrough(new TransformStream({transform:(n,a)=>{const s=n.byteLength>r?n.subarray(0,r):n;r-=s.byteLength,a.enqueue(s),r===0&&a.terminate()},flush:n=>{r>0&&n.error(new RangeError("[markdown-explorer] the asset ended before its declared length"))}}))},ke=async(e,t,r,n,a)=>{if(n!==null&&r.set("Content-Length",String(n)),e.method.toUpperCase()==="HEAD")return new Response(null,{status:t,headers:r});const s=await a();return new Response(n===null?s:Vt(s,n),{status:t,headers:r})},Qt=(e,t)=>{const r=new Headers(e);for(const[n,a]of Object.entries({"Accept-Ranges":"bytes","Content-Range":`bytes */${t}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff"}))r.set(n,a);return new Response(null,{status:416,headers:r})},Zt=async(e,t,r)=>{const n=`"${t.version}"`,a=Gt(t.contentType,t.name),s=new Headers(r);for(const[E,k]of Object.entries({...a.headers,...Xt,ETag:n}))s.set(E,k);if(Kt(e.headers.get("If-None-Match"),n))return new Response(null,{status:304,headers:s});if(s.set("Content-Type",a.contentType),t.size===null)return ke(e,200,s,null,()=>t.open(null));if(t.size===0)return s.set("Content-Length","0"),new Response(null,{status:200,headers:s});s.set("Accept-Ranges","bytes");const c=Yt(e.headers,t.size,n);if(c.kind==="unsatisfiable")return Qt(r,t.size);if(c.kind==="whole")return ke(e,200,s,t.size,()=>t.open(null));const{range:f}=c;return s.set("Content-Range",`bytes ${f.offset}-${f.offset+f.length-1}/${t.size}`),ke(e,206,s,f.length,()=>t.open(f))},Re=(e,t)=>{const r=new AbortController,n=t(AbortSignal.any([e.signal,r.signal]));return new Promise(a=>{let s;const c=setTimeout(()=>{a(e.late),s=setTimeout(()=>r.abort(),e.handOverMs)},e.timeoutMs),f=()=>{clearTimeout(c),clearTimeout(s)};n.then(E=>{f(),a(E)},()=>{f(),a(e.late)})})},qt=Object.freeze({error:(e,t)=>{console.error(e,t)}}),pt=Symbol.for("@aiquants/markdown-explorer:ExplorerError");class he extends Error{reason;code;constructor(t,r={}){if(!b.isExplorerFailureReason(t))throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${JSON.stringify(t)}`);if(r.code!==void 0&&!b.isExplorerFailureCode(r.code))throw new RangeError(`[markdown-explorer] an ExplorerError code must be 1 to 64 lowercase letters, digits or hyphens; got ${JSON.stringify(r.code)}`);super(`[markdown-explorer] ${t}`,r.cause===void 0?void 0:{cause:r.cause}),this.name="ExplorerError",this.reason=t,this.code=r.code,Object.defineProperty(this,pt,{value:!0})}}const er=e=>e instanceof Error&&Object.hasOwn(e,pt)&&b.isExplorerFailureReason(e.reason),tr=e=>typeof e=="object"&&e!==null&&e.name==="AbortError",Me=(e,t,r)=>{try{e.error(t,r)}catch(n){console.error("[markdown-explorer] the logger threw while reporting a failure",{operation:r.operation,error:n})}},ne=(e,t)=>Me(e,`[markdown-explorer] ${t.operation} failed`,t),rr=(e,t)=>Me(e,`[markdown-explorer] ${t.operation} left out an entry`,t),Xe=(e,t)=>Me(e,`[markdown-explorer] ${t.operation} refused a path the deny rules match`,{...t,error:new RangeError("[markdown-explorer] the path matches a deny rule")}),Ge=(e,t)=>{e===null||typeof e!="object"&&typeof e!="function"||Promise.resolve(e).then(void 0,t)},Z=(e,t,r,n)=>er(e)?b.failureOf(e.reason,e.code):(tr(e)||r.aborted||ne(n,{...t,error:e}),{reason:"failed"}),nr=2*1024*1024,or=256*1024*1024,sr=async(e,t)=>{const r=e.getReader(),n=new Uint8Array(t);let a=0;for(;a<t;){const{done:s,value:c}=await r.read();if(s)return n.subarray(0,a);const f=c.subarray(0,t-a);n.set(f,a),a+=f.byteLength}return r.cancel().catch(()=>{}),n},ar=async(e,t)=>{if(e.size===0)return{text:"",truncated:!1};const r=e.size!==null&&e.size>t,n=e.size===null?t+1:Math.min(e.size,t),a=await sr(await e.open(r?{offset:0,length:t}:null),n);if(e.size!==null&&a.byteLength<n)throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");const s=r||a.byteLength>t,c=s?a.subarray(0,t):a;return c.includes(0)?null:{text:new TextDecoder("utf-8").decode(c,{stream:s}),truncated:s}},Je=(e,t)=>{if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] a cache ${e} must be a positive integer; got ${String(t)}`)},ht=(e,t)=>{Je("capacity",e),t!==void 0&&Je("weight budget",t.max);const r=new Map;let n=0;const a=s=>{const c=r.get(s);c!==void 0&&(r.delete(s),n-=c.weight)};return{get:s=>{const c=r.get(s);if(c!==void 0)return r.delete(s),r.set(s,c),c.value},set:(s,c)=>{a(s);const f=t===void 0?0:t.of(s,c);if(!(t!==void 0&&f>t.max)){r.set(s,{value:c,weight:f}),n+=f;for(const E of r.keys()){if(r.size<=e&&(t===void 0||n<=t.max))break;a(E)}}},delete:a,size:()=>r.size,weight:()=>n}},wt=e=>Math.max(1,e-1),ir=2147483647,Ye=Object.freeze({status:"aborted"}),ce=(e,t,r)=>{const n=(e.get(t)??0)+r;n===0?e.delete(t):e.set(t,n)},le=(e,t,r)=>{if(!Number.isSafeInteger(t)||t<=0||t>r)throw new RangeError(`[markdown-explorer] a worker pool's ${e} must be an integer in 1..${String(r)}; got ${String(t)}`)},cr=e=>e!==null&&typeof e=="object"&&e.ready===!0&&!("id"in e),ur=(e,t)=>e!==null&&typeof e=="object"&&e.id===t&&"output"in e,lr=({url:e,size:t,deadlineMs:r,jobsPerScope:n,maxQueuedJobs:a,heapLimits:s})=>{le("size",t,Number.MAX_SAFE_INTEGER),le("deadline",r,ir),le("jobsPerScope",n,Number.MAX_SAFE_INTEGER),le("maxQueuedJobs",a,Number.MAX_SAFE_INTEGER),le("maxOldGenerationSizeMb",s.maxOldGenerationSizeMb,Number.MAX_SAFE_INTEGER),le("maxYoungGenerationSizeMb",s.maxYoungGenerationSizeMb,Number.MAX_SAFE_INTEGER);const c=Object.freeze({maxOldGenerationSizeMb:s.maxOldGenerationSizeMb,maxYoungGenerationSizeMb:s.maxYoungGenerationSizeMb}),f=new Set,E=[],k=new Map,p=new Map,w=wt(t);let O=0;const A=(d,y)=>{const{job:h}=d;d.timer!==null&&clearTimeout(d.timer),d.timer=null,d.job=null,d.sent=!1,h!==null&&(ce(k,h.scope,-1),ce(p,h.scope,-1),h.settle(y))},v=d=>{const[y]=E.splice(d,1);y?.detach()},_=()=>{let d=-1,y=w,h=Number.POSITIVE_INFINITY;for(const[x,T]of E.entries()){const N=k.get(T.scope)??0,L=p.get(T.scope)??0;(N<y||N===y&&d>=0&&L<h)&&(d=x,y=N,h=L)}return d},R=(d,y)=>{f.has(d)&&(f.delete(d),A(d,y),d.worker.terminate().catch(()=>{}),j())},D=d=>{d.timer=setTimeout(()=>{R(d,{status:"timeout"})},r)},S=(d,y)=>d.sent?{status:"crashed",error:y}:{status:"unavailable",error:y},P=(d,y)=>{d.sent=!0,D(d);try{d.worker.postMessage({id:y.id,input:y.input})}catch(h){A(d,{status:"crashed",error:h}),d.worker.unref()}},B=()=>{const d={worker:new It.Worker(e,{resourceLimits:c}),job:null,sent:!1,timer:null,ready:!1};return d.worker.unref(),d.timer=setTimeout(()=>{R(d,{status:"unavailable",error:new Error(`[markdown-explorer] a worker did not start within ${String(r)} ms`)})},r),d.worker.on("message",y=>{if(!d.ready&&cr(y)){d.ready=!0,d.timer!==null&&clearTimeout(d.timer),d.timer=null,d.job===null?d.worker.unref():P(d,d.job),d.job===null&&j();return}const{job:h}=d;if(h===null||!ur(y,h.id)){R(d,S(d,new Error("[markdown-explorer] a worker sent a message that answers no job")));return}A(d,{status:"done",output:y.output}),d.worker.unref(),j()}),d.worker.on("error",y=>{R(d,S(d,y))}),d.worker.on("messageerror",y=>{R(d,S(d,y))}),d.worker.on("exit",y=>{R(d,S(d,new Error(`[markdown-explorer] a worker exited with code ${String(y)}`)))}),f.add(d),d},j=()=>{for(;;){const d=_(),y=E[d];if(y===void 0)return;let h;for(const T of f)if(T.job===null){h=T;break}if(h===void 0&&f.size<t)try{h=B()}catch(T){v(d),ce(p,y.scope,-1),y.settle({status:"unavailable",error:T});continue}if(h===void 0)return;v(d),ce(k,y.scope,1);const x=h;x.job=y,x.worker.ref(),x.ready&&P(x,y)}};return{run:(d,{scope:y,signal:h})=>new Promise(x=>{if(h.aborted){x(Ye);return}if((p.get(y)??0)>=n){x({status:"refused",limit:"scope"});return}O+=1;const T={id:O,input:d,scope:y,settle:x,detach:()=>{}};E.push(T),ce(p,y,1),j();const N=E.indexOf(T);if(N<0)return;if(E.length>a){v(N),ce(p,y,-1),x({status:"refused",limit:"queue"});return}const L=()=>{const F=E.indexOf(T);F<0||(v(F),ce(p,y,-1),x(Ye))};h.addEventListener("abort",L,{once:!0}),T.detach=()=>{h.removeEventListener("abort",L)}}),workers:()=>f.size}},ve=1024*1024,dr=3e4,fr=4*ve,mr=64*ve,pr=3,hr=2,wr=(e,t)=>e+wt(t)+pr,gr=4,Er=32,yr=512,br=64,Tr=4096,Sr=32,We=4096,xr=4,gt=({workerHeapMb:e,maxHtmlBytes:t})=>Math.floor(((e-br)*ve-t*Sr)/Tr),Or=({maxHtmlBytes:e})=>e,kr=({maxHtmlBytes:e})=>xr*e,Rr=1024,_r=2147483647,Ar=64,Nr=2**29,Pr=1024*1024,Ir=64,Ke=Object.freeze({status:"rejected",reason:"too-large",cause:null}),_e=Object.freeze({status:"rejected",reason:"failed",cause:null}),ue=(e,t,r,n)=>{if(t===void 0)return r;if(typeof t!="number")throw new TypeError(`[markdown-explorer] sanitizer.${e} must be a number; got ${typeof t}`);if(!Number.isSafeInteger(t)||t<=0||t>n)throw new RangeError(`[markdown-explorer] sanitizer.${e} must be an integer in 1..${String(n)}; got ${String(t)}`);return t},Mr=(e,t)=>{if(e!==void 0&&(e===null||typeof e!="object"))throw new TypeError("[markdown-explorer] sanitizer must be an object of { workers, deadlineMs, maxHtmlBytes, cacheBytes, workerHeapMb, jobsPerScope, maxQueuedJobs }");const{workers:r,deadlineMs:n,maxHtmlBytes:a,cacheBytes:s,workerHeapMb:c,jobsPerScope:f,maxQueuedJobs:E}=e??{},k=ue("workers",r,hr,Ar),p=ue("jobsPerScope",f,wr(t,k),Number.MAX_SAFE_INTEGER),w=Object.freeze({workers:k,deadlineMs:ue("deadlineMs",n,dr,_r),maxHtmlBytes:ue("maxHtmlBytes",a,fr,Nr),cacheBytes:ue("cacheBytes",s,mr,Number.MAX_SAFE_INTEGER),workerHeapMb:ue("workerHeapMb",c,yr,Pr),jobsPerScope:p,maxQueuedJobs:ue("maxQueuedJobs",E,gr*p,Number.MAX_SAFE_INTEGER)});if(w.jobsPerScope<t)throw new RangeError(`[markdown-explorer] sanitizer.jobsPerScope must be at least multiView.maxPanels (${String(t)}), because a page sends the document of every panel to the sanitizer at once for one reader; got ${String(w.jobsPerScope)}`);if(w.maxQueuedJobs<t)throw new RangeError(`[markdown-explorer] sanitizer.maxQueuedJobs must be at least multiView.maxPanels (${String(t)}), because a reader whose page finds every worker busy waits with the document of every panel; got ${String(w.maxQueuedJobs)}`);if(gt(w)<We)throw new RangeError(`[markdown-explorer] sanitizer.workerHeapMb (${String(w.workerHeapMb)} MiB) must leave room for ${String(We)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(w.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`);return w},vr=()=>{const e=typeof document>"u"?require("url").pathToFileURL(__filename).href:Oe&&Oe.tagName.toUpperCase()==="SCRIPT"&&Oe.src||new URL("server.cjs",document.baseURI).href,t=new URL(`./sanitizeWorker${re.extname(xe.fileURLToPath(e))}`,e);if(!ae.existsSync(xe.fileURLToPath(t)))throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${xe.fileURLToPath(t)}`);return t},Ve=new Map,Lr=(e,t)=>{const r=[e.href,t.workers,t.deadlineMs,t.workerHeapMb,t.jobsPerScope,t.maxQueuedJobs].map(String).join("\0");let n=Ve.get(r);return n===void 0&&(n=lr({url:e,size:t.workers,deadlineMs:t.deadlineMs,jobsPerScope:t.jobsPerScope,maxQueuedJobs:t.maxQueuedJobs,heapLimits:{maxOldGenerationSizeMb:t.workerHeapMb,maxYoungGenerationSizeMb:Er}}),Ve.set(r,n)),n},$r=e=>{if(e===null||typeof e!="object")return!1;const{status:t,html:r,message:n}=e;return t==="sanitized"&&typeof r=="string"||t==="too-large"||t==="error"&&typeof n=="string"},Dr=e=>e instanceof Error&&e.code==="ERR_WORKER_OUT_OF_MEMORY",jr=({iframeHosts:e,dataPath:t,options:r,pool:n})=>{const a=Object.freeze([...e]),s=gt(r),c=Or(r),f=kr(r),E=ht(Rr,{max:r.cacheBytes,of:(_,R)=>2*_.length+(R.status==="sanitized"?2*R.html.length:Ir)}),k=new Map,p=new Map,w=_=>{k.get(_.key)===_&&k.delete(_.key);const R=p.get(_.hash);R?.delete(_),R?.size===0&&p.delete(_.hash)},O=async(_,R,D)=>{const S=await n.run({html:_,iframeHosts:a,dataPath:t,maxNodes:s,maxAttributeChars:c,maxSanitizedChars:f},{scope:R,signal:D});if(S.status==="refused"){const B=S.limit==="scope"?`its reader already has ${String(r.jobsPerScope)} documents being sanitized or waiting`:`${String(r.maxQueuedJobs)} documents are already waiting`;return{outcome:{status:"rejected",reason:"failed",cause:new Error(`[markdown-explorer] the HTML sanitizer refused a document: ${B}`)},lasting:!1}}if(S.status==="aborted")return{outcome:_e,lasting:!1};if(S.status==="timeout")return{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer did not finish within ${String(r.deadlineMs)} ms`)},lasting:!0};if(S.status==="unavailable")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker could not start",{cause:S.error})},lasting:!1};if(S.status==="crashed"&&Dr(S.error))return{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer ran out of its ${String(r.workerHeapMb)} MiB worker heap`,{cause:S.error})},lasting:!0};if(S.status==="crashed")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker failed",{cause:S.error})},lasting:!0};const{output:P}=S;return $r(P)?P.status==="too-large"?{outcome:Ke,lasting:!0}:P.status==="error"?{outcome:{status:"rejected",reason:"failed",cause:new Error(`[markdown-explorer] the HTML sanitizer failed: ${P.message}`)},lasting:!0}:P.html.length>f?{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer's output of ${String(P.html.length)} characters exceeds its limit of ${String(f)}`)},lasting:!0}:{outcome:{status:"sanitized",html:P.html},lasting:!0}:{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker answered something that is not an outcome")},lasting:!0}},A=(_,R,D,S)=>{let P=()=>{};const B=new Promise(y=>{P=y}),j={hash:R,key:D,outcome:B,answer:P,controller:new AbortController,waiters:0};k.set(D,j);const d=p.get(R);return d===void 0?p.set(R,new Set([j])):d.add(j),O(_,S,j.controller.signal).catch(y=>({outcome:{status:"rejected",reason:"failed",cause:y instanceof Error?y:new Error(String(y))},lasting:!0})).then(({outcome:y,lasting:h})=>{if(w(j),j.answer(y),!h)return;const x=E.get(R),T=x??(y.status==="rejected"?{...y,cause:null}:y);x===void 0&&E.set(R,T);for(const N of p.get(R)??[])w(N),N.answer(T),N.controller.abort()}),j},v=(_,R)=>new Promise(D=>{_.waiters+=1;const S=()=>{_.waiters-=1,D(_e),!(_.waiters>0)&&(w(_),_.controller.abort())};R.addEventListener("abort",S,{once:!0}),_.outcome.then(P=>{R.removeEventListener("abort",S),D(P)})});return(_,{scope:R,signal:D})=>{if(_.length>r.maxHtmlBytes||Buffer.byteLength(_,"utf8")>r.maxHtmlBytes)return Promise.resolve(Ke);const S=dt.createHash("sha256").update(_,"utf8").digest("base64"),P=E.get(S);if(P!==void 0)return Promise.resolve(P);if(D.aborted)return Promise.resolve(_e);const B=`${S}\0${R}`,j=k.get(B);return v(j===void 0?A(_,S,B,R):j,D)}},Te=e=>({result:e,json:JSON.stringify(e)}),Ae=Object.freeze(Te(Object.freeze({status:"error",failure:Object.freeze({reason:"failed"})}))),zr=e=>e.status==="ok"&&e.entries.length>0,Cr=({ttlMs:e,maxEntries:t,maxBytes:r,now:n})=>{const a=ht(t,{max:r,of:(p,w)=>2*w.tree.json.length}),s=new Map,c=new Map,f=(p,w)=>{const O=new AbortController,A={waiters:0,superseded:!1,started:!1,loadTree:w},v=c.get(p),_=(B,j)=>{const d=Te(B);return!(A.superseded||O.signal.aborted)&&zr(B)&&a.set(p,{tree:d,loadedAt:j}),d},D=(async()=>{if(v!==void 0&&await v,O.signal.aborted)return Ae;const B=n();return A.started=!0,_(await A.loadTree(O.signal,B),B)})().finally(()=>{s.get(p)===S&&s.delete(p)}),S={promise:D,controller:O,state:A};s.set(p,S);const P=D.then(()=>{},()=>{});return c.set(p,P),P.then(()=>{c.get(p)===P&&c.delete(p)}),S},E=(p,w,O)=>{w.state.waiters+=1;const A=()=>{w.state.waiters-=1,!(w.state.waiters>0)&&(s.get(p)===w&&s.delete(p),w.controller.abort())};return O.addEventListener("abort",A,{once:!0}),w.promise.finally(()=>{O.removeEventListener("abort",A)})},k=p=>{a.delete(p);const w=s.get(p);w?.state.started&&(w.state.superseded=!0,s.delete(p))};return{load:(p,w,O)=>{if(w.aborted)return Promise.resolve(Ae);const A=a.get(p);if(A!==void 0){if(n()-A.loadedAt<e)return Promise.resolve(A.tree);a.delete(p)}const v=s.get(p);return E(p,v===void 0?f(p,O):v,w)},refresh:(p,w,O)=>{if(w.aborted)return Promise.resolve(Ae);k(p);const A=s.get(p);return A===void 0?E(p,f(p,O),w):(A.state.loadTree=O,E(p,A,w))},forget:k}},Hr=e=>({load:(t,r,n)=>n(r,e()).then(Te),refresh:(t,r,n)=>n(r,e()).then(Te),forget:()=>{}}),$=e=>{throw new TypeError(`[markdown-explorer] ${e}`)},Br=e=>{if(e===null||typeof e!="object")return null;const{name:t,path:r}=e;return typeof t!="string"||typeof r!="string"?null:t===""?{path:r,reason:"an empty name"}:b.isAcceptableDocumentPath(r)?null:{path:r,reason:"a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)"}},Fr=(e,t,r,n)=>{if(e===null)return null;if(!Array.isArray(e))throw new TypeError(`[markdown-explorer] a source's ancestors must be null or an array of folder paths; got ${typeof e}`);const a=new Set;for(const s of e){if(typeof s!="string"||!b.isAcceptableDocumentPath(s))throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");if(r.deniesPath(s))throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");if(!n(s))throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");if(s===t)throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");if(a.has(s))throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");a.add(s)}return Object.freeze([...a])},Ur=(e,t,r,n,a)=>{const s=new Set,c=E=>{if(!Array.isArray(E))return $("a source returned entries that are not an array");const k=[];for(const p of E){const w=f(p);w!==null&&k.push(w)}return k},f=E=>{const k=Br(E);if(k!==null)return n(k),null;const p=b.entryViolation(E);if(p!==null)return $(p);const w=E;if(s.has(w))return $("a source returned entries that contain themselves");const{name:O,path:A,type:v,mimeType:_,children:R,lazy:D}=w;if(t.deniesName(O)||t.deniesPath(A))return null;if(!a(A))return n({path:A,reason:"a path outside the source's boundary"}),null;const S=_===void 0?{name:O,path:A}:{name:O,path:A,mimeType:_};if(v==="file")return{...S,type:v};if(D===!0)return r?{...S,type:v,lazy:!0,children:[]}:$("a lazy directory came from a source without a children function");if(R===void 0)return{...S,type:v};s.add(w);const P=c(R);return s.delete(w),{...S,type:v,children:P}};return c(e)},Xr=/^[\x21\x23-\x7E]{1,256}$/u,Et=e=>typeof e=="string"&&Xr.test(e),Gr=new Set(["text","image","media","file"]),Jr=e=>typeof e=="string"&&Gr.has(e),Yr=(e,t)=>{if(e!==null&&typeof e=="object"){const a=e,{kind:s}=a;if(Jr(s)){if(Object.hasOwn(a,"url"))return $(`a ${s} document carries its version, not a url`);if(typeof a.name!="string")return $("a document needs a name string");if(!Et(a.version))return $(`a ${s} document needs a version of 1 to 256 visible ASCII characters other than '"'`);const c=t(a.version);switch(s){case"image":case"file":return{kind:s,name:a.name,url:c};case"media":{const{mediaType:f}=a;return b.isExplorerMediaType(f)?{kind:s,name:a.name,url:c,mediaType:f}:$(`unknown media type ${typeof f=="string"?JSON.stringify(f.slice(0,64)):typeof f}`)}case"text":return typeof a.text!="string"||typeof a.truncated!="boolean"?$("a text document needs text and truncated"):{kind:s,name:a.name,text:a.text,truncated:a.truncated,url:c}}}}const r=b.documentViolation(e);if(r!==null)return $(r);const n=e;switch(n.kind){case"failure":{const{reason:a,code:s}=n.failure;return{kind:"failure",failure:b.failureOf(a,s)}}case"markdown":return n.headings.length>b.EXPLORER_MAX_HEADINGS?{kind:"failure",failure:b.failureOf("too-large")}:{kind:"unsanitized-markdown",name:n.name,html:n.htmlContent,headings:n.headings.map(({text:a,depth:s,id:c})=>({text:a,depth:s,id:c}))}}},Qe=e=>{if(e===null||typeof e!="object")return $("an asset file must be an object");const{name:t,contentType:r,size:n,version:a,open:s}=e;return typeof t!="string"||t===""?$("an asset file needs a non-empty name"):typeof r!="string"?$("an asset file needs a contentType string ('' when unknown)"):n!==null&&!(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)?$("an asset file's size must be null or a non-negative safe integer"):Et(a)?typeof s!="function"?$("an asset file needs an open function"):Object.freeze({name:t,contentType:r,size:n,version:a,open:s}):$(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`)},Wr=e=>Array.isArray(e)?e.map(t=>{if(t===null||typeof t!="object")return $("a notice must be an object");const{id:r,tone:n,title:a,body:s,action:c}=t;if(typeof r!="string"||r===""||typeof a!="string")return $("a notice needs an id and a title");if(!b.isExplorerNoticeTone(n))return $(`unknown notice tone ${typeof n=="string"?JSON.stringify(n.slice(0,64)):typeof n}`);if(s!==void 0&&typeof s!="string")return $("a notice body must be a string");const E={id:r,tone:n,title:a,...s===void 0?{}:{body:s}};if(c===void 0)return E;if(c===null||typeof c!="object")return $("a notice action must be an object");const{label:k,href:p}=c;return typeof k!="string"||!b.isAcceptableUrl(p,b.EXPLORER_LINK_PROTOCOLS)?$("a notice action needs a label and an http(s), mailto or relative href"):{...E,action:{label:k,href:p}}}):$("notices must be an array"),Kr=4e3,Ee=Object.freeze({ttlMs:3e5,maxEntries:64,maxBytes:64*1024*1024}),Ze=32,yt="private, no-store",Vr=Object.freeze({"Content-Type":"application/json; charset=utf-8","Cache-Control":yt,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; frame-ancestors 'none'; sandbox","Cross-Origin-Resource-Policy":"same-origin"}),Qr=22,Zr=2147483647,Ne=Object.freeze([]),qr=Object.freeze({status:"ok",source:null,ancestors:null}),qe=Object.freeze(["contains","confirm"]),et=Object.freeze({readOnly:!1}),en=Object.freeze({readOnly:!0}),W=(e,t,r)=>{if(!(r&&t===void 0)&&typeof t!="function")throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${typeof t}`)},pe=(e,t,r)=>{if(typeof t!="number")throw new TypeError(`[markdown-explorer] ${e} must be a number; got ${typeof t}`);if(!Number.isSafeInteger(t)||t<=0||t>r)throw new RangeError(`[markdown-explorer] ${e} must be an integer in 1..${String(r)}; got ${String(t)}`);return t},tn=e=>{if(e===null||typeof e!="object"||!Object.isFrozen(e))throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");return se.revalidateExplorerConfig(e)},tt=e=>{try{return new Headers(e)}catch{throw new TypeError("[markdown-explorer] authenticate returned headers that are not a valid headers init (their values are not logged)")}},rt=e=>e instanceof Response?new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`):e,rn=e=>{if(typeof e!="string")throw new TypeError(`[markdown-explorer] scopeSecret must be a string; got ${typeof e}`);if(e.length<Ze)throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(Ze)} characters; got ${String(e.length)}`);return e},nn=(e,t)=>{if(!se.isPlainObject(t))throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);for(const r of Object.keys(t))if(!qe.includes(r))throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${qe.join(", ")}`);W(`${e}.boundary.contains`,t.contains,!1),W(`${e}.boundary.confirm`,t.confirm,!0)},on=e=>{if(!Array.isArray(e))throw new TypeError("[markdown-explorer] sources must be an array");const t=e;if(t.length===0)throw new RangeError("[markdown-explorer] sources must hold at least one source");const r=new Set;for(const[n,a]of t.entries()){if(a===null||typeof a!="object")throw new TypeError(`[markdown-explorer] sources[${String(n)}] must be an object`);const{id:s,label:c,boundary:f,tree:E,children:k,ancestors:p,cacheScope:w}=a;if(!se.isExplorerSourceId(s))throw new RangeError(`[markdown-explorer] sources[${String(n)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${typeof s=="string"?JSON.stringify(s):typeof s}`);const O=`source ${JSON.stringify(s)}`;if(r.has(s))throw new RangeError(`[markdown-explorer] source ids must be unique; ${JSON.stringify(s)} repeats at sources[${String(n)}]`);if(r.add(s),typeof c!="string"&&typeof c!="function")throw new TypeError(`[markdown-explorer] ${O}.label must be a string or a function`);if(typeof c=="string"&&c.trim()==="")throw new RangeError(`[markdown-explorer] ${O}.label must not be blank`);if(nn(O,f),W(`${O}.tree`,E,!1),W(`${O}.children`,k,!0),W(`${O}.ancestors`,p,!0),w!==void 0&&w!=="principal"&&w!=="shared")throw new RangeError(`[markdown-explorer] ${O}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(w)}`)}return t},sn=e=>{if(e===!1)return!1;if(e===void 0)return Ee;if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] treeCache must be { ttlMs, maxEntries, maxBytes } or false");const{ttlMs:t,maxEntries:r,maxBytes:n}=e;return{ttlMs:t===void 0?Ee.ttlMs:pe("treeCache.ttlMs",t,Number.MAX_SAFE_INTEGER),maxEntries:r===void 0?Ee.maxEntries:pe("treeCache.maxEntries",r,Number.MAX_SAFE_INTEGER),maxBytes:n===void 0?Ee.maxBytes:pe("treeCache.maxBytes",n,Number.MAX_SAFE_INTEGER)}},nt=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] authenticate must resolve to { status, ... }");const{status:t}=e;if(t!=="signed-in"&&t!=="signed-out"&&t!=="forbidden")throw new TypeError(`[markdown-explorer] authenticate resolved to an unknown status ${JSON.stringify(t)}`);return e},ot=(e,t)=>{if(!(t instanceof Response))throw new TypeError(`[markdown-explorer] ${e} must return a Response`);return t},st=(e,t)=>{if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");return dt.createHmac("sha256",e).update(t,"utf8").digest("base64url").slice(0,Qr)},an=e=>e.view==="multi"?e.docs:e.doc===null?[]:[e.doc],fe=(e,t)=>{const r=e.getAll(t),[n]=r;return r.length===1&&n!==void 0&&n!==""?n:null},oe=(e,t,r,n={})=>{const a=new Headers(r);for(const[s,c]of Object.entries({...Vr,...n}))a.set(s,c);return new Response(t,{status:e,headers:a})},U=(e,t,r)=>oe(b.EXPLORER_FAILURE_STATUS[e.reason],JSON.stringify({failure:e}),t,r),at=(e,t)=>{const r=t==="refresh"?["POST"]:["GET","HEAD"];return r.includes(e.method.toUpperCase())?null:oe(405,JSON.stringify({failure:{reason:"invalid"}}),void 0,{Allow:r.join(", ")})},it=e=>e.headers.get(b.EXPLORER_REFRESH_HEADER)===b.EXPLORER_REFRESH_HEADER_VALUE&&ze.crossOriginRefusal(e,ze.NO_CROSS_ORIGIN_NAVIGATION)===void 0,cn=({parentHeaders:e,loaderHeaders:t,errorHeaders:r})=>{const n=new Headers,a=r===void 0?[e,t]:[e,t,r];for(const s of a)for(const[c,f]of s)c!=="set-cookie"&&n.set(c,f);return n},un=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the server configuration must be an object");const t=tn(e.config),r=rn(e.scopeSecret);W("authenticate",e.authenticate,!1),W("principalKey",e.principalKey,!1),W("document",e.document,!1),W("asset",e.asset,!1),W("signedOutPage",e.signedOutPage,!1),W("forbiddenPage",e.forbiddenPage,!0),W("notices",e.notices,!0),W("onTreeRefreshed",e.onTreeRefreshed,!0);const n=on(e.sources),a=se.withExplorerSources(t,n.map(o=>o.id)),s=e.logger;if(s!==void 0&&(s===null||typeof s!="object"||typeof s.error!="function"))throw new TypeError("[markdown-explorer] logger must be an object with an error function");const c=e.logger===void 0?qt:e.logger,f=b.resolvePathRules(e.deny),E=e.deferredTimeoutMs===void 0?Kr:pe("deferredTimeoutMs",e.deferredTimeoutMs,Zr),k=e.textMaxBytes===void 0?nr:pe("textMaxBytes",e.textMaxBytes,or),p=sn(e.treeCache),w=()=>Date.now(),O=p===!1?Hr(w):Cr({...p,now:w}),A=Mr(e.sanitizer,t.multiView.maxPanels),v=jr({iframeHosts:t.iframeHosts,dataPath:t.dataPath,options:A,pool:Lr(vr(),A)}),_=new Map(n.map(o=>[o.id,o])),R=se.documentStyleNames(t),{authenticate:D,principalKey:S,signedOutPage:P,forbiddenPage:B,onTreeRefreshed:j}=e,d=(o,l)=>{if(typeof o.label=="string")return o.label;const i=o.label(l);if(typeof i!="string"||i.trim()==="")throw new TypeError(`[markdown-explorer] the label of source ${JSON.stringify(o.id)} must be a non-blank string`);return i},y=(o,l)=>o.cacheScope==="shared"?o.id:`${o.id}\0${l}`,h=(o,l)=>{const i=m=>ne(c,{operation:"boundary",sourceId:o.id,path:l,error:m});let u;try{u=o.boundary.contains(l)}catch(m){return i(m),!1}return typeof u=="boolean"?u:(Ge(u,i),i(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(o.id)} must return a boolean; got ${typeof u}`)),!1)},x=async(o,l,i)=>{const{confirm:u}=o.boundary;if(u===void 0)return{status:"inside",readPath:i};let m;try{m=await u(l,i)}catch(Y){return{status:"error",failure:Z(Y,{operation:"boundary",sourceId:o.id,path:i},l.signal,c)}}const g=Y=>(ne(c,{operation:"boundary",sourceId:o.id,path:i,error:new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} ${Y}`)}),{status:"outside"});if(m===null||typeof m!="object")return g(`must resolve to { inside, readPath? }; got ${m===null?"null":typeof m}`);const{inside:M,readPath:C}=m;return M===!1?{status:"outside"}:M!==!0||typeof C!="string"?g("must resolve to { inside: false } or { inside: true, readPath: string }"):!b.isAcceptableDocumentPath(C)||f.deniesPath(C)?(ne(c,{operation:"boundary",sourceId:o.id,path:i,error:new RangeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} answered a readPath the explorer does not serve (unacceptable or denied)`)}),{status:"error",failure:{reason:"failed"}}):{status:"inside",readPath:C}},T=async(o,l)=>{const i=n.filter(m=>h(m,l));if(i.length===0)return{status:"error",failure:{reason:"forbidden"}};if(i.some(m=>m.boundary.confirm===void 0))return{status:"inside",readPath:l};let u=null;for(const m of i){const g=await x(m,o,l);if(g.status==="inside")return g;g.status==="error"&&u===null&&(u=g.failure)}return{status:"error",failure:u===null?{reason:"forbidden"}:u}},N=(o,l,i)=>{const u=({path:m,reason:g})=>rr(c,{operation:i.operation,sourceId:i.sourceId,path:m,error:new TypeError(`[markdown-explorer] an entry with ${g} was left out`)});try{return{status:"ok",entries:Ur(o,f,l.children!==void 0,u,m=>h(l,m))}}catch(m){return ne(c,{...i,error:m}),{status:"error",failure:{reason:"failed"}}}},L=async(o,l,i)=>{let u;try{u=await o.tree(l)}catch(g){return{status:"error",failure:Z(g,{operation:"tree",sourceId:o.id},l.signal,c)}}const m=N(u,o,{operation:"tree",sourceId:o.id});return m.status==="ok"?{status:"ok",entries:m.entries,loadedAt:i}:m},F=(o,l,i,u)=>(m,g)=>L(o,{principal:l,request:i,signal:m,refresh:u},g),I=(o,l,i,u,m)=>O.load(y(o,i),m,F(o,l,u,!1)),G=(o,l,i,u)=>O.refresh(y(o,i),u.signal,F(o,l,u,!0)),K=(o,l)=>{if(j===void 0)return;const i=u=>ne(c,{operation:"refresh",sourceId:o.id,error:u});try{Ge(j(l),i)}catch(u){i(u)}},X=async(o,l,i,u)=>{if(f.deniesPath(u)||!h(o,u))return{status:"error",failure:{reason:"forbidden"}};const m=await x(o,i,u);if(m.status==="outside")return{status:"error",failure:{reason:"forbidden"}};if(m.status==="error")return{status:"error",failure:m.failure};let g;try{g=await l(i,u,m.readPath)}catch(M){return{status:"error",failure:Z(M,{operation:"children",sourceId:o.id,path:u},i.signal,c)}}return N(g,o,{operation:"children",sourceId:o.id,path:u})},te=async(o,l,i,u)=>{const m=await x(o,i,u);if(m.status==="outside")return{status:"ok",ancestors:null};if(m.status==="error")return{status:"error",failure:m.failure};let g;try{g=await l(i,u,m.readPath,{maxDepth:t.revealDocument.maxDepth})}catch(M){return{status:"error",failure:Z(M,{operation:"ancestors",sourceId:o.id,path:u},i.signal,c)}}if(Array.isArray(g)&&g.length>t.revealDocument.maxDepth)return{status:"ok",ancestors:null};try{return{status:"ok",ancestors:Fr(g,u,f,M=>h(o,M))}}catch(M){return ne(c,{operation:"ancestors",sourceId:o.id,path:u,error:M}),{status:"error",failure:{reason:"failed"}}}},z=async(o,l,i,u)=>f.deniesPath(u)?{status:"error",failure:{reason:"forbidden"}}:h(o,u)?te(o,l,i,u):{status:"ok",ancestors:null},V=async(o,l,i)=>{if(f.deniesPath(i))return{status:"error",failure:{reason:"forbidden"}};for(const u of[o,...n.filter(m=>m!==o)]){if(l.signal.aborted)break;const m=u.ancestors;if(m===void 0||!h(u,i))continue;const g=await te(u,m,l,i);if(g.status==="ok"&&g.ancestors!==null)return{status:"ok",source:u.id,ancestors:g.ancestors}}return qr},Q=async(o,l,i)=>{if(f.deniesPath(i))return b.failureDocument("forbidden");const u=await T(o,i);if(u.status==="error")return{kind:"failure",failure:u.failure};let m;try{m=await e.document(o,i,u.readPath)}catch(C){return{kind:"failure",failure:Z(C,{operation:"document",path:i},o.signal,c)}}let g;try{g=Yr(m,C=>b.explorerAssetHref(t.dataPath,i,C))}catch(C){return ne(c,{operation:"document",path:i,error:C}),b.failureDocument("failed")}if(g.kind!=="unsanitized-markdown")return g;const M=await v(g.html,{scope:l,signal:o.signal});return M.status==="sanitized"?{kind:"markdown",name:g.name,htmlContent:M.html,headings:g.headings}:(M.cause!==null&&ne(c,{operation:"document",path:i,error:M.cause}),b.failureDocument(M.reason))},q=async o=>{if(e.notices===void 0)return Ne;try{return Wr(await e.notices(o))}catch(l){return Z(l,{operation:"notices"},o.signal,c),Ne}},we=async(o,l,i)=>{const u=fe(l,b.EXPLORER_DATA_QUERY.path);if(u===null||!b.isAcceptableDocumentPath(u))return U({reason:"invalid"},i);if(f.deniesPath(u))return Xe(c,{operation:"asset",path:u}),U({reason:"forbidden"},i);const m=await T(o,u);if(m.status==="error")return U(m.failure,i);try{const g=Qe(await e.asset(o,u,m.readPath));return await Zt(o.request,g,i)}catch(g){return U(Z(g,{operation:"asset",path:u},o.signal,c),i)}},kt=async(o,l)=>{if(f.deniesPath(l))return Xe(c,{operation:"text",path:l}),b.failureDocument("forbidden");const i=await T(o,l);if(i.status==="error")return{kind:"failure",failure:i.failure};try{const u=Qe(await e.asset(o,l,i.readPath)),m=await ar(u,k);return m===null?b.failureDocument("unsupported"):{kind:"text",name:u.name,text:m.text,truncated:m.truncated,url:b.explorerAssetHref(t.dataPath,l,u.version)}}catch(u){return{kind:"failure",failure:Z(u,{operation:"text",path:l},o.signal,c)}}},Rt=async({request:o,url:l,params:i})=>{const u=nt(await D(o,et)),m=tt(u.headers);if(m.set("Cache-Control",yt),u.status==="signed-out")throw ot("signedOutPage",P(o,m));if(u.status==="forbidden")throw B===void 0?Se.data(null,{status:403,headers:m}):ot("forbiddenPage",B(o,m));const g=se.resolveExplorerLocation(a,i["*"],l.searchParams);if(g.kind==="redirect")throw Se.redirect(g.href,{headers:m});const{location:M}=g,{principal:C}=u,Y=st(r,S(C)),ie=_.get(M.source);if(ie===void 0)throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(M.source)}`);const de={signal:o.signal,timeoutMs:E,late:null,handOverMs:E},ee={scope:Y,sources:n.map(H=>({id:H.id,label:d(H,C)})),settings:se.parseViewSettings(se.readCookieValue(o.headers.get("Cookie"),t.settingsCookie),R),tree:M.view==="single"?null:{sourceId:M.source,result:Re(de,H=>I(ie,C,Y,o,H).then(J=>J.result))},documents:an(M).map(H=>({path:H,document:Re(de,J=>Q({principal:C,request:o,signal:J,refresh:!1},Y,H))})),notices:Re({signal:o.signal,timeoutMs:E,late:Ne,handOverMs:0},H=>q({principal:C,request:o,signal:H,refresh:!1}))};return Se.data(ee,{headers:m})},Le=async(o,l)=>{const i=nt(await D(o,l));return{authentication:i,headers:tt(i.headers)}},_t=async(o,l,i)=>{let u;try{u=await Le(l,et)}catch(J){return U(Z(rt(J),{operation:"authenticate"},l.signal,c))}const{authentication:m,headers:g}=u;if(m.status==="signed-out")return U({reason:"unauthorized"},g);if(m.status==="forbidden")return U({reason:"forbidden"},g);const{principal:M}=m;if(o==="asset")return we({principal:M,request:l,signal:l.signal,refresh:!1},i,g);const C=st(r,S(M));g.set(b.EXPLORER_SCOPE_HEADER,C);const Y={principal:M,request:l,signal:l.signal,refresh:!1},ie=()=>U({reason:"invalid"},g);if(o==="document"){const J=fe(i,b.EXPLORER_DATA_QUERY.path);if(J===null||!b.isAcceptableDocumentPath(J))return ie();const je=l.headers.has(b.EXPLORER_REFRESH_HEADER);return je&&!it(l)?U({reason:"forbidden"},g):oe(200,JSON.stringify(await Q({...Y,refresh:je},C,J)),g)}if(o==="text"){const J=fe(i,b.EXPLORER_DATA_QUERY.path);return J===null||!b.isAcceptableDocumentPath(J)?ie():oe(200,JSON.stringify(await kt(Y,J)),g)}const de=fe(i,b.EXPLORER_DATA_QUERY.source),ee=fe(i,b.EXPLORER_DATA_QUERY.path);if(de===null||(o==="children"||o==="ancestors"||o==="reveal")&&(ee===null||!b.isAcceptableDocumentPath(ee)))return ie();const H=_.get(de);if(H===void 0)return U({reason:"not-found"},g);if(o==="tree")return oe(200,(await I(H,M,C,l,l.signal)).json,g);if(o==="refresh"){const J=await G(H,M,C,l);return l.signal.aborted||K(H,y(H,C)),oe(200,J.json,g)}return o==="ancestors"?H.ancestors===void 0||ee===null?U({reason:"not-found"},g):oe(200,JSON.stringify(await z(H,H.ancestors,Y,ee)),g):o==="reveal"?ee===null?ie():oe(200,JSON.stringify(await V(H,Y,ee)),g):H.children===void 0||ee===null?U({reason:"not-found"},g):oe(200,JSON.stringify(await X(H,H.children,Y,ee)),g)},At=async o=>{const{authentication:l,headers:i}=await Le(o,en);if(!i.keys().next().done)throw new TypeError("[markdown-explorer] authenticate returned headers in read-only mode; a read-only authentication must only read the session (none was forwarded)");return l.status==="signed-in"},$e=t.embeds.linkCardEndpoint===null?null:Pt.createLinkCardHandler({authorize:At}),Nt=async(o,l)=>{try{return await o(l)}catch(i){return U(Z(rt(i),{operation:"authenticate"},l.signal,c))}},De=async(o,l,i)=>{if(new URL(o.url).pathname.endsWith(".data"))return U({reason:"not-found"});if(!b.isExplorerDataOperation(i))return U({reason:"not-found"});if(i==="link-card"){if($e===null)return U({reason:"not-found"});const m=at(o,i);return m!==null?m:Nt($e,o)}const u=at(o,i);if(u!==null)return u;if(i==="refresh"&&!it(o))return U({reason:"forbidden"});try{return await _t(i,o,l.searchParams)}catch(m){return U(Z(m,{operation:i},o.signal,c))}};return Object.freeze({loader:Rt,headers:cn,dataLoader:({request:o,url:l,params:i})=>De(o,l,i["*"]),dataAction:({request:o,url:l,params:i})=>De(o,l,i["*"]),forgetTree:o=>{if(typeof o!="string")throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof o}`);O.forget(o)}})},ye=Object.freeze({maxEntries:2e4,maxDocumentBytes:2*1024*1024,textPreviewBytes:8*1024,walkConcurrency:8}),ln=new Set(["md","markdown","mdx"]),bt=new Map([...[["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"],["svg","image/svg+xml"],["webp","image/webp"],["ico","image/x-icon"],["bmp","image/bmp"],["tif","image/tiff"],["tiff","image/tiff"],["avif","image/avif"]].map(([e,t])=>[e,{kind:"image",contentType:t}]),...[["mp4","video/mp4"],["m4v","video/mp4"],["webm","video/webm"],["mov","video/quicktime"],["avi","video/x-msvideo"],["mkv","video/x-matroska"],["ogv","video/ogg"]].map(([e,t])=>[e,{kind:"media",mediaType:"video",contentType:t}]),...[["mp3","audio/mpeg"],["wav","audio/wav"],["ogg","audio/ogg"],["oga","audio/ogg"],["opus","audio/ogg"],["m4a","audio/mp4"],["flac","audio/flac"],["aac","audio/aac"],["wma","audio/x-ms-wma"]].map(([e,t])=>[e,{kind:"media",mediaType:"audio",contentType:t}]),["pdf",{kind:"media",mediaType:"pdf",contentType:"application/pdf"}]]),dn=new Set(["txt","text","log","csv","tsv","json","jsonc","json5","ndjson","yaml","yml","toml","ini","cfg","conf","properties","xml","xsl","xsd","dtd","html","htm","xhtml","css","scss","sass","less","styl","js","mjs","cjs","jsx","ts","mts","cts","tsx","vue","svelte","astro","py","pyi","rb","go","rs","java","kt","kts","scala","groovy","gradle","c","h","cc","cpp","cxx","hpp","hh","hxx","cs","fs","vb","swift","m","mm","php","pl","pm","r","jl","lua","dart","ex","exs","erl","hrl","hs","ml","mli","clj","cljs","elm","nim","zig","v","sol","tf","hcl","nix","sh","bash","zsh","fish","ps1","psm1","bat","cmd","sql","graphql","gql","proto","thrift","avsc","rst","adoc","asciidoc","tex","bib","org","textile","diff","patch","srt","vtt","ics","vcf","gitignore","gitattributes","editorconfig","dockerignore","npmignore","prettierrc","eslintrc","babelrc","mailmap"]),fn=new Set(["readme","license","licence","copying","notice","authors","contributors","changelog","changes","todo","makefile","dockerfile","containerfile","procfile","gemfile","rakefile","vagrantfile","jenkinsfile","brewfile","codeowners"]),Tt=typeof ae.constants.O_NOFOLLOW=="number"?ae.constants.O_NOFOLLOW:0,St=typeof ae.constants.O_NONBLOCK=="number"?ae.constants.O_NONBLOCK:0,ct=e=>`${e.size}-${e.mtimeNs}`,mn=e=>e!==""&&e!=="."&&e!==".."&&!e.includes(":")&&!e.endsWith(".")&&!e.endsWith(" "),ut=e=>b.isAcceptableDocumentPath(e)&&e===e.normalize("NFC")&&e.split("/").every(mn),xt=e=>{const t=e.toLowerCase(),r=t.lastIndexOf(".");return r<0?"":t.slice(r+1)},pn=e=>{const t=xt(e);if(ln.has(t))return{kind:"markdown"};const r=bt.get(t);if(r!==void 0)return r.kind==="image"?{kind:"image"}:{kind:"media",mediaType:r.mediaType};const n=e.toLowerCase();return dn.has(t)||!n.includes(".")&&fn.has(n)?{kind:"text"}:{kind:"file"}},Ie=e=>{switch(typeof e=="object"&&e!==null?e.code:void 0){case"ENOENT":case"ENOTDIR":return"not-found";case"ELOOP":case"EACCES":case"EPERM":return"forbidden";case"ENAMETOOLONG":return"invalid";case"EISDIR":return"unsupported";default:return null}},Ot=e=>{const t=Ie(e);return t===null?e:new he(t)},hn=e=>{const t=typeof e=="object"&&e!==null?e.code:void 0;return t==="EACCES"||t==="EPERM"||t==="ENOENT"||t==="ENOTDIR"},lt=async(e,t)=>{const r=[];for await(const n of e.createReadStream({start:0,end:t-1,autoClose:!1}))r.push(n);return Buffer.concat(r)},wn=(e,t)=>e!==null?{start:e.offset,end:e.offset+e.length-1}:t===0n?{}:{start:0,end:Number(t)-1},gn=async(e,t,r,n)=>{let a;try{a=await me.open(e,ae.constants.O_RDONLY|Tt|St);const E=await a.stat({bigint:!0});if(!E.isFile()||E.ino!==t.ino||E.dev!==t.dev||E.size!==t.size||E.mtimeNs!==t.mtimeNs)throw new he("not-found")}catch(E){throw await a?.close(),Ot(E)}const s=a.createReadStream(wn(r,t.size)),c=Mt.Readable.toWeb(s),f=()=>{s.destroy(n.reason)};return n.aborted?f():n.addEventListener("abort",f,{once:!0}),c},En=(e,t)=>{const r=se.NAME_COLLATOR.compare(e,t);return r!==0?r:e===t?0:e<t?-1:1},yn=e=>{let t=0;const r=[];return async n=>{t<e?t+=1:await new Promise(a=>r.push(a));try{return await n()}finally{const a=r.shift();a===void 0?t-=1:a()}}},bn=(e,t)=>{if(e.isSymbolicLink())return"symbolic-link";if(!(e.isDirectory()||e.isFile()))return"special-file";const{name:r}=e;return r!==r.normalize("NFC")?"not-nfc":r.includes(":")?"colon":r.endsWith(".")||r.endsWith(" ")?"trailing-dot-or-space":b.isAcceptableDocumentPath(r)?b.isAcceptableDocumentPath(t)?null:"path-too-long":"control-character-or-backslash"},Tn=new Set(["id","label","root","pathPrefix","parse","deny","maxEntries","maxDocumentBytes","textPreviewBytes","walkConcurrency","cacheScope","reportSkipped"]),be=(e,t,r)=>{if(t===void 0)return r;if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] ${e} must be a positive integer; got ${String(t)}`);return t},Sn=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] createFileSystemSource needs an options object");for(const h of Object.keys(e))if(!Tn.has(h))throw new TypeError(`[markdown-explorer] createFileSystemSource does not know the option ${JSON.stringify(h)}`);const{id:t,label:r,root:n,parse:a}=e;if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] a file-system source needs a non-empty id");if(typeof r!="string"||r.trim()==="")throw new TypeError("[markdown-explorer] a file-system source needs a non-blank label");if(typeof a!="function")throw new TypeError("[markdown-explorer] a file-system source needs a parse function");if(typeof n!="string"||!re.isAbsolute(n))throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);let s;try{s=ae.statSync(n).isDirectory()}catch(h){throw new RangeError(`[markdown-explorer] root does not exist: ${n}`,{cause:h})}if(!s)throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);const c=ae.realpathSync(n),f=e.pathPrefix;if(typeof f!="string")throw new TypeError('[markdown-explorer] pathPrefix is required: "" for a source over the whole root, or relative segments ending with "/"');if(f!==""&&!(f.endsWith("/")&&ut(f.slice(0,-1))))throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(f)}`);const E=b.resolvePathRules(e.deny),k=be("maxEntries",e.maxEntries,ye.maxEntries),p=be("maxDocumentBytes",e.maxDocumentBytes,ye.maxDocumentBytes),w=be("textPreviewBytes",e.textPreviewBytes,ye.textPreviewBytes),O=be("walkConcurrency",e.walkConcurrency,ye.walkConcurrency),A=e.cacheScope===void 0?"principal":e.cacheScope;if(A!=="principal"&&A!=="shared")throw new RangeError(`[markdown-explorer] cacheScope must be "principal" or "shared"; got ${JSON.stringify(A)}`);const v=e.reportSkipped;if(v!==void 0&&typeof v!="function")throw new TypeError("[markdown-explorer] reportSkipped must be a function");const _=v===void 0?h=>{console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(h.sourceId)} does not list ${JSON.stringify(h.path)}: ${h.reason}`)}:v,R=new Set,D=h=>{const x=re.resolve(c,...h.split("/")),T=re.relative(c,x);return T===""||T===".."||T.startsWith(`..${re.sep}`)||re.isAbsolute(T)?null:x},S=(h,x)=>{const T=`${x}\0${h}`;R.has(T)||R.size>=k||(R.add(T),_({sourceId:t,path:h,reason:x}))},P=async({signal:h})=>{h.throwIfAborted();const x=new AbortController,T=()=>{x.abort(h.reason)};h.addEventListener("abort",T,{once:!0});const N=yn(O);let L=0;const F=async(I,G)=>{const K=await N(async()=>{x.signal.throwIfAborted();try{return await me.readdir(I,{withFileTypes:!0})}catch(z){if(G===""||!hn(z))throw z;return null}});if(x.signal.throwIfAborted(),K===null)return S(`${f}${G}`,"unreadable-directory"),null;const X=[];for(const z of K){if(E.deniesName(z.name))continue;const V=G===""?z.name:`${G}/${z.name}`,Q=`${f}${V}`,q=bn(z,Q);if(q!==null){S(Q,q);continue}X.push({dirent:z,relativePath:V,path:Q})}if(L+=X.length,L>k)throw new he("too-large");return X.sort((z,V)=>En(z.dirent.name,V.dirent.name)),(await Promise.all(X.map(async({dirent:z,relativePath:V,path:Q})=>{if(!z.isDirectory())return{name:z.name,path:Q,type:"file"};const q=await F(re.join(I,z.name),V);return q===null?null:{name:z.name,path:Q,type:"directory",children:q}}))).filter(z=>z!==null)};try{const I=await F(c,"");if(I===null)throw new Error("[markdown-explorer] the source's root could not be listed");return I}catch(I){throw x.abort(),I}finally{h.removeEventListener("abort",T)}},B=async h=>{if(!h.startsWith(f))return{status:"refused",reason:"not-found"};const x=h.slice(f.length);if(!ut(x))return{status:"refused",reason:"invalid"};if(E.deniesPath(x))return{status:"refused",reason:"forbidden"};const T=D(x);if(T===null)return{status:"refused",reason:"forbidden"};const N=await me.lstat(T,{bigint:!0});if(N.isSymbolicLink())return{status:"refused",reason:"forbidden"};if(!N.isFile())return{status:"refused",reason:"unsupported"};const L=await me.realpath(T);return L!==T||E.deniesPath(re.relative(c,L).split(re.sep).join("/"))?{status:"refused",reason:"forbidden"}:{status:"file",target:T,name:x.slice(x.lastIndexOf("/")+1),stats:N}},j=async(h,x,T)=>{let N;try{const L=await B(T);if(L.status==="refused")return b.failureDocument(L.reason);const{target:F,name:I,stats:G}=L,K=pn(I),X=ct(G);if(K.kind==="image")return{kind:"image",name:I,version:X};if(K.kind==="media")return{kind:"media",name:I,mediaType:K.mediaType,version:X};if(K.kind==="file")return{kind:"file",name:I,version:X};N=await me.open(F,ae.constants.O_RDONLY|Tt|St);const te=await N.stat({bigint:!0});if(!te.isFile()||te.ino!==G.ino||te.dev!==G.dev)return b.failureDocument("forbidden");if(K.kind==="markdown"){if(te.size>BigInt(p))return b.failureDocument("too-large");const q=await lt(N,p+1);if(q.length>p)return b.failureDocument("too-large");const we=await a(new TextDecoder("utf-8").decode(q),x);return{kind:"markdown",name:I,htmlContent:we.htmlContent,headings:we.headings}}const z=await lt(N,w);if(z.includes(0))return{kind:"file",name:I,version:X};const V=te.size>BigInt(w),Q=new TextDecoder("utf-8").decode(z,{stream:V});return{kind:"text",name:I,text:Q,truncated:V,version:X}}catch(L){const F=Ie(L);if(F===null)throw L;return b.failureDocument(F)}finally{await N?.close()}},d=async(h,x,T)=>{let N;try{N=await B(T)}catch(X){throw Ot(X)}if(N.status==="refused")throw new he(N.reason);const{target:L,name:F,stats:I}=N,G=bt.get(xt(F)),K=G===void 0?"":G.contentType;return{name:F,contentType:K,size:Number(I.size),version:ct(I),open:X=>gn(L,I,X,h.signal)}},y=async(h,x,T)=>{let N;try{N=await B(T)}catch(I){if(Ie(I)!==null)return null;throw I}if(N.status==="refused")return null;const L=T.slice(f.length).split("/");if(L.some(I=>E.deniesName(I)))return null;const F=L.slice(0,-1);return F.map((I,G)=>`${f}${F.slice(0,G+1).join("/")}`)};return Object.freeze({id:t,label:r,cacheScope:A,boundary:Object.freeze({contains:h=>h.startsWith(f)}),tree:P,ancestors:y,document:j,asset:d})};exports.DEFAULT_DENIED_PATH_SEGMENTS=b.DEFAULT_DENIED_PATH_SEGMENTS;exports.MAX_DOCUMENT_PATH_LENGTH=b.MAX_DOCUMENT_PATH_LENGTH;exports.isAcceptableDocumentPath=b.isAcceptableDocumentPath;exports.isDeniedPath=b.isDeniedPath;exports.ExplorerError=he;exports.anonymousAccess=vt;exports.createFileSystemSource=Sn;exports.createMarkdownExplorer=un;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("./dataRoute-CcZ8PK00.cjs"),ht=require("node:crypto"),Ut=require("@aiquants/markdown/server"),Se=require("@aiquants/request-isolation"),Oe=require("react-router"),se=require("./location-DmzVAFvo.cjs"),ie=require("node:fs"),oe=require("node:path"),xe=require("node:url"),Xt=require("node:worker_threads"),we=require("node:fs/promises"),Gt=require("node:stream");var Re=typeof document<"u"?document.currentScript:null;const Fe=Object.freeze({kind:"anonymous"}),Jt=Object.freeze({authenticate:async()=>({status:"signed-in",principal:Fe}),principalKey:()=>Fe.kind,signedOutPage:(e,t)=>new Response(null,{status:401,headers:t})}),Yt="application/octet-stream",wt="application/pdf",Wt=new Set(["image/png","image/apng","image/jpeg","image/gif","image/webp","image/avif","image/bmp","image/x-icon","image/vnd.microsoft.icon","audio/mpeg","audio/mp4","audio/aac","audio/ogg","audio/opus","audio/wav","audio/wave","audio/x-wav","audio/webm","audio/flac","audio/x-flac","audio/x-m4a","video/mp4","video/webm","video/ogg","video/quicktime",wt]),gt="default-src 'none'; media-src 'self'; style-src 'unsafe-inline'",Kt=`${gt}; sandbox`,Vt=`${gt}; sandbox allow-same-origin`,Ue=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,Qt=/^[\t\n\r ]+|[\t\n\r ]+$/gu,Me=/^[\t ]+|[\t ]+$/gu,Zt=e=>{const t=[];let r="",n=0;for(;;){for(;n<e.length&&e[n]!=='"'&&e[n]!==",";)r+=e[n],n+=1;if(n<e.length&&e[n]==='"'){const a=n;for(n+=1;n<e.length&&e[n]!=='"';)n+=e[n]==="\\"?2:1;if(n=Math.min(n+1,e.length),r+=e.slice(a,n),n<e.length)continue}if(t.push(r.replace(Me,"")),r="",n>=e.length)return t;n+=1}},qt=e=>{const t=e.replace(Qt,""),r=t.indexOf("/");if(r<0)return null;const n=t.slice(0,r),a=t.indexOf(";",r+1),s=t.slice(r+1,a<0?t.length:a).replace(/[\t\n\r ]+$/u,"");return Ue.test(n)&&Ue.test(s)?`${n}/${s}`.toLowerCase():null},er=e=>{let t=null;for(const r of Zt(e)){const n=qt(r);n!==null&&n!=="*/*"&&(t=n)}return t},tr=/['()*]/gu,rr=e=>encodeURIComponent(e).replace(tr,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),nr=Object.freeze({"Cache-Control":"private, max-age=60, stale-while-revalidate=600, no-transform",Vary:"Cookie"}),or=(e,t)=>{const r=er(e),n=r!==null&&Wt.has(r),a=n&&(r.startsWith("audio/")||r.startsWith("video/"));return{contentType:r===null?Yt:r,inline:n,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`${n?"inline":"attachment"}; filename*=UTF-8''${rr(t)}`,...r===wt?{}:{"Content-Security-Policy":a?Vt:Kt},"Cross-Origin-Resource-Policy":"same-origin"}}},sr=/^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu,ye=Object.freeze({kind:"whole"}),Xe=Object.freeze({kind:"unsatisfiable"}),ir=(e,t,r)=>{const n=e.get("Range");if(n===null)return ye;const a=e.get("If-Range");if(a!==null&&a!==r)return ye;const s=sr.exec(n);if(s===null)return ye;const[,u,m,g]=s;if(g!==void 0){const y=Number(g);if(y===0)return Xe;const T=Math.max(0,t-y);return{kind:"partial",range:{offset:T,length:t-T}}}const O=Number(u),h=m===""?Number.POSITIVE_INFINITY:Number(m);return h<O?ye:O>=t?Xe:{kind:"partial",range:{offset:O,length:Math.min(h,t-1)-O+1}}},Ge="W/",ar=e=>{const t=[];let r=0,n=!1;for(let a=0;a<e.length;a+=1)e[a]==='"'?n=!n:e[a]===","&&!n&&(t.push(e.slice(r,a).replace(Me,"")),r=a+1);return t.push(e.slice(r).replace(Me,"")),t},Je=e=>e.startsWith(Ge)?e.slice(Ge.length):e,cr=(e,t)=>{if(e===null)return!1;const r=ar(e);if(r.length===1&&r[0]==="*")return!0;const n=Je(t);return r.some(a=>Je(a)===n)},ur=(e,t)=>{let r=t;return e.pipeThrough(new TransformStream({transform:(n,a)=>{const s=n.byteLength>r?n.subarray(0,r):n;r-=s.byteLength,a.enqueue(s),r===0&&a.terminate()},flush:n=>{r>0&&n.error(new RangeError("[markdown-explorer] the asset ended before its declared length"))}}))},_e=async(e,t,r,n,a)=>{if(n!==null&&r.set("Content-Length",String(n)),e.method.toUpperCase()==="HEAD")return new Response(null,{status:t,headers:r});const s=await a();return new Response(n===null?s:ur(s,n),{status:t,headers:r})},lr=(e,t)=>{const r=new Headers(e);for(const[n,a]of Object.entries({"Accept-Ranges":"bytes","Content-Range":`bytes */${t}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff"}))r.set(n,a);return new Response(null,{status:416,headers:r})},dr=async(e,t,r)=>{const n=`"${t.version}"`,a=or(t.contentType,t.name),s=new Headers(r);for(const[g,O]of Object.entries({...a.headers,...nr,ETag:n}))s.set(g,O);if(cr(e.headers.get("If-None-Match"),n))return new Response(null,{status:304,headers:s});if(s.set("Content-Type",a.contentType),t.size===null)return _e(e,200,s,null,()=>t.open(null));if(t.size===0)return s.set("Content-Length","0"),new Response(null,{status:200,headers:s});s.set("Accept-Ranges","bytes");const u=ir(e.headers,t.size,n);if(u.kind==="unsatisfiable")return lr(r,t.size);if(u.kind==="whole")return _e(e,200,s,t.size,()=>t.open(null));const{range:m}=u;return s.set("Content-Range",`bytes ${m.offset}-${m.offset+m.length-1}/${t.size}`),_e(e,206,s,m.length,()=>t.open(m))},Ae=(e,t)=>{const r=new AbortController,n=t(AbortSignal.any([e.signal,r.signal]));return new Promise(a=>{let s;const u=setTimeout(()=>{a(e.late),s=setTimeout(()=>r.abort(),e.handOverMs)},e.timeoutMs),m=()=>{clearTimeout(u),clearTimeout(s)};n.then(g=>{m(),a(g)},()=>{m(),a(e.late)})})},fr=Object.freeze({error:(e,t)=>{console.error(e,t)}}),yt=Symbol.for("@aiquants/markdown-explorer:ExplorerError");class ge extends Error{reason;code;constructor(t,r={}){if(!w.isExplorerFailureReason(t))throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${JSON.stringify(t)}`);if(r.code!==void 0&&!w.isExplorerFailureCode(r.code))throw new RangeError(`[markdown-explorer] an ExplorerError code must be 1 to 64 lowercase letters, digits or hyphens; got ${JSON.stringify(r.code)}`);super(`[markdown-explorer] ${t}`,r.cause===void 0?void 0:{cause:r.cause}),this.name="ExplorerError",this.reason=t,this.code=r.code,Object.defineProperty(this,yt,{value:!0})}}const mr=e=>e instanceof Error&&Object.hasOwn(e,yt)&&w.isExplorerFailureReason(e.reason),pr=e=>typeof e=="object"&&e!==null&&e.name==="AbortError",De=(e,t,r)=>{try{e.error(t,r)}catch(n){console.error("[markdown-explorer] the logger threw while reporting a failure",{operation:r.operation,error:n})}},ne=(e,t)=>De(e,`[markdown-explorer] ${t.operation} failed`,t),hr=(e,t)=>De(e,`[markdown-explorer] ${t.operation} left out an entry`,t),ve=(e,t)=>De(e,`[markdown-explorer] ${t.operation} refused a path the deny rules match`,{...t,error:new RangeError("[markdown-explorer] the path matches a deny rule")}),Ye=(e,t)=>{e===null||typeof e!="object"&&typeof e!="function"||Promise.resolve(e).then(void 0,t)},Y=(e,t,r,n)=>mr(e)?w.failureOf(e.reason,e.code):(pr(e)||r.aborted||ne(n,{...t,error:e}),{reason:"failed"}),We=2*1024*1024,Ke=256*1024*1024,wr=async(e,t)=>{const r=e.getReader(),n=new Uint8Array(t);let a=0;for(;a<t;){const{done:s,value:u}=await r.read();if(s)return n.subarray(0,a);const m=u.subarray(0,t-a);n.set(m,a),a+=m.byteLength}return r.cancel().catch(()=>{}),n},gr=async(e,t)=>{if(e.size===0)return{text:"",truncated:!1};const r=e.size!==null&&e.size>t,n=e.size===null?t+1:Math.min(e.size,t),a=await wr(await e.open(r?{offset:0,length:t}:null),n);if(e.size!==null&&a.byteLength<n)throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");const s=r||a.byteLength>t,u=s?a.subarray(0,t):a;return u.includes(0)?null:{text:new TextDecoder("utf-8").decode(u,{stream:s}),truncated:s}},Ve=(e,t)=>{if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] a cache ${e} must be a positive integer; got ${String(t)}`)},Et=(e,t)=>{Ve("capacity",e),t!==void 0&&Ve("weight budget",t.max);const r=new Map;let n=0;const a=s=>{const u=r.get(s);u!==void 0&&(r.delete(s),n-=u.weight)};return{get:s=>{const u=r.get(s);if(u!==void 0)return r.delete(s),r.set(s,u),u.value},set:(s,u)=>{a(s);const m=t===void 0?0:t.of(s,u);if(!(t!==void 0&&m>t.max)){r.set(s,{value:u,weight:m}),n+=m;for(const g of r.keys()){if(r.size<=e&&(t===void 0||n<=t.max))break;a(g)}}},delete:a,size:()=>r.size,weight:()=>n}},bt=e=>Math.max(1,e-1),yr=2147483647,Qe=Object.freeze({status:"aborted"}),ue=(e,t,r)=>{const n=(e.get(t)??0)+r;n===0?e.delete(t):e.set(t,n)},de=(e,t,r)=>{if(!Number.isSafeInteger(t)||t<=0||t>r)throw new RangeError(`[markdown-explorer] a worker pool's ${e} must be an integer in 1..${String(r)}; got ${String(t)}`)},Er=e=>e!==null&&typeof e=="object"&&e.ready===!0&&!("id"in e),br=(e,t)=>e!==null&&typeof e=="object"&&e.id===t&&"output"in e,Tr=({url:e,size:t,deadlineMs:r,jobsPerScope:n,maxQueuedJobs:a,heapLimits:s})=>{de("size",t,Number.MAX_SAFE_INTEGER),de("deadline",r,yr),de("jobsPerScope",n,Number.MAX_SAFE_INTEGER),de("maxQueuedJobs",a,Number.MAX_SAFE_INTEGER),de("maxOldGenerationSizeMb",s.maxOldGenerationSizeMb,Number.MAX_SAFE_INTEGER),de("maxYoungGenerationSizeMb",s.maxYoungGenerationSizeMb,Number.MAX_SAFE_INTEGER);const u=Object.freeze({maxOldGenerationSizeMb:s.maxOldGenerationSizeMb,maxYoungGenerationSizeMb:s.maxYoungGenerationSizeMb}),m=new Set,g=[],O=new Map,h=new Map,y=bt(t);let T=0;const A=(p,E)=>{const{job:b}=p;p.timer!==null&&clearTimeout(p.timer),p.timer=null,p.job=null,p.sent=!1,b!==null&&(ue(O,b.scope,-1),ue(h,b.scope,-1),b.settle(E))},D=p=>{const[E]=g.splice(p,1);E?.detach()},N=()=>{let p=-1,E=y,b=Number.POSITIVE_INFINITY;for(const[_,S]of g.entries()){const P=O.get(S.scope)??0,L=h.get(S.scope)??0;(P<E||P===E&&p>=0&&L<b)&&(p=_,E=P,b=L)}return p},v=(p,E)=>{m.has(p)&&(m.delete(p),A(p,E),p.worker.terminate().catch(()=>{}),F())},z=p=>{p.timer=setTimeout(()=>{v(p,{status:"timeout"})},r)},R=(p,E)=>p.sent?{status:"crashed",error:E}:{status:"unavailable",error:E},M=(p,E)=>{p.sent=!0,z(p);try{p.worker.postMessage({id:E.id,input:E.input})}catch(b){A(p,{status:"crashed",error:b}),p.worker.unref()}},B=()=>{const p={worker:new Xt.Worker(e,{resourceLimits:u}),job:null,sent:!1,timer:null,ready:!1};return p.worker.unref(),p.timer=setTimeout(()=>{v(p,{status:"unavailable",error:new Error(`[markdown-explorer] a worker did not start within ${String(r)} ms`)})},r),p.worker.on("message",E=>{if(!p.ready&&Er(E)){p.ready=!0,p.timer!==null&&clearTimeout(p.timer),p.timer=null,p.job===null?p.worker.unref():M(p,p.job),p.job===null&&F();return}const{job:b}=p;if(b===null||!br(E,b.id)){v(p,R(p,new Error("[markdown-explorer] a worker sent a message that answers no job")));return}A(p,{status:"done",output:E.output}),p.worker.unref(),F()}),p.worker.on("error",E=>{v(p,R(p,E))}),p.worker.on("messageerror",E=>{v(p,R(p,E))}),p.worker.on("exit",E=>{v(p,R(p,new Error(`[markdown-explorer] a worker exited with code ${String(E)}`)))}),m.add(p),p},F=()=>{for(;;){const p=N(),E=g[p];if(E===void 0)return;let b;for(const S of m)if(S.job===null){b=S;break}if(b===void 0&&m.size<t)try{b=B()}catch(S){D(p),ue(h,E.scope,-1),E.settle({status:"unavailable",error:S});continue}if(b===void 0)return;D(p),ue(O,E.scope,1);const _=b;_.job=E,_.worker.ref(),_.ready&&M(_,E)}};return{run:(p,{scope:E,signal:b})=>new Promise(_=>{if(b.aborted){_(Qe);return}if((h.get(E)??0)>=n){_({status:"refused",limit:"scope"});return}T+=1;const S={id:T,input:p,scope:E,settle:_,detach:()=>{}};g.push(S),ue(h,E,1),F();const P=g.indexOf(S);if(P<0)return;if(g.length>a){D(P),ue(h,E,-1),_({status:"refused",limit:"queue"});return}const L=()=>{const X=g.indexOf(S);X<0||(D(X),ue(h,E,-1),_(Qe))};b.addEventListener("abort",L,{once:!0}),S.detach=()=>{b.removeEventListener("abort",L)}}),workers:()=>m.size}},$e=1024*1024,Sr=3e4,kr=4*$e,Or=64*$e,xr=3,Rr=2,_r=(e,t)=>e+bt(t)+xr,Ar=4,vr=32,Nr=512,Pr=64,Ir=4096,Mr=32,Ze=4096,Lr=4,Tt=({workerHeapMb:e,maxHtmlBytes:t})=>Math.floor(((e-Pr)*$e-t*Mr)/Ir),Dr=({maxHtmlBytes:e})=>e,$r=({maxHtmlBytes:e})=>Lr*e,jr=1024,zr=2147483647,Cr=64,Hr=2**29,Br=1024*1024,Fr=64,qe=Object.freeze({status:"rejected",reason:"too-large",cause:null}),Ne=Object.freeze({status:"rejected",reason:"failed",cause:null}),le=(e,t,r,n)=>{if(t===void 0)return r;if(typeof t!="number")throw new TypeError(`[markdown-explorer] sanitizer.${e} must be a number; got ${typeof t}`);if(!Number.isSafeInteger(t)||t<=0||t>n)throw new RangeError(`[markdown-explorer] sanitizer.${e} must be an integer in 1..${String(n)}; got ${String(t)}`);return t},Ur=(e,t)=>{if(e!==void 0&&(e===null||typeof e!="object"))throw new TypeError("[markdown-explorer] sanitizer must be an object of { workers, deadlineMs, maxHtmlBytes, cacheBytes, workerHeapMb, jobsPerScope, maxQueuedJobs }");const{workers:r,deadlineMs:n,maxHtmlBytes:a,cacheBytes:s,workerHeapMb:u,jobsPerScope:m,maxQueuedJobs:g}=e??{},O=le("workers",r,Rr,Cr),h=le("jobsPerScope",m,_r(t,O),Number.MAX_SAFE_INTEGER),y=Object.freeze({workers:O,deadlineMs:le("deadlineMs",n,Sr,zr),maxHtmlBytes:le("maxHtmlBytes",a,kr,Hr),cacheBytes:le("cacheBytes",s,Or,Number.MAX_SAFE_INTEGER),workerHeapMb:le("workerHeapMb",u,Nr,Br),jobsPerScope:h,maxQueuedJobs:le("maxQueuedJobs",g,Ar*h,Number.MAX_SAFE_INTEGER)});if(y.jobsPerScope<t)throw new RangeError(`[markdown-explorer] sanitizer.jobsPerScope must be at least multiView.maxPanels (${String(t)}), because a page sends the document of every panel to the sanitizer at once for one reader; got ${String(y.jobsPerScope)}`);if(y.maxQueuedJobs<t)throw new RangeError(`[markdown-explorer] sanitizer.maxQueuedJobs must be at least multiView.maxPanels (${String(t)}), because a reader whose page finds every worker busy waits with the document of every panel; got ${String(y.maxQueuedJobs)}`);if(Tt(y)<Ze)throw new RangeError(`[markdown-explorer] sanitizer.workerHeapMb (${String(y.workerHeapMb)} MiB) must leave room for ${String(Ze)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(y.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`);return y},Xr=()=>{const e=typeof document>"u"?require("url").pathToFileURL(__filename).href:Re&&Re.tagName.toUpperCase()==="SCRIPT"&&Re.src||new URL("server.cjs",document.baseURI).href,t=new URL(`./sanitizeWorker${oe.extname(xe.fileURLToPath(e))}`,e);if(!ie.existsSync(xe.fileURLToPath(t)))throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${xe.fileURLToPath(t)}`);return t},et=new Map,Gr=(e,t)=>{const r=[e.href,t.workers,t.deadlineMs,t.workerHeapMb,t.jobsPerScope,t.maxQueuedJobs].map(String).join("\0");let n=et.get(r);return n===void 0&&(n=Tr({url:e,size:t.workers,deadlineMs:t.deadlineMs,jobsPerScope:t.jobsPerScope,maxQueuedJobs:t.maxQueuedJobs,heapLimits:{maxOldGenerationSizeMb:t.workerHeapMb,maxYoungGenerationSizeMb:vr}}),et.set(r,n)),n},Jr=e=>{if(e===null||typeof e!="object")return!1;const{status:t,html:r,message:n}=e;return t==="sanitized"&&typeof r=="string"||t==="too-large"||t==="error"&&typeof n=="string"},Yr=e=>e instanceof Error&&e.code==="ERR_WORKER_OUT_OF_MEMORY",Wr=({iframeHosts:e,dataPath:t,options:r,pool:n})=>{const a=Object.freeze([...e]),s=Tt(r),u=Dr(r),m=$r(r),g=Et(jr,{max:r.cacheBytes,of:(N,v)=>2*N.length+(v.status==="sanitized"?2*v.html.length:Fr)}),O=new Map,h=new Map,y=N=>{O.get(N.key)===N&&O.delete(N.key);const v=h.get(N.hash);v?.delete(N),v?.size===0&&h.delete(N.hash)},T=async(N,v,z)=>{const R=await n.run({html:N,iframeHosts:a,dataPath:t,maxNodes:s,maxAttributeChars:u,maxSanitizedChars:m},{scope:v,signal:z});if(R.status==="refused"){const B=R.limit==="scope"?`its reader already has ${String(r.jobsPerScope)} documents being sanitized or waiting`:`${String(r.maxQueuedJobs)} documents are already waiting`;return{outcome:{status:"rejected",reason:"failed",cause:new Error(`[markdown-explorer] the HTML sanitizer refused a document: ${B}`)},lasting:!1}}if(R.status==="aborted")return{outcome:Ne,lasting:!1};if(R.status==="timeout")return{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer did not finish within ${String(r.deadlineMs)} ms`)},lasting:!0};if(R.status==="unavailable")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker could not start",{cause:R.error})},lasting:!1};if(R.status==="crashed"&&Yr(R.error))return{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer ran out of its ${String(r.workerHeapMb)} MiB worker heap`,{cause:R.error})},lasting:!0};if(R.status==="crashed")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker failed",{cause:R.error})},lasting:!0};const{output:M}=R;return Jr(M)?M.status==="too-large"?{outcome:qe,lasting:!0}:M.status==="error"?{outcome:{status:"rejected",reason:"failed",cause:new Error(`[markdown-explorer] the HTML sanitizer failed: ${M.message}`)},lasting:!0}:M.html.length>m?{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer's output of ${String(M.html.length)} characters exceeds its limit of ${String(m)}`)},lasting:!0}:{outcome:{status:"sanitized",html:M.html},lasting:!0}:{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker answered something that is not an outcome")},lasting:!0}},A=(N,v,z,R)=>{let M=()=>{};const B=new Promise(E=>{M=E}),F={hash:v,key:z,outcome:B,answer:M,controller:new AbortController,waiters:0};O.set(z,F);const p=h.get(v);return p===void 0?h.set(v,new Set([F])):p.add(F),T(N,R,F.controller.signal).catch(E=>({outcome:{status:"rejected",reason:"failed",cause:E instanceof Error?E:new Error(String(E))},lasting:!0})).then(({outcome:E,lasting:b})=>{if(y(F),F.answer(E),!b)return;const _=g.get(v),S=_??(E.status==="rejected"?{...E,cause:null}:E);_===void 0&&g.set(v,S);for(const P of h.get(v)??[])y(P),P.answer(S),P.controller.abort()}),F},D=(N,v)=>new Promise(z=>{N.waiters+=1;const R=()=>{N.waiters-=1,z(Ne),!(N.waiters>0)&&(y(N),N.controller.abort())};v.addEventListener("abort",R,{once:!0}),N.outcome.then(M=>{v.removeEventListener("abort",R),z(M)})});return(N,{scope:v,signal:z})=>{if(N.length>r.maxHtmlBytes||Buffer.byteLength(N,"utf8")>r.maxHtmlBytes)return Promise.resolve(qe);const R=ht.createHash("sha256").update(N,"utf8").digest("base64"),M=g.get(R);if(M!==void 0)return Promise.resolve(M);if(z.aborted)return Promise.resolve(Ne);const B=`${R}\0${v}`,F=O.get(B);return D(F===void 0?A(N,R,B,v):F,z)}},ke=e=>({result:e,json:JSON.stringify(e)}),Pe=Object.freeze(ke(Object.freeze({status:"error",failure:Object.freeze({reason:"failed"})}))),Kr=e=>e.status==="ok"&&e.entries.length>0,Vr=({ttlMs:e,maxEntries:t,maxBytes:r,now:n})=>{const a=Et(t,{max:r,of:(h,y)=>2*y.tree.json.length}),s=new Map,u=new Map,m=(h,y)=>{const T=new AbortController,A={waiters:0,superseded:!1,started:!1,loadTree:y},D=u.get(h),N=(B,F)=>{const p=ke(B);return!(A.superseded||T.signal.aborted)&&Kr(B)&&a.set(h,{tree:p,loadedAt:F}),p},z=(async()=>{if(D!==void 0&&await D,T.signal.aborted)return Pe;const B=n();return A.started=!0,N(await A.loadTree(T.signal,B),B)})().finally(()=>{s.get(h)===R&&s.delete(h)}),R={promise:z,controller:T,state:A};s.set(h,R);const M=z.then(()=>{},()=>{});return u.set(h,M),M.then(()=>{u.get(h)===M&&u.delete(h)}),R},g=(h,y,T)=>{y.state.waiters+=1;const A=()=>{y.state.waiters-=1,!(y.state.waiters>0)&&(s.get(h)===y&&s.delete(h),y.controller.abort())};return T.addEventListener("abort",A,{once:!0}),y.promise.finally(()=>{T.removeEventListener("abort",A)})},O=h=>{a.delete(h);const y=s.get(h);y?.state.started&&(y.state.superseded=!0,s.delete(h))};return{load:(h,y,T)=>{if(y.aborted)return Promise.resolve(Pe);const A=a.get(h);if(A!==void 0){if(n()-A.loadedAt<e)return Promise.resolve(A.tree);a.delete(h)}const D=s.get(h);return g(h,D===void 0?m(h,T):D,y)},refresh:(h,y,T)=>{if(y.aborted)return Promise.resolve(Pe);O(h);const A=s.get(h);return A===void 0?g(h,m(h,T),y):(A.state.loadTree=T,g(h,A,y))},forget:O}},Qr=e=>({load:(t,r,n)=>n(r,e()).then(ke),refresh:(t,r,n)=>n(r,e()).then(ke),forget:()=>{}}),x=e=>{throw new TypeError(`[markdown-explorer] ${e}`)},Zr=e=>{if(e===null||typeof e!="object")return null;const{name:t,path:r}=e;return typeof t!="string"||typeof r!="string"?null:t===""?{path:r,reason:"an empty name"}:w.isAcceptableDocumentPath(r)?null:{path:r,reason:"a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)"}},qr=(e,t,r,n)=>{if(e===null)return null;if(!Array.isArray(e))throw new TypeError(`[markdown-explorer] a source's ancestors must be null or an array of folder paths; got ${typeof e}`);const a=new Set;for(const s of e){if(typeof s!="string"||!w.isAcceptableDocumentPath(s))throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");if(r.deniesPath(s))throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");if(!n(s))throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");if(s===t)throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");if(a.has(s))throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");a.add(s)}return Object.freeze([...a])},en=(e,t,r,n,a)=>{const s=new Set,u=g=>{if(!Array.isArray(g))return x("a source returned entries that are not an array");const O=[];for(const h of g){const y=m(h);y!==null&&O.push(y)}return O},m=g=>{const O=Zr(g);if(O!==null)return n(O),null;const h=w.entryViolation(g);if(h!==null)return x(h);const y=g;if(s.has(y))return x("a source returned entries that contain themselves");const{name:T,path:A,type:D,mimeType:N,children:v,lazy:z}=y;if(t.deniesName(T)||t.deniesPath(A))return null;if(!a(A))return n({path:A,reason:"a path outside the source's boundary"}),null;const R=N===void 0?{name:T,path:A}:{name:T,path:A,mimeType:N};if(D==="file")return{...R,type:D};if(z===!0)return r?{...R,type:D,lazy:!0,children:[]}:x("a lazy directory came from a source without a children function");if(v===void 0)return{...R,type:D};s.add(y);const M=u(v);return s.delete(y),{...R,type:D,children:M}};return u(e)},tn=/^[\x21\x23-\x7E]{1,256}$/u,St=e=>typeof e=="string"&&tn.test(e),rn=new Set(["text","image","media","file"]),nn=e=>typeof e=="string"&&rn.has(e),on=(e,t,r)=>{if(e!==null&&typeof e=="object"){const s=e,{kind:u}=s;if(nn(u)){if(Object.hasOwn(s,"url"))return x(`a ${u} document carries its version, not a url`);if(typeof s.name!="string")return x("a document needs a name string");if(!St(s.version))return x(`a ${u} document needs a version of 1 to 256 visible ASCII characters other than '"'`);const m=t(s.version);switch(u){case"image":case"file":return{kind:u,name:s.name,url:m};case"media":{const{mediaType:g}=s;return w.isExplorerMediaType(g)?{kind:u,name:s.name,url:m,mediaType:g}:x(`unknown media type ${typeof g=="string"?JSON.stringify(g.slice(0,64)):typeof g}`)}case"text":return typeof s.text!="string"||typeof s.truncated!="boolean"?x("a text document needs text and truncated"):{kind:u,name:s.name,text:s.text,truncated:s.truncated,url:m}}}}const n=w.documentViolation(e);if(n!==null)return x(n);const a=e;switch(a.kind){case"failure":{const{reason:s,code:u}=a.failure;return{kind:"failure",failure:w.failureOf(s,u)}}case"markdown":return a.headings.length>w.EXPLORER_MAX_HEADINGS?{kind:"failure",failure:w.failureOf("too-large")}:a.edit?.kind==="inline"&&!r?x("a markdown document offers inline editing, but the server has no edit ports"):{kind:"unsanitized-markdown",name:a.name,html:a.htmlContent,headings:a.headings.map(({text:s,depth:u,id:m})=>({text:s,depth:u,id:m})),edit:sn(a.edit)}}},sn=e=>e===null?null:e.kind==="inline"?{kind:"inline"}:{kind:"external",href:e.href},je=(e,t,r)=>typeof e!="string"?x(`${r} needs a text string`):e.includes("\0")?x(`${r} holds NUL, which no text editor can keep`):new TextEncoder().encode(e).byteLength>t?x(`${r} is over editMaxBytes (${t} bytes); refuse a longer source with ExplorerError "too-large"`):e,kt=e=>w.isRootRelativeUrl(e.href)?{kind:"grant",href:e.href}:x("a grant needs a root-relative href"),an=(e,t)=>{if(e===null||typeof e!="object")return x("an edit source must be an object");const r=e;return r.kind==="grant"?kt(r):r.kind!=="edit"?x(`an edit source's kind must be "edit" or "grant"`):w.isExplorerEditToken(r.version)?typeof r.history!="boolean"?x("an edit source needs history"):{kind:"edit",text:je(r.text,t,"an edit source"),version:r.version,history:r.history}:x("an edit source needs a version of 1 to 1024 characters")},cn=(e,t)=>{if(e===null||typeof e!="object")return x("a save result must be an object");const r=e;switch(r.kind){case"grant":return kt(r);case"saved":return w.isExplorerEditToken(r.version)?{kind:"saved",version:r.version}:x("a saved result needs a version of 1 to 1024 characters");case"conflict":return w.isExplorerEditToken(r.version)?{kind:"conflict",version:r.version,text:je(r.text,t,"a conflict's current text")}:x("a conflict needs the current version of 1 to 1024 characters");default:return x(`a save result's kind must be "saved", "conflict" or "grant"`)}},un=e=>{if(e===null||typeof e!="object")return x("a preview must be an object");const{htmlContent:t,headings:r}=e;if(typeof t!="string"||!Array.isArray(r))return x("a preview needs htmlContent and headings");if(r.length>w.EXPLORER_MAX_HEADINGS)return{kind:"failure",failure:w.failureOf("too-large")};for(const n of r){const a=w.headingViolation(n);if(a!==null)return x(a)}return{html:t,headings:r.map(({text:n,depth:a,id:s})=>({text:n,depth:a,id:s}))}},ln=e=>{if(!Array.isArray(e))return x("revisions must be an array");const t=new Set;return e.map(r=>{const n=w.revisionViolation(r);if(n!==null)return x(n);const{id:a,modifiedAt:s,size:u,author:m,kept:g,current:O}=r;return t.has(a)?x(`two revisions share the id ${JSON.stringify(a.slice(0,64))}`):(t.add(a),{id:a,modifiedAt:s,size:u,author:m,kept:g,current:O})})},dn=(e,t)=>je(e,t,"a revision"),tt=e=>{if(e===null||typeof e!="object")return x("an asset file must be an object");const{name:t,contentType:r,size:n,version:a,open:s}=e;return typeof t!="string"||t===""?x("an asset file needs a non-empty name"):typeof r!="string"?x("an asset file needs a contentType string ('' when unknown)"):n!==null&&!(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)?x("an asset file's size must be null or a non-negative safe integer"):St(a)?typeof s!="function"?x("an asset file needs an open function"):Object.freeze({name:t,contentType:r,size:n,version:a,open:s}):x(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`)},fn=e=>Array.isArray(e)?e.map(t=>{if(t===null||typeof t!="object")return x("a notice must be an object");const{id:r,tone:n,title:a,body:s,action:u}=t;if(typeof r!="string"||r===""||typeof a!="string")return x("a notice needs an id and a title");if(!w.isExplorerNoticeTone(n))return x(`unknown notice tone ${typeof n=="string"?JSON.stringify(n.slice(0,64)):typeof n}`);if(s!==void 0&&typeof s!="string")return x("a notice body must be a string");const g={id:r,tone:n,title:a,...s===void 0?{}:{body:s}};if(u===void 0)return g;if(u===null||typeof u!="object")return x("a notice action must be an object");const{label:O,href:h}=u;return typeof O!="string"||!w.isAcceptableUrl(h,w.EXPLORER_LINK_PROTOCOLS)?x("a notice action needs a label and an http(s), mailto or relative href"):{...g,action:{label:O,href:h}}}):x("notices must be an array"),mn=4e3,Ee=Object.freeze({ttlMs:3e5,maxEntries:64,maxBytes:64*1024*1024}),rt=32,Ot="private, no-store",pn=Object.freeze({"Content-Type":"application/json; charset=utf-8","Cache-Control":Ot,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; frame-ancestors 'none'; sandbox","Cross-Origin-Resource-Policy":"same-origin"}),hn=22,wn=2147483647,Ie=Object.freeze([]),gn=Object.freeze({status:"ok",source:null,ancestors:null}),nt=Object.freeze(["contains","confirm"]),ot=Object.freeze({readOnly:!1}),yn=Object.freeze({readOnly:!0}),V=(e,t,r)=>{if(!(r&&t===void 0)&&typeof t!="function")throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${typeof t}`)},fe=(e,t,r)=>{if(typeof t!="number")throw new TypeError(`[markdown-explorer] ${e} must be a number; got ${typeof t}`);if(!Number.isSafeInteger(t)||t<=0||t>r)throw new RangeError(`[markdown-explorer] ${e} must be an integer in 1..${String(r)}; got ${String(t)}`);return t},En=e=>{if(e===null||typeof e!="object"||!Object.isFrozen(e))throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");return se.revalidateExplorerConfig(e)},st=e=>{try{return new Headers(e)}catch{throw new TypeError("[markdown-explorer] authenticate returned headers that are not a valid headers init (their values are not logged)")}},it=e=>e instanceof Response?new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`):e,bn=e=>{if(typeof e!="string")throw new TypeError(`[markdown-explorer] scopeSecret must be a string; got ${typeof e}`);if(e.length<rt)throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(rt)} characters; got ${String(e.length)}`);return e},Tn=(e,t)=>{if(!se.isPlainObject(t))throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);for(const r of Object.keys(t))if(!nt.includes(r))throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${nt.join(", ")}`);V(`${e}.boundary.contains`,t.contains,!1),V(`${e}.boundary.confirm`,t.confirm,!0)},Sn=e=>{if(!Array.isArray(e))throw new TypeError("[markdown-explorer] sources must be an array");const t=e;if(t.length===0)throw new RangeError("[markdown-explorer] sources must hold at least one source");const r=new Set;for(const[n,a]of t.entries()){if(a===null||typeof a!="object")throw new TypeError(`[markdown-explorer] sources[${String(n)}] must be an object`);const{id:s,label:u,boundary:m,tree:g,children:O,ancestors:h,cacheScope:y}=a;if(!se.isExplorerSourceId(s))throw new RangeError(`[markdown-explorer] sources[${String(n)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${typeof s=="string"?JSON.stringify(s):typeof s}`);const T=`source ${JSON.stringify(s)}`;if(r.has(s))throw new RangeError(`[markdown-explorer] source ids must be unique; ${JSON.stringify(s)} repeats at sources[${String(n)}]`);if(r.add(s),typeof u!="string"&&typeof u!="function")throw new TypeError(`[markdown-explorer] ${T}.label must be a string or a function`);if(typeof u=="string"&&u.trim()==="")throw new RangeError(`[markdown-explorer] ${T}.label must not be blank`);if(Tn(T,m),V(`${T}.tree`,g,!1),V(`${T}.children`,O,!0),V(`${T}.ancestors`,h,!0),y!==void 0&&y!=="principal"&&y!=="shared")throw new RangeError(`[markdown-explorer] ${T}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(y)}`)}return t},kn=e=>{if(e===!1)return!1;if(e===void 0)return Ee;if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] treeCache must be { ttlMs, maxEntries, maxBytes } or false");const{ttlMs:t,maxEntries:r,maxBytes:n}=e;return{ttlMs:t===void 0?Ee.ttlMs:fe("treeCache.ttlMs",t,Number.MAX_SAFE_INTEGER),maxEntries:r===void 0?Ee.maxEntries:fe("treeCache.maxEntries",r,Number.MAX_SAFE_INTEGER),maxBytes:n===void 0?Ee.maxBytes:fe("treeCache.maxBytes",n,Number.MAX_SAFE_INTEGER)}},at=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] authenticate must resolve to { status, ... }");const{status:t}=e;if(t!=="signed-in"&&t!=="signed-out"&&t!=="forbidden")throw new TypeError(`[markdown-explorer] authenticate resolved to an unknown status ${JSON.stringify(t)}`);return e},ct=(e,t)=>{if(!(t instanceof Response))throw new TypeError(`[markdown-explorer] ${e} must return a Response`);return t},ut=(e,t)=>{if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");return ht.createHmac("sha256",e).update(t,"utf8").digest("base64url").slice(0,hn)},On=e=>e.view==="multi"?e.docs:e.doc===null?[]:[e.doc],ce=(e,t)=>{const r=e.getAll(t),[n]=r;return r.length===1&&n!==void 0&&n!==""?n:null},K=(e,t,r,n={})=>{const a=new Headers(r);for(const[s,u]of Object.entries({...pn,...n}))a.set(s,u);return new Response(t,{status:e,headers:a})},j=(e,t,r)=>K(w.EXPLORER_FAILURE_STATUS[e.reason],JSON.stringify({failure:e}),t,r),xn=new Set(["refresh","save","preview"]),Rn=new Set(["edit","save","preview","revisions","revision"]),lt=(e,t)=>{const r=xn.has(t)?["POST"]:["GET","HEAD"];return r.includes(e.method.toUpperCase())?null:K(405,JSON.stringify({failure:{reason:"invalid"}}),void 0,{Allow:r.join(", ")})},dt=e=>e.headers.get(w.EXPLORER_PROOF_HEADER)===w.EXPLORER_REFRESH_PROOF&&Se.crossOriginRefusal(e,Se.NO_CROSS_ORIGIN_NAVIGATION)===void 0,_n=e=>e.headers.get(w.EXPLORER_PROOF_HEADER)===w.EXPLORER_EDIT_PROOF&&Se.crossOriginRefusal(e,Se.NO_CROSS_ORIGIN_NAVIGATION)===void 0,An=async(e,t)=>{const[r,...n]=(e.headers.get("Content-Type")??"").split(";").map(T=>T.trim().toLowerCase()),a=n.find(T=>T.startsWith("charset="));if(r!==w.EXPLORER_DRAFT_MEDIA_TYPE||a!==void 0&&a!=="charset=utf-8")return{status:"error",failure:{reason:"invalid"}};const s=Number(e.headers.get("Content-Length")??"0");if(Number.isFinite(s)&&s>t)return{status:"error",failure:{reason:"too-large"}};if(e.body===null)return{status:"ok",text:""};const u=e.body.getReader(),m=[];let g=0;for(;;){const{done:T,value:A}=await u.read();if(T)break;if(g+=A.byteLength,g>t)return await u.cancel(),{status:"error",failure:{reason:"too-large"}};m.push(A)}const O=new Uint8Array(g);let h=0;for(const T of m)O.set(T,h),h+=T.byteLength;let y;try{y=new TextDecoder("utf-8",{fatal:!0}).decode(O)}catch{return{status:"error",failure:{reason:"invalid"}}}return y.includes("\0")?{status:"error",failure:{reason:"invalid"}}:{status:"ok",text:y}},vn=e=>{if(e===void 0)return;if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] edit must be an object of the editor's ports");const t=e;for(const r of["source","save","preview","revisions","revision"])V(`edit.${r}`,t[r],!1);return e},Nn=({parentHeaders:e,loaderHeaders:t,errorHeaders:r})=>{const n=new Headers,a=r===void 0?[e,t]:[e,t,r];for(const s of a)for(const[u,m]of s)u!=="set-cookie"&&n.set(u,m);return n},Pn=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the server configuration must be an object");const t=En(e.config),r=bn(e.scopeSecret);V("authenticate",e.authenticate,!1),V("principalKey",e.principalKey,!1),V("document",e.document,!1),V("asset",e.asset,!1),V("signedOutPage",e.signedOutPage,!1),V("forbiddenPage",e.forbiddenPage,!0),V("notices",e.notices,!0),V("onTreeRefreshed",e.onTreeRefreshed,!0);const n=Sn(e.sources),a=se.withExplorerSources(t,n.map(o=>o.id)),s=e.logger;if(s!==void 0&&(s===null||typeof s!="object"||typeof s.error!="function"))throw new TypeError("[markdown-explorer] logger must be an object with an error function");const u=e.logger===void 0?fr:e.logger,m=w.resolvePathRules(e.deny),g=e.deferredTimeoutMs===void 0?mn:fe("deferredTimeoutMs",e.deferredTimeoutMs,wn),O=e.textMaxBytes===void 0?We:fe("textMaxBytes",e.textMaxBytes,Ke),h=vn(e.edit);if(h===void 0&&e.editMaxBytes!==void 0)throw new TypeError("[markdown-explorer] editMaxBytes needs the edit ports");const y=e.editMaxBytes===void 0?We:fe("editMaxBytes",e.editMaxBytes,Ke),T=kn(e.treeCache),A=()=>Date.now(),D=T===!1?Qr(A):Vr({...T,now:A}),N=Ur(e.sanitizer,t.multiView.maxPanels),v=Wr({iframeHosts:t.iframeHosts,dataPath:t.dataPath,options:N,pool:Gr(Xr(),N)}),z=new Map(n.map(o=>[o.id,o])),R=se.documentStyleNames(t),{authenticate:M,principalKey:B,signedOutPage:F,forbiddenPage:p,onTreeRefreshed:E}=e,b=(o,c)=>{if(typeof o.label=="string")return o.label;const i=o.label(c);if(typeof i!="string"||i.trim()==="")throw new TypeError(`[markdown-explorer] the label of source ${JSON.stringify(o.id)} must be a non-blank string`);return i},_=(o,c)=>o.cacheScope==="shared"?o.id:`${o.id}\0${c}`,S=(o,c)=>{const i=d=>ne(u,{operation:"boundary",sourceId:o.id,path:c,error:d});let l;try{l=o.boundary.contains(c)}catch(d){return i(d),!1}return typeof l=="boolean"?l:(Ye(l,i),i(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(o.id)} must return a boolean; got ${typeof l}`)),!1)},P=async(o,c,i)=>{const{confirm:l}=o.boundary;if(l===void 0)return{status:"inside",readPath:i};let d;try{d=await l(c,i)}catch(U){return{status:"error",failure:Y(U,{operation:"boundary",sourceId:o.id,path:i},c.signal,u)}}const f=U=>(ne(u,{operation:"boundary",sourceId:o.id,path:i,error:new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} ${U}`)}),{status:"outside"});if(d===null||typeof d!="object")return f(`must resolve to { inside, readPath? }; got ${d===null?"null":typeof d}`);const{inside:k,readPath:I}=d;return k===!1?{status:"outside"}:k!==!0||typeof I!="string"?f("must resolve to { inside: false } or { inside: true, readPath: string }"):!w.isAcceptableDocumentPath(I)||m.deniesPath(I)?(ne(u,{operation:"boundary",sourceId:o.id,path:i,error:new RangeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} answered a readPath the explorer does not serve (unacceptable or denied)`)}),{status:"error",failure:{reason:"failed"}}):{status:"inside",readPath:I}},L=async(o,c)=>{const i=n.filter(d=>S(d,c));if(i.length===0)return{status:"error",failure:{reason:"forbidden"}};if(i.some(d=>d.boundary.confirm===void 0))return{status:"inside",readPath:c};let l=null;for(const d of i){const f=await P(d,o,c);if(f.status==="inside")return f;f.status==="error"&&l===null&&(l=f.failure)}return{status:"error",failure:l===null?{reason:"forbidden"}:l}},X=(o,c,i)=>{const l=({path:d,reason:f})=>hr(u,{operation:i.operation,sourceId:i.sourceId,path:d,error:new TypeError(`[markdown-explorer] an entry with ${f} was left out`)});try{return{status:"ok",entries:en(o,m,c.children!==void 0,l,d=>S(c,d))}}catch(d){return ne(u,{...i,error:d}),{status:"error",failure:{reason:"failed"}}}},$=async(o,c,i)=>{let l;try{l=await o.tree(c)}catch(f){return{status:"error",failure:Y(f,{operation:"tree",sourceId:o.id},c.signal,u)}}const d=X(l,o,{operation:"tree",sourceId:o.id});return d.status==="ok"?{status:"ok",entries:d.entries,loadedAt:i}:d},G=(o,c,i,l)=>(d,f)=>$(o,{principal:c,request:i,signal:d,refresh:l},f),Q=(o,c,i,l,d)=>D.load(_(o,i),d,G(o,c,l,!1)),J=(o,c,i,l)=>D.refresh(_(o,i),l.signal,G(o,c,l,!0)),ae=(o,c)=>{if(E===void 0)return;const i=l=>ne(u,{operation:"refresh",sourceId:o.id,error:l});try{Ye(E(c),i)}catch(l){i(l)}},C=async(o,c,i,l)=>{if(m.deniesPath(l)||!S(o,l))return{status:"error",failure:{reason:"forbidden"}};const d=await P(o,i,l);if(d.status==="outside")return{status:"error",failure:{reason:"forbidden"}};if(d.status==="error")return{status:"error",failure:d.failure};let f;try{f=await c(i,l,d.readPath)}catch(k){return{status:"error",failure:Y(k,{operation:"children",sourceId:o.id,path:l},i.signal,u)}}return X(f,o,{operation:"children",sourceId:o.id,path:l})},Z=async(o,c,i,l)=>{const d=await P(o,i,l);if(d.status==="outside")return{status:"ok",ancestors:null};if(d.status==="error")return{status:"error",failure:d.failure};let f;try{f=await c(i,l,d.readPath,{maxDepth:t.revealDocument.maxDepth})}catch(k){return{status:"error",failure:Y(k,{operation:"ancestors",sourceId:o.id,path:l},i.signal,u)}}if(Array.isArray(f)&&f.length>t.revealDocument.maxDepth)return{status:"ok",ancestors:null};try{return{status:"ok",ancestors:qr(f,l,m,k=>S(o,k))}}catch(k){return ne(u,{operation:"ancestors",sourceId:o.id,path:l,error:k}),{status:"error",failure:{reason:"failed"}}}},q=async(o,c,i,l)=>m.deniesPath(l)?{status:"error",failure:{reason:"forbidden"}}:S(o,l)?Z(o,c,i,l):{status:"ok",ancestors:null},ee=async(o,c,i)=>{if(m.deniesPath(i))return{status:"error",failure:{reason:"forbidden"}};for(const l of[o,...n.filter(d=>d!==o)]){if(c.signal.aborted)break;const d=l.ancestors;if(d===void 0||!S(l,i))continue;const f=await Z(l,d,c,i);if(f.status==="ok"&&f.ancestors!==null)return{status:"ok",source:l.id,ancestors:f.ancestors}}return gn},me=async(o,c,i)=>{if(m.deniesPath(i))return w.failureDocument("forbidden");const l=await L(o,i);if(l.status==="error")return{kind:"failure",failure:l.failure};let d;try{d=await e.document(o,i,l.readPath)}catch(I){return{kind:"failure",failure:Y(I,{operation:"document",path:i},o.signal,u)}}let f;try{f=on(d,I=>w.explorerAssetHref(t.dataPath,i,I),h!==void 0)}catch(I){return ne(u,{operation:"document",path:i,error:I}),w.failureDocument("failed")}if(f.kind!=="unsanitized-markdown")return f;const k=await v(f.html,{scope:c,signal:o.signal});return k.status==="sanitized"?{kind:"markdown",name:f.name,htmlContent:k.html,headings:f.headings,edit:f.edit}:(k.cause!==null&&ne(u,{operation:"document",path:i,error:k.cause}),w.failureDocument(k.reason))},Nt=async o=>{if(e.notices===void 0)return Ie;try{return fn(await e.notices(o))}catch(c){return Y(c,{operation:"notices"},o.signal,u),Ie}},Pt=async(o,c,i)=>{const l=ce(c,w.EXPLORER_DATA_QUERY.path);if(l===null||!w.isAcceptableDocumentPath(l))return j({reason:"invalid"},i);if(m.deniesPath(l))return ve(u,{operation:"asset",path:l}),j({reason:"forbidden"},i);const d=await L(o,l);if(d.status==="error")return j(d.failure,i);try{const f=tt(await e.asset(o,l,d.readPath));return await dr(o.request,f,i)}catch(f){return j(Y(f,{operation:"asset",path:l},o.signal,u),i)}},It=async(o,c)=>{if(m.deniesPath(c))return ve(u,{operation:"text",path:c}),w.failureDocument("forbidden");const i=await L(o,c);if(i.status==="error")return{kind:"failure",failure:i.failure};try{const l=tt(await e.asset(o,c,i.readPath)),d=await gr(l,O);return d===null?w.failureDocument("unsupported"):{kind:"text",name:l.name,text:d.text,truncated:d.truncated,url:w.explorerAssetHref(t.dataPath,c,l.version)}}catch(l){return{kind:"failure",failure:Y(l,{operation:"text",path:c},o.signal,u)}}},pe=async(o,c,i)=>m.deniesPath(i)?(ve(u,{operation:c,path:i}),{status:"error",failure:{reason:"forbidden"}}):L(o,i),Mt=async(o,c,i)=>{const l=await pe(c,"edit",i);if(l.status==="error")return{kind:"failure",failure:l.failure};try{return an(await o.source(c,i,l.readPath),y)}catch(d){return{kind:"failure",failure:Y(d,{operation:"edit",path:i},c.signal,u)}}},Lt=async(o,c,i,l,d)=>{const f=await pe(c,"save",i);if(f.status==="error")return{kind:"failure",failure:f.failure};try{return cn(await o.save(c,i,f.readPath,{text:d,baseVersion:l}),y)}catch(k){return{kind:"failure",failure:Y(k,{operation:"save",path:i},c.signal,u)}}},Dt=async(o,c,i,l,d)=>{const f=await pe(c,"preview",l);if(f.status==="error")return{kind:"failure",failure:f.failure};let k;try{k=un(await o.preview(c,l,f.readPath,d))}catch(U){return{kind:"failure",failure:Y(U,{operation:"preview",path:l},c.signal,u)}}if("kind"in k)return k.kind==="failure"?k:w.failureDocument("failed");const I=await v(k.html,{scope:i,signal:c.signal});return I.status==="sanitized"?{kind:"preview",htmlContent:I.html,headings:k.headings}:(I.cause!==null&&ne(u,{operation:"preview",path:l,error:I.cause}),w.failureDocument(I.reason))},$t=async(o,c,i)=>{const l=await pe(c,"revisions",i);if(l.status==="error")return{kind:"failure",failure:l.failure};try{return{kind:"revisions",revisions:ln(await o.revisions(c,i,l.readPath))}}catch(d){return{kind:"failure",failure:Y(d,{operation:"revisions",path:i},c.signal,u)}}},jt=async(o,c,i,l)=>{const d=await pe(c,"revision",i);if(d.status==="error")return{kind:"failure",failure:d.failure};try{return{kind:"revision",id:l,text:dn(await o.revision(c,i,d.readPath,l),y)}}catch(f){return{kind:"failure",failure:Y(f,{operation:"revision",path:i},c.signal,u)}}},zt=async(o,c,i,l,d,f)=>{const k=ce(d,w.EXPLORER_DATA_QUERY.path);if(k===null||!w.isAcceptableDocumentPath(k))return j({reason:"invalid"},f);if(c==="edit")return K(200,JSON.stringify(await Mt(o,i,k)),f);if(c==="revisions")return K(200,JSON.stringify(await $t(o,i,k)),f);if(c==="revision"){const te=ce(d,w.EXPLORER_DATA_QUERY.revision);return w.isExplorerEditToken(te)?K(200,JSON.stringify(await jt(o,i,k,te)),f):j({reason:"invalid"},f)}const I=ce(d,w.EXPLORER_DATA_QUERY.base);if(c==="save"&&!w.isExplorerEditToken(I))return j({reason:"invalid"},f);const U=await An(i.request,y);return U.status==="error"?j(U.failure,f):c==="preview"?K(200,JSON.stringify(await Dt(o,i,l,k,U.text)),f):K(200,JSON.stringify(await Lt(o,i,k,I,U.text)),f)},Ct=async({request:o,url:c,params:i})=>{const l=at(await M(o,ot)),d=st(l.headers);if(d.set("Cache-Control",Ot),l.status==="signed-out")throw ct("signedOutPage",F(o,d));if(l.status==="forbidden")throw p===void 0?Oe.data(null,{status:403,headers:d}):ct("forbiddenPage",p(o,d));const f=se.resolveExplorerLocation(a,i["*"],c.searchParams);if(f.kind==="redirect")throw Oe.redirect(f.href,{headers:d});const{location:k}=f,{principal:I}=l,U=ut(r,B(I)),te=z.get(k.source);if(te===void 0)throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(k.source)}`);const he={signal:o.signal,timeoutMs:g,late:null,handOverMs:g},re={scope:U,sources:n.map(H=>({id:H.id,label:b(H,I)})),settings:se.parseViewSettings(se.readCookieValue(o.headers.get("Cookie"),t.settingsCookie),R),tree:k.view==="single"?null:{sourceId:k.source,result:Ae(he,H=>Q(te,I,U,o,H).then(W=>W.result))},documents:On(k).map(H=>({path:H,document:Ae(he,W=>me({principal:I,request:o,signal:W,refresh:!1},U,H))})),notices:Ae({signal:o.signal,timeoutMs:g,late:Ie,handOverMs:0},H=>Nt({principal:I,request:o,signal:H,refresh:!1}))};return Oe.data(re,{headers:d})},ze=async(o,c)=>{const i=at(await M(o,c));return{authentication:i,headers:st(i.headers)}},Ht=async(o,c,i)=>{let l;try{l=await ze(c,ot)}catch(W){return j(Y(it(W),{operation:"authenticate"},c.signal,u))}const{authentication:d,headers:f}=l;if(d.status==="signed-out")return j({reason:"unauthorized"},f);if(d.status==="forbidden")return j({reason:"forbidden"},f);const{principal:k}=d;if(o==="asset")return Pt({principal:k,request:c,signal:c.signal,refresh:!1},i,f);const I=ut(r,B(k));f.set(w.EXPLORER_SCOPE_HEADER,I);const U={principal:k,request:c,signal:c.signal,refresh:!1},te=()=>j({reason:"invalid"},f);if(o==="document"){const W=ce(i,w.EXPLORER_DATA_QUERY.path);if(W===null||!w.isAcceptableDocumentPath(W))return te();const Be=c.headers.has(w.EXPLORER_PROOF_HEADER);return Be&&!dt(c)?j({reason:"forbidden"},f):K(200,JSON.stringify(await me({...U,refresh:Be},I,W)),f)}if(o==="text"){const W=ce(i,w.EXPLORER_DATA_QUERY.path);return W===null||!w.isAcceptableDocumentPath(W)?te():K(200,JSON.stringify(await It(U,W)),f)}if(o==="edit"||o==="save"||o==="preview"||o==="revisions"||o==="revision")return h===void 0?j({reason:"not-found"},f):zt(h,o,U,I,i,f);const he=ce(i,w.EXPLORER_DATA_QUERY.source),re=ce(i,w.EXPLORER_DATA_QUERY.path);if(he===null||(o==="children"||o==="ancestors"||o==="reveal")&&(re===null||!w.isAcceptableDocumentPath(re)))return te();const H=z.get(he);if(H===void 0)return j({reason:"not-found"},f);if(o==="tree")return K(200,(await Q(H,k,I,c,c.signal)).json,f);if(o==="refresh"){const W=await J(H,k,I,c);return c.signal.aborted||ae(H,_(H,I)),K(200,W.json,f)}return o==="ancestors"?H.ancestors===void 0||re===null?j({reason:"not-found"},f):K(200,JSON.stringify(await q(H,H.ancestors,U,re)),f):o==="reveal"?re===null?te():K(200,JSON.stringify(await ee(H,U,re)),f):H.children===void 0||re===null?j({reason:"not-found"},f):K(200,JSON.stringify(await C(H,H.children,U,re)),f)},Bt=async o=>{const{authentication:c,headers:i}=await ze(o,yn);if(!i.keys().next().done)throw new TypeError("[markdown-explorer] authenticate returned headers in read-only mode; a read-only authentication must only read the session (none was forwarded)");return c.status==="signed-in"},Ce=t.embeds.linkCardEndpoint===null?null:Ut.createLinkCardHandler({authorize:Bt}),Ft=async(o,c)=>{try{return await o(c)}catch(i){return j(Y(it(i),{operation:"authenticate"},c.signal,u))}},He=async(o,c,i)=>{if(new URL(o.url).pathname.endsWith(".data"))return j({reason:"not-found"});if(!w.isExplorerDataOperation(i))return j({reason:"not-found"});if(i==="link-card"){if(Ce===null)return j({reason:"not-found"});const d=lt(o,i);return d!==null?d:Ft(Ce,o)}if(Rn.has(i)&&h===void 0)return j({reason:"not-found"});const l=lt(o,i);if(l!==null)return l;if(i==="refresh"&&!dt(o))return j({reason:"forbidden"});if((i==="save"||i==="preview")&&!_n(o))return j({reason:"forbidden"});try{return await Ht(i,o,c.searchParams)}catch(d){return j(Y(d,{operation:i},o.signal,u))}};return Object.freeze({loader:Ct,headers:Nn,dataLoader:({request:o,url:c,params:i})=>He(o,c,i["*"]),dataAction:({request:o,url:c,params:i})=>He(o,c,i["*"]),forgetTree:o=>{if(typeof o!="string")throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof o}`);D.forget(o)}})},be=Object.freeze({maxEntries:2e4,maxDocumentBytes:2*1024*1024,textPreviewBytes:8*1024,walkConcurrency:8}),In=new Set(["md","markdown","mdx"]),xt=new Map([...[["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"],["svg","image/svg+xml"],["webp","image/webp"],["ico","image/x-icon"],["bmp","image/bmp"],["tif","image/tiff"],["tiff","image/tiff"],["avif","image/avif"]].map(([e,t])=>[e,{kind:"image",contentType:t}]),...[["mp4","video/mp4"],["m4v","video/mp4"],["webm","video/webm"],["mov","video/quicktime"],["avi","video/x-msvideo"],["mkv","video/x-matroska"],["ogv","video/ogg"]].map(([e,t])=>[e,{kind:"media",mediaType:"video",contentType:t}]),...[["mp3","audio/mpeg"],["wav","audio/wav"],["ogg","audio/ogg"],["oga","audio/ogg"],["opus","audio/ogg"],["m4a","audio/mp4"],["flac","audio/flac"],["aac","audio/aac"],["wma","audio/x-ms-wma"]].map(([e,t])=>[e,{kind:"media",mediaType:"audio",contentType:t}]),["pdf",{kind:"media",mediaType:"pdf",contentType:"application/pdf"}]]),Mn=new Set(["txt","text","log","csv","tsv","json","jsonc","json5","ndjson","yaml","yml","toml","ini","cfg","conf","properties","xml","xsl","xsd","dtd","html","htm","xhtml","css","scss","sass","less","styl","js","mjs","cjs","jsx","ts","mts","cts","tsx","vue","svelte","astro","py","pyi","rb","go","rs","java","kt","kts","scala","groovy","gradle","c","h","cc","cpp","cxx","hpp","hh","hxx","cs","fs","vb","swift","m","mm","php","pl","pm","r","jl","lua","dart","ex","exs","erl","hrl","hs","ml","mli","clj","cljs","elm","nim","zig","v","sol","tf","hcl","nix","sh","bash","zsh","fish","ps1","psm1","bat","cmd","sql","graphql","gql","proto","thrift","avsc","rst","adoc","asciidoc","tex","bib","org","textile","diff","patch","srt","vtt","ics","vcf","gitignore","gitattributes","editorconfig","dockerignore","npmignore","prettierrc","eslintrc","babelrc","mailmap"]),Ln=new Set(["readme","license","licence","copying","notice","authors","contributors","changelog","changes","todo","makefile","dockerfile","containerfile","procfile","gemfile","rakefile","vagrantfile","jenkinsfile","brewfile","codeowners"]),Rt=typeof ie.constants.O_NOFOLLOW=="number"?ie.constants.O_NOFOLLOW:0,_t=typeof ie.constants.O_NONBLOCK=="number"?ie.constants.O_NONBLOCK:0,ft=e=>`${e.size}-${e.mtimeNs}`,Dn=e=>e!==""&&e!=="."&&e!==".."&&!e.includes(":")&&!e.endsWith(".")&&!e.endsWith(" "),mt=e=>w.isAcceptableDocumentPath(e)&&e===e.normalize("NFC")&&e.split("/").every(Dn),At=e=>{const t=e.toLowerCase(),r=t.lastIndexOf(".");return r<0?"":t.slice(r+1)},$n=e=>{const t=At(e);if(In.has(t))return{kind:"markdown"};const r=xt.get(t);if(r!==void 0)return r.kind==="image"?{kind:"image"}:{kind:"media",mediaType:r.mediaType};const n=e.toLowerCase();return Mn.has(t)||!n.includes(".")&&Ln.has(n)?{kind:"text"}:{kind:"file"}},Le=e=>{switch(typeof e=="object"&&e!==null?e.code:void 0){case"ENOENT":case"ENOTDIR":return"not-found";case"ELOOP":case"EACCES":case"EPERM":return"forbidden";case"ENAMETOOLONG":return"invalid";case"EISDIR":return"unsupported";default:return null}},vt=e=>{const t=Le(e);return t===null?e:new ge(t)},jn=e=>{const t=typeof e=="object"&&e!==null?e.code:void 0;return t==="EACCES"||t==="EPERM"||t==="ENOENT"||t==="ENOTDIR"},pt=async(e,t)=>{const r=[];for await(const n of e.createReadStream({start:0,end:t-1,autoClose:!1}))r.push(n);return Buffer.concat(r)},zn=(e,t)=>e!==null?{start:e.offset,end:e.offset+e.length-1}:t===0n?{}:{start:0,end:Number(t)-1},Cn=async(e,t,r,n)=>{let a;try{a=await we.open(e,ie.constants.O_RDONLY|Rt|_t);const g=await a.stat({bigint:!0});if(!g.isFile()||g.ino!==t.ino||g.dev!==t.dev||g.size!==t.size||g.mtimeNs!==t.mtimeNs)throw new ge("not-found")}catch(g){throw await a?.close(),vt(g)}const s=a.createReadStream(zn(r,t.size)),u=Gt.Readable.toWeb(s),m=()=>{s.destroy(n.reason)};return n.aborted?m():n.addEventListener("abort",m,{once:!0}),u},Hn=(e,t)=>{const r=se.NAME_COLLATOR.compare(e,t);return r!==0?r:e===t?0:e<t?-1:1},Bn=e=>{let t=0;const r=[];return async n=>{t<e?t+=1:await new Promise(a=>r.push(a));try{return await n()}finally{const a=r.shift();a===void 0?t-=1:a()}}},Fn=(e,t)=>{if(e.isSymbolicLink())return"symbolic-link";if(!(e.isDirectory()||e.isFile()))return"special-file";const{name:r}=e;return r!==r.normalize("NFC")?"not-nfc":r.includes(":")?"colon":r.endsWith(".")||r.endsWith(" ")?"trailing-dot-or-space":w.isAcceptableDocumentPath(r)?w.isAcceptableDocumentPath(t)?null:"path-too-long":"control-character-or-backslash"},Un=new Set(["id","label","root","pathPrefix","parse","deny","maxEntries","maxDocumentBytes","textPreviewBytes","walkConcurrency","cacheScope","reportSkipped"]),Te=(e,t,r)=>{if(t===void 0)return r;if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] ${e} must be a positive integer; got ${String(t)}`);return t},Xn=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] createFileSystemSource needs an options object");for(const b of Object.keys(e))if(!Un.has(b))throw new TypeError(`[markdown-explorer] createFileSystemSource does not know the option ${JSON.stringify(b)}`);const{id:t,label:r,root:n,parse:a}=e;if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] a file-system source needs a non-empty id");if(typeof r!="string"||r.trim()==="")throw new TypeError("[markdown-explorer] a file-system source needs a non-blank label");if(typeof a!="function")throw new TypeError("[markdown-explorer] a file-system source needs a parse function");if(typeof n!="string"||!oe.isAbsolute(n))throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);let s;try{s=ie.statSync(n).isDirectory()}catch(b){throw new RangeError(`[markdown-explorer] root does not exist: ${n}`,{cause:b})}if(!s)throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);const u=ie.realpathSync(n),m=e.pathPrefix;if(typeof m!="string")throw new TypeError('[markdown-explorer] pathPrefix is required: "" for a source over the whole root, or relative segments ending with "/"');if(m!==""&&!(m.endsWith("/")&&mt(m.slice(0,-1))))throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(m)}`);const g=w.resolvePathRules(e.deny),O=Te("maxEntries",e.maxEntries,be.maxEntries),h=Te("maxDocumentBytes",e.maxDocumentBytes,be.maxDocumentBytes),y=Te("textPreviewBytes",e.textPreviewBytes,be.textPreviewBytes),T=Te("walkConcurrency",e.walkConcurrency,be.walkConcurrency),A=e.cacheScope===void 0?"principal":e.cacheScope;if(A!=="principal"&&A!=="shared")throw new RangeError(`[markdown-explorer] cacheScope must be "principal" or "shared"; got ${JSON.stringify(A)}`);const D=e.reportSkipped;if(D!==void 0&&typeof D!="function")throw new TypeError("[markdown-explorer] reportSkipped must be a function");const N=D===void 0?b=>{console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(b.sourceId)} does not list ${JSON.stringify(b.path)}: ${b.reason}`)}:D,v=new Set,z=b=>{const _=oe.resolve(u,...b.split("/")),S=oe.relative(u,_);return S===""||S===".."||S.startsWith(`..${oe.sep}`)||oe.isAbsolute(S)?null:_},R=(b,_)=>{const S=`${_}\0${b}`;v.has(S)||v.size>=O||(v.add(S),N({sourceId:t,path:b,reason:_}))},M=async({signal:b})=>{b.throwIfAborted();const _=new AbortController,S=()=>{_.abort(b.reason)};b.addEventListener("abort",S,{once:!0});const P=Bn(T);let L=0;const X=async($,G)=>{const Q=await P(async()=>{_.signal.throwIfAborted();try{return await we.readdir($,{withFileTypes:!0})}catch(C){if(G===""||!jn(C))throw C;return null}});if(_.signal.throwIfAborted(),Q===null)return R(`${m}${G}`,"unreadable-directory"),null;const J=[];for(const C of Q){if(g.deniesName(C.name))continue;const Z=G===""?C.name:`${G}/${C.name}`,q=`${m}${Z}`,ee=Fn(C,q);if(ee!==null){R(q,ee);continue}J.push({dirent:C,relativePath:Z,path:q})}if(L+=J.length,L>O)throw new ge("too-large");return J.sort((C,Z)=>Hn(C.dirent.name,Z.dirent.name)),(await Promise.all(J.map(async({dirent:C,relativePath:Z,path:q})=>{if(!C.isDirectory())return{name:C.name,path:q,type:"file"};const ee=await X(oe.join($,C.name),Z);return ee===null?null:{name:C.name,path:q,type:"directory",children:ee}}))).filter(C=>C!==null)};try{const $=await X(u,"");if($===null)throw new Error("[markdown-explorer] the source's root could not be listed");return $}catch($){throw _.abort(),$}finally{b.removeEventListener("abort",S)}},B=async b=>{if(!b.startsWith(m))return{status:"refused",reason:"not-found"};const _=b.slice(m.length);if(!mt(_))return{status:"refused",reason:"invalid"};if(g.deniesPath(_))return{status:"refused",reason:"forbidden"};const S=z(_);if(S===null)return{status:"refused",reason:"forbidden"};const P=await we.lstat(S,{bigint:!0});if(P.isSymbolicLink())return{status:"refused",reason:"forbidden"};if(!P.isFile())return{status:"refused",reason:"unsupported"};const L=await we.realpath(S);return L!==S||g.deniesPath(oe.relative(u,L).split(oe.sep).join("/"))?{status:"refused",reason:"forbidden"}:{status:"file",target:S,name:_.slice(_.lastIndexOf("/")+1),stats:P}},F=async(b,_,S)=>{let P;try{const L=await B(S);if(L.status==="refused")return w.failureDocument(L.reason);const{target:X,name:$,stats:G}=L,Q=$n($),J=ft(G);if(Q.kind==="image")return{kind:"image",name:$,version:J};if(Q.kind==="media")return{kind:"media",name:$,mediaType:Q.mediaType,version:J};if(Q.kind==="file")return{kind:"file",name:$,version:J};P=await we.open(X,ie.constants.O_RDONLY|Rt|_t);const ae=await P.stat({bigint:!0});if(!ae.isFile()||ae.ino!==G.ino||ae.dev!==G.dev)return w.failureDocument("forbidden");if(Q.kind==="markdown"){if(ae.size>BigInt(h))return w.failureDocument("too-large");const ee=await pt(P,h+1);if(ee.length>h)return w.failureDocument("too-large");const me=await a(new TextDecoder("utf-8").decode(ee),_);return{kind:"markdown",name:$,htmlContent:me.htmlContent,headings:me.headings,edit:null}}const C=await pt(P,y);if(C.includes(0))return{kind:"file",name:$,version:J};const Z=ae.size>BigInt(y),q=new TextDecoder("utf-8").decode(C,{stream:Z});return{kind:"text",name:$,text:q,truncated:Z,version:J}}catch(L){const X=Le(L);if(X===null)throw L;return w.failureDocument(X)}finally{await P?.close()}},p=async(b,_,S)=>{let P;try{P=await B(S)}catch(J){throw vt(J)}if(P.status==="refused")throw new ge(P.reason);const{target:L,name:X,stats:$}=P,G=xt.get(At(X)),Q=G===void 0?"":G.contentType;return{name:X,contentType:Q,size:Number($.size),version:ft($),open:J=>Cn(L,$,J,b.signal)}},E=async(b,_,S)=>{let P;try{P=await B(S)}catch($){if(Le($)!==null)return null;throw $}if(P.status==="refused")return null;const L=S.slice(m.length).split("/");if(L.some($=>g.deniesName($)))return null;const X=L.slice(0,-1);return X.map(($,G)=>`${m}${X.slice(0,G+1).join("/")}`)};return Object.freeze({id:t,label:r,cacheScope:A,boundary:Object.freeze({contains:b=>b.startsWith(m)}),tree:M,ancestors:E,document:F,asset:p})};exports.DEFAULT_DENIED_PATH_SEGMENTS=w.DEFAULT_DENIED_PATH_SEGMENTS;exports.MAX_DOCUMENT_PATH_LENGTH=w.MAX_DOCUMENT_PATH_LENGTH;exports.isAcceptableDocumentPath=w.isAcceptableDocumentPath;exports.isDeniedPath=w.isDeniedPath;exports.ExplorerError=ge;exports.anonymousAccess=Jt;exports.createFileSystemSource=Xn;exports.createMarkdownExplorer=Pn;
|
package/dist/server.d.cts
CHANGED
|
@@ -3,5 +3,5 @@ export { type AnonymousAccess, type AnonymousPrincipal, anonymousAccess } from "
|
|
|
3
3
|
export { createMarkdownExplorer } from "./server/createMarkdownExplorer.cjs";
|
|
4
4
|
export { ExplorerError, type ExplorerLogDetail, type ExplorerLogger, type ExplorerOperation } from "./server/errors.cjs";
|
|
5
5
|
export { createFileSystemSource, type FileSystemSkippedEntry, type FileSystemSkipReason, type FileSystemSource, type FileSystemSourceOptions } from "./server/fileSystemSource.cjs";
|
|
6
|
-
export type { ExplorerAncestorsOptions, ExplorerAssetFile, ExplorerAuthentication, ExplorerAuthenticationMode, ExplorerBoundaryAnswer, ExplorerByteRange, ExplorerHostDocument, ExplorerPageLoaderResult, ExplorerSource, ExplorerSourceBoundary, ExplorerSourceContext, MarkdownExplorerServer, MarkdownExplorerServerConfig, } from "./server/ports.cjs";
|
|
6
|
+
export type { ExplorerAncestorsOptions, ExplorerAssetFile, ExplorerAuthentication, ExplorerAuthenticationMode, ExplorerBoundaryAnswer, ExplorerByteRange, ExplorerDraft, ExplorerEditPorts, ExplorerHostDocument, ExplorerHostEditSource, ExplorerHostPreview, ExplorerHostSaveResult, ExplorerPageLoaderResult, ExplorerSource, ExplorerSourceBoundary, ExplorerSourceContext, MarkdownExplorerServer, MarkdownExplorerServerConfig, } from "./server/ports.cjs";
|
|
7
7
|
export type { HtmlSanitizerOptions } from "./server/sanitizer.cjs";
|
package/dist/server.d.ts
CHANGED
|
@@ -3,5 +3,5 @@ export { type AnonymousAccess, type AnonymousPrincipal, anonymousAccess } from "
|
|
|
3
3
|
export { createMarkdownExplorer } from "./server/createMarkdownExplorer.js";
|
|
4
4
|
export { ExplorerError, type ExplorerLogDetail, type ExplorerLogger, type ExplorerOperation } from "./server/errors.js";
|
|
5
5
|
export { createFileSystemSource, type FileSystemSkippedEntry, type FileSystemSkipReason, type FileSystemSource, type FileSystemSourceOptions } from "./server/fileSystemSource.js";
|
|
6
|
-
export type { ExplorerAncestorsOptions, ExplorerAssetFile, ExplorerAuthentication, ExplorerAuthenticationMode, ExplorerBoundaryAnswer, ExplorerByteRange, ExplorerHostDocument, ExplorerPageLoaderResult, ExplorerSource, ExplorerSourceBoundary, ExplorerSourceContext, MarkdownExplorerServer, MarkdownExplorerServerConfig, } from "./server/ports.js";
|
|
6
|
+
export type { ExplorerAncestorsOptions, ExplorerAssetFile, ExplorerAuthentication, ExplorerAuthenticationMode, ExplorerBoundaryAnswer, ExplorerByteRange, ExplorerDraft, ExplorerEditPorts, ExplorerHostDocument, ExplorerHostEditSource, ExplorerHostPreview, ExplorerHostSaveResult, ExplorerPageLoaderResult, ExplorerSource, ExplorerSourceBoundary, ExplorerSourceContext, MarkdownExplorerServer, MarkdownExplorerServerConfig, } from "./server/ports.js";
|
|
7
7
|
export type { HtmlSanitizerOptions } from "./server/sanitizer.js";
|