@aiquants/markdown-explorer 0.14.0 → 0.15.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 CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.15.0 (2026-10-21) — an `asset` port that may answer a short-lived URL, and `@aiquants/markdown` 7
4
+
5
+ ### Added
6
+
7
+ - **The `asset` port may answer a short-lived URL instead of bytes.** The port receives a fourth argument,
8
+ `{ redirect }` (the new `ExplorerAssetOptions`), which is `true` only when the `asset` operation delivers the stored
9
+ file. The port may then answer `{ kind: "redirect", url }` (the new `ExplorerAssetRedirect`) with an absolute `https:`
10
+ URL without credentials, and the data route answers `302` to it with `Cache-Control: private, no-store` and
11
+ `Referrer-Policy: no-referrer`, after the same deny rules and admission, for GET and HEAD, with or without `Range`.
12
+ Hosts that never answer a redirect keep streaming, unchanged; see [Redirecting to the storage](README.md#redirecting-to-the-storage)
13
+ for what a redirecting host must allow (CSP origins, COEP and CORP, seeking against the URL's lifetime, no shared caching).
14
+
15
+ ### Changed
16
+
17
+ - **The peer `@aiquants/markdown` is `^7.0.0`.** Its service and `parseMarkdown` require `MARKDOWN_SOCKET_PATH`, its
18
+ socket is owner-only by default and it refuses non-canonical schemes; a host upgrades both together.
19
+ - **An `asset` answer that carries a `kind` key must be a valid redirect.** A redirect where `redirect` is `false`
20
+ (`&as=text` and the `text` operation read the bytes themselves), a URL that is not absolute `https:` without
21
+ credentials, or another `kind` is a contract violation, logged and answered `failed`, as any malformed answer.
22
+
3
23
  ## 0.14.0 (2026-10-16)
4
24
 
5
25
  ### Breaking
package/README.md CHANGED
@@ -282,7 +282,7 @@ The full contract, including canonicalization, is in [URL contract](docs/behavio
282
282
  | `scopeSecret` | `string` | The deployment's secret for the readers' scopes: at least 32 characters (a shorter one throws a `RangeError`) and the same on every server instance. |
283
283
  | `sources` | `ExplorerSource<P>[]` | The sources in switcher order (at least one; the first is the default): `id` (lowercase letters, digits and `-`, starting with a letter or digit, unique; the URL's `source` value), `label` (a string, or a function of the principal), `boundary` (where the source's documents may lie, see [Source boundaries](#source-boundaries)), `tree(context)` (lists the source's roots), `children?(context, path, readPath)` for lazy folders (asked only while the tree shows the folder open — the reader opened it, Expand all opened it (a press keeps opening folders as their listings land, within `expandAll`), or a remembered expansion opened it — and only for a path inside the source's boundary; a listing no tree wants any more is aborted through `context.signal`, which the source should honour), `ancestors?(context, path, readPath, options)` (the folders down to a document, for the reader's reveal; see [Revealing the open document](#revealing-the-open-document)), `cacheScope?` (`"principal"`, the default, or `"shared"`). The `context` is described under [Entries and notices](#entries-and-notices). |
284
284
  | `document` | `(context, path, readPath) => Promise<ExplorerHostDocument>` | Resolves a document path. Called only for a path inside at least one source's boundary; `readPath` is what the admitting source's `confirm` answered (`path` when that source has no `confirm`), so read `readPath` and show the document as `path`. An image, media, text or file document reports its file's `version`; the explorer writes its URL (see [Documents](#documents)). |
285
- | `asset` | `(context, path, readPath) => Promise<ExplorerAssetFile>` | Finds the file behind the data route's `asset` operation (and its `text` operation, which reads a Markdown document's source through it): any regular file the document admission admits, whatever its kind. Called only after the path passed the deny rules and the same union admission as a document, with the same `readPath`; see [Serving files](#serving-files). |
285
+ | `asset` | `(context, path, readPath, options) => Promise<ExplorerAssetFile \| ExplorerAssetRedirect>` | Finds the file behind the data route's `asset` operation (and its `text` operation, which reads a Markdown document's source through it): any regular file the document admission admits, whatever its kind. Called only after the path passed the deny rules and the same union admission as a document, with the same `readPath`; see [Serving files](#serving-files). With `options.redirect` true it may answer a short-lived URL instead, see [Redirecting to the storage](#redirecting-to-the-storage). |
286
286
  | `signedOutPage` | `(request, headers) => Response` | The page response for a signed-out reader, usually a redirect to sign-in. Data requests answer 401 instead. |
287
287
  | `forbiddenPage?` | `(request, headers) => Response` | The page response for a reader without access (default: a 403 for the route's error boundary). |
288
288
  | `notices?` | `(context) => Promise<ExplorerNotice[]>` | Callouts above the tree (a missing permission with a link that grants it, for example). |
@@ -541,6 +541,33 @@ The URL carries the path in its query, so no name needs an extra escape and the
541
541
  The data route's `text` operation reads a file through the same port for the Source toggle: `<dataPath>/text?path=<document path>` (GET and HEAD) takes the same authentication, deny rules (a refusal logged once with the operation `text`) and admission as `asset`, then answers JSON like a document request — status 200 with a text document (`name`, `text`, `truncated`, and the file's asset `url` with its version) or a failure document, and the reader's scope header.
542
542
  It reads at most `textMaxBytes` bytes (the first ones as a range when `size` is larger, the whole file otherwise, an empty file never, a file of unknown `size` one byte past the limit to learn whether more follows), cancels the stream once enough was read, decodes them as UTF-8 (a leading byte order mark dropped, a multi-byte character the limit cuts left out), and answers `unsupported` for bytes holding NUL and `failed` (logged) for a stream that ends before the `size` the port reported. It sends no refresh mark: the port receives `refresh: false`.
543
543
 
544
+ ### Redirecting to the storage
545
+
546
+ A host whose storage issues short-lived URLs (a storage-api `gcs://` signed URL, for example) can let the browser read a file's bytes from the storage instead of through the explorer.
547
+ The `asset` port receives a fourth argument, `{ redirect }`: it is `true` only when the `asset` operation delivers the stored file, and `false` for `&as=text` and the `text` operation, which read the bytes themselves.
548
+ When it is `true` the port may answer an `ExplorerAssetRedirect`, `{ kind: "redirect", url }`, instead of an `ExplorerAssetFile`:
549
+
550
+ ```ts
551
+ asset: async (context, path, readPath, { redirect }) =>
552
+ redirect ? { kind: "redirect", url: await signedUrlOf(readPath, context.signal) } : fileOf(readPath, context.signal),
553
+ ```
554
+
555
+ The explorer then answers `302` with `Location: <url>`, `Cache-Control: private, no-store` and `Referrer-Policy: no-referrer` (plus the headers authentication returned), for GET and HEAD alike and with or without `Range`: the storage answers ranges itself.
556
+ The deny rules and the source admission run before the port exactly as for a file, so a denied or unadmitted path never reaches the port and is never redirected; `If-None-Match` is not read for a redirect.
557
+ The page's HTML keeps pointing at the explorer's own `asset` operation.
558
+ The URL must be absolute `https:` without credentials (it is written as the URL parser serializes it); any other URL, a redirect when `redirect` is `false`, or an answer whose `kind` is not `"redirect"` is a contract violation, logged and answered `failed` (500).
559
+ A host that never answers a redirect keeps streaming through `open`, unchanged.
560
+
561
+ What a host that redirects must allow and decide:
562
+
563
+ | Concern | What to do |
564
+ | --- | --- |
565
+ | CSP | The redirect target is checked against the page's policy. Add the storage's origin (`https://storage.googleapis.com` for storage-api's Cloud Storage URLs) to `img-src` and `media-src`, to `frame-src` / `object-src` when PDFs are shown in frames, and to `connect-src` for `fetch`. |
566
+ | COEP and CORP | Under `Cross-Origin-Embedder-Policy: require-corp` a cross-origin response needs `Cross-Origin-Resource-Policy: cross-origin` or CORS, and Cloud Storage sends neither by default: configure the bucket's CORS for the page's origin and load with `crossorigin="anonymous"`, or use `COEP: credentialless`. CORS is also needed whenever the bytes are read into a canvas. |
567
+ | Range, seeking and lifetime | A media element may reuse the URL it was redirected to for later range requests (seeking), and those fail with 403 once the URL expires. Choose a lifetime that covers a viewing session, or make sure each request comes back through the explorer's route. |
568
+ | Caching | The redirect is never cached (`private, no-store`). Never let a shared cache (a CDN or reverse proxy) store it: the URL lets whoever holds it read the file until it expires. |
569
+ | What the storage serves | The storage answers with the object's stored content type and its own headers, not the explorer's (download disposition, `nosniff`, sandboxing). Redirect only the kinds whose in-place display you accept (images, audio, video); the port receives `path` to decide. |
570
+
544
571
  ### Link cards
545
572
 
546
573
  With `embeds: { linkCards: true }`, the data route has a `link-card` operation: `GET` or `HEAD` `<dataPath>/link-card?url=<href>`, which `@aiquants/markdown`'s link card asks (same-origin, in the background, once the card nears the viewport). It is the only route of the cards: the explorer creates `@aiquants/markdown`'s `createLinkCardHandler` once, in `createMarkdownExplorer`, behind the read-only authentication, and passes every answer of it through unchanged — status, headers and cache headers. In order:
@@ -57,6 +57,13 @@ export type ExplorerAssetFile = {
57
57
  readonly version: string;
58
58
  readonly open: (range: ExplorerByteRange | null) => Promise<ReadableStream<Uint8Array>>;
59
59
  };
60
+ export type ExplorerAssetRedirect = {
61
+ readonly kind: "redirect";
62
+ readonly url: string;
63
+ };
64
+ export type ExplorerAssetOptions = {
65
+ readonly redirect: boolean;
66
+ };
60
67
  export type ExplorerHostDocument = {
61
68
  readonly kind: "markdown";
62
69
  readonly name: string;
@@ -122,7 +129,7 @@ export type MarkdownExplorerServerConfig<P> = {
122
129
  readonly scopeSecret: string;
123
130
  readonly sources: readonly ExplorerSource<P>[];
124
131
  readonly document: (context: ExplorerSourceContext<P>, path: string, readPath: string) => Promise<ExplorerHostDocument>;
125
- readonly asset: (context: ExplorerSourceContext<P>, path: string, readPath: string) => Promise<ExplorerAssetFile>;
132
+ readonly asset: (context: ExplorerSourceContext<P>, path: string, readPath: string, options: ExplorerAssetOptions) => Promise<ExplorerAssetFile | ExplorerAssetRedirect>;
126
133
  readonly signedOutPage: (request: Request, headers: Headers) => Response;
127
134
  readonly forbiddenPage?: (request: Request, headers: Headers) => Response;
128
135
  readonly notices?: (context: ExplorerSourceContext<P>) => Promise<readonly ExplorerNotice[]>;
@@ -57,6 +57,13 @@ export type ExplorerAssetFile = {
57
57
  readonly version: string;
58
58
  readonly open: (range: ExplorerByteRange | null) => Promise<ReadableStream<Uint8Array>>;
59
59
  };
60
+ export type ExplorerAssetRedirect = {
61
+ readonly kind: "redirect";
62
+ readonly url: string;
63
+ };
64
+ export type ExplorerAssetOptions = {
65
+ readonly redirect: boolean;
66
+ };
60
67
  export type ExplorerHostDocument = {
61
68
  readonly kind: "markdown";
62
69
  readonly name: string;
@@ -122,7 +129,7 @@ export type MarkdownExplorerServerConfig<P> = {
122
129
  readonly scopeSecret: string;
123
130
  readonly sources: readonly ExplorerSource<P>[];
124
131
  readonly document: (context: ExplorerSourceContext<P>, path: string, readPath: string) => Promise<ExplorerHostDocument>;
125
- readonly asset: (context: ExplorerSourceContext<P>, path: string, readPath: string) => Promise<ExplorerAssetFile>;
132
+ readonly asset: (context: ExplorerSourceContext<P>, path: string, readPath: string, options: ExplorerAssetOptions) => Promise<ExplorerAssetFile | ExplorerAssetRedirect>;
126
133
  readonly signedOutPage: (request: Request, headers: Headers) => Response;
127
134
  readonly forbiddenPage?: (request: Request, headers: Headers) => Response;
128
135
  readonly notices?: (context: ExplorerSourceContext<P>) => Promise<readonly ExplorerNotice[]>;
package/dist/server.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("./dataRoute-BONacTPi.cjs"),wt=require("node:crypto"),Jt=require("@aiquants/markdown/server"),ke=require("@aiquants/request-isolation"),Re=require("react-router"),se=require("./location-D6RE3wAN.cjs"),ie=require("node:fs"),ne=require("node:path"),_e=require("node:url"),Yt=require("node:worker_threads"),me=require("node:fs/promises"),Wt=require("node:stream");var Ae=typeof document<"u"?document.currentScript:null;const Ue=Object.freeze({kind:"anonymous"}),Kt=Object.freeze({authenticate:async()=>({status:"signed-in",principal:Ue}),principalKey:()=>Ue.kind,signedOutPage:(e,t)=>new Response(null,{status:401,headers:t})}),Vt="application/octet-stream",yt="application/pdf",Qt=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",yt]),gt="default-src 'none'; media-src 'self'; style-src 'unsafe-inline'",Et=`${gt}; sandbox`,Zt=`${gt}; sandbox allow-same-origin`,Xe=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,qt=/^[\t\n\r ]+|[\t\n\r ]+$/gu,De=/^[\t ]+|[\t ]+$/gu,er=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(De,"")),r="",n>=e.length)return t;n+=1}},tr=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),i=t.slice(r+1,a<0?t.length:a).replace(/[\t\n\r ]+$/u,"");return Xe.test(n)&&Xe.test(i)?`${n}/${i}`.toLowerCase():null},rr=e=>{let t=null;for(const r of er(e)){const n=tr(r);n!==null&&n!=="*/*"&&(t=n)}return t},nr=/['()*]/gu,bt=e=>encodeURIComponent(e).replace(nr,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),or=Object.freeze({"Cache-Control":"private, max-age=60, stale-while-revalidate=600, no-transform",Vary:"Cookie"}),sr=(e,t)=>{const r=rr(e),n=r!==null&&Qt.has(r),a=n&&(r.startsWith("audio/")||r.startsWith("video/"));return{contentType:r===null?Vt:r,inline:n,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`${n?"inline":"attachment"}; filename*=UTF-8''${bt(t)}`,...r===yt?{}:{"Content-Security-Policy":a?Zt:Et},"Cross-Origin-Resource-Policy":"same-origin"}}},ir="text/plain; charset=utf-8",ar=e=>({contentType:ir,inline:!0,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`inline; filename*=UTF-8''${bt(e)}`,"Content-Security-Policy":Et,"Cross-Origin-Resource-Policy":"same-origin"}}),cr=/^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu,Ee=Object.freeze({kind:"whole"}),Ge=Object.freeze({kind:"unsatisfiable"}),ur=(e,t,r)=>{const n=e.get("Range");if(n===null)return Ee;const a=e.get("If-Range");if(a!==null&&a!==r)return Ee;const i=cr.exec(n);if(i===null)return Ee;const[,c,m,y]=i;if(y!==void 0){const g=Number(y);if(g===0)return Ge;const k=Math.max(0,t-g);return{kind:"partial",range:{offset:k,length:t-k}}}const x=Number(c),h=m===""?Number.POSITIVE_INFINITY:Number(m);return h<x?Ee:x>=t?Ge:{kind:"partial",range:{offset:x,length:Math.min(h,t-1)-x+1}}},Je="W/",dr=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(De,"")),r=a+1);return t.push(e.slice(r).replace(De,"")),t},Ye=e=>e.startsWith(Je)?e.slice(Je.length):e,lr=(e,t)=>{if(e===null)return!1;const r=dr(e);if(r.length===1&&r[0]==="*")return!0;const n=Ye(t);return r.some(a=>Ye(a)===n)},fr=(e,t)=>{let r=t;return e.pipeThrough(new TransformStream({transform:(n,a)=>{const i=n.byteLength>r?n.subarray(0,r):n;r-=i.byteLength,a.enqueue(i),r===0&&a.terminate()},flush:n=>{r>0&&n.error(new RangeError("[markdown-explorer] the asset ended before its declared length"))}}))},ve=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 i=await a();return new Response(n===null?i:fr(i,n),{status:t,headers:r})},mr=(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})},pr=async(e,t,r,n)=>{const a=`"${t.version}"`,i=n==="text"?ar(t.name):sr(t.contentType,t.name),c=new Headers(r);for(const[x,h]of Object.entries({...i.headers,...or,ETag:a}))c.set(x,h);if(lr(e.headers.get("If-None-Match"),a))return new Response(null,{status:304,headers:c});if(c.set("Content-Type",i.contentType),t.size===null)return ve(e,200,c,null,()=>t.open(null));if(t.size===0)return c.set("Content-Length","0"),new Response(null,{status:200,headers:c});c.set("Accept-Ranges","bytes");const m=ur(e.headers,t.size,a);if(m.kind==="unsatisfiable")return mr(r,t.size);if(m.kind==="whole")return ve(e,200,c,t.size,()=>t.open(null));const{range:y}=m;return c.set("Content-Range",`bytes ${y.offset}-${y.offset+y.length-1}/${t.size}`),ve(e,206,c,y.length,()=>t.open(y))},Ne=(e,t)=>{const r=new AbortController,n=t(AbortSignal.any([e.signal,r.signal]));return new Promise(a=>{let i;const c=setTimeout(()=>{a(e.late),i=setTimeout(()=>r.abort(),e.handOverMs)},e.timeoutMs),m=()=>{clearTimeout(c),clearTimeout(i)};n.then(y=>{m(),a(y)},()=>{m(),a(e.late)})})},hr=Object.freeze({error:(e,t)=>{console.error(e,t)}}),Tt=Symbol.for("@aiquants/markdown-explorer:ExplorerError");class ye 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,Tt,{value:!0})}}const wr=e=>e instanceof Error&&Object.hasOwn(e,Tt)&&w.isExplorerFailureReason(e.reason),yr=e=>typeof e=="object"&&e!==null&&e.name==="AbortError",je=(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})}},oe=(e,t)=>je(e,`[markdown-explorer] ${t.operation} failed`,t),gr=(e,t)=>je(e,`[markdown-explorer] ${t.operation} left out an entry`,t),Pe=(e,t)=>je(e,`[markdown-explorer] ${t.operation} refused a path the deny rules match`,{...t,error:new RangeError("[markdown-explorer] the path matches a deny rule")}),We=(e,t)=>{e===null||typeof e!="object"&&typeof e!="function"||Promise.resolve(e).then(void 0,t)},Y=(e,t,r,n)=>wr(e)?w.failureOf(e.reason,e.code):(yr(e)||r.aborted||oe(n,{...t,error:e}),{reason:"failed"}),Ke=2*1024*1024,Ve=256*1024*1024,Er=async(e,t)=>{const r=e.getReader(),n=new Uint8Array(t);let a=0;for(;a<t;){const{done:i,value:c}=await r.read();if(i)return n.subarray(0,a);const m=c.subarray(0,t-a);n.set(m,a),a+=m.byteLength}return r.cancel().catch(()=>{}),n},br=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 Er(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 i=r||a.byteLength>t,c=i?a.subarray(0,t):a;return c.includes(0)?null:{text:new TextDecoder("utf-8").decode(c,{stream:i}),truncated:i}},Qe=(e,t)=>{if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] a cache ${e} must be a positive integer; got ${String(t)}`)},St=(e,t)=>{Qe("capacity",e),t!==void 0&&Qe("weight budget",t.max);const r=new Map;let n=0;const a=i=>{const c=r.get(i);c!==void 0&&(r.delete(i),n-=c.weight)};return{get:i=>{const c=r.get(i);if(c!==void 0)return r.delete(i),r.set(i,c),c.value},set:(i,c)=>{a(i);const m=t===void 0?0:t.of(i,c);if(!(t!==void 0&&m>t.max)){r.set(i,{value:c,weight:m}),n+=m;for(const y of r.keys()){if(r.size<=e&&(t===void 0||n<=t.max))break;a(y)}}},delete:a,size:()=>r.size,weight:()=>n}},kt=e=>Math.max(1,e-1),Tr=2147483647,Ze=Object.freeze({status:"aborted"}),de=(e,t,r)=>{const n=(e.get(t)??0)+r;n===0?e.delete(t):e.set(t,n)},fe=(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)}`)},Sr=e=>e!==null&&typeof e=="object"&&e.ready===!0&&!("id"in e),kr=(e,t)=>e!==null&&typeof e=="object"&&e.id===t&&"output"in e,xr=({url:e,size:t,deadlineMs:r,jobsPerScope:n,maxQueuedJobs:a,heapLimits:i})=>{fe("size",t,Number.MAX_SAFE_INTEGER),fe("deadline",r,Tr),fe("jobsPerScope",n,Number.MAX_SAFE_INTEGER),fe("maxQueuedJobs",a,Number.MAX_SAFE_INTEGER),fe("maxOldGenerationSizeMb",i.maxOldGenerationSizeMb,Number.MAX_SAFE_INTEGER),fe("maxYoungGenerationSizeMb",i.maxYoungGenerationSizeMb,Number.MAX_SAFE_INTEGER);const c=Object.freeze({maxOldGenerationSizeMb:i.maxOldGenerationSizeMb,maxYoungGenerationSizeMb:i.maxYoungGenerationSizeMb}),m=new Set,y=[],x=new Map,h=new Map,g=kt(t);let k=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&&(de(x,b.scope,-1),de(h,b.scope,-1),b.settle(E))},$=p=>{const[E]=y.splice(p,1);E?.detach()},N=()=>{let p=-1,E=g,b=Number.POSITIVE_INFINITY;for(const[R,S]of y.entries()){const P=x.get(S.scope)??0,L=h.get(S.scope)??0;(P<E||P===E&&p>=0&&L<b)&&(p=R,E=P,b=L)}return p},_=(p,E)=>{m.has(p)&&(m.delete(p),A(p,E),p.worker.terminate().catch(()=>{}),F())},z=p=>{p.timer=setTimeout(()=>{_(p,{status:"timeout"})},r)},v=(p,E)=>p.sent?{status:"crashed",error:E}:{status:"unavailable",error:E},I=(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()}},C=()=>{const p={worker:new Yt.Worker(e,{resourceLimits:c}),job:null,sent:!1,timer:null,ready:!1};return p.worker.unref(),p.timer=setTimeout(()=>{_(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&&Sr(E)){p.ready=!0,p.timer!==null&&clearTimeout(p.timer),p.timer=null,p.job===null?p.worker.unref():I(p,p.job),p.job===null&&F();return}const{job:b}=p;if(b===null||!kr(E,b.id)){_(p,v(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=>{_(p,v(p,E))}),p.worker.on("messageerror",E=>{_(p,v(p,E))}),p.worker.on("exit",E=>{_(p,v(p,new Error(`[markdown-explorer] a worker exited with code ${String(E)}`)))}),m.add(p),p},F=()=>{for(;;){const p=N(),E=y[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=C()}catch(S){$(p),de(h,E.scope,-1),E.settle({status:"unavailable",error:S});continue}if(b===void 0)return;$(p),de(x,E.scope,1);const R=b;R.job=E,R.worker.ref(),R.ready&&I(R,E)}};return{run:(p,{scope:E,signal:b})=>new Promise(R=>{if(b.aborted){R(Ze);return}if((h.get(E)??0)>=n){R({status:"refused",limit:"scope"});return}k+=1;const S={id:k,input:p,scope:E,settle:R,detach:()=>{}};y.push(S),de(h,E,1),F();const P=y.indexOf(S);if(P<0)return;if(y.length>a){$(P),de(h,E,-1),R({status:"refused",limit:"queue"});return}const L=()=>{const X=y.indexOf(S);X<0||($(X),de(h,E,-1),R(Ze))};b.addEventListener("abort",L,{once:!0}),S.detach=()=>{b.removeEventListener("abort",L)}}),workers:()=>m.size}},ze=1024*1024,Or=3e4,Rr=4*ze,_r=64*ze,Ar=3,vr=2,Nr=(e,t)=>e+kt(t)+Ar,Pr=4,Ir=32,Mr=512,Lr=64,Dr=4096,$r=32,qe=4096,jr=4,xt=({workerHeapMb:e,maxHtmlBytes:t})=>Math.floor(((e-Lr)*ze-t*$r)/Dr),zr=({maxHtmlBytes:e})=>e,Cr=({maxHtmlBytes:e})=>jr*e,Hr=1024,Br=2147483647,Fr=64,Ur=2**29,Xr=1024*1024,Gr=64,et=Object.freeze({status:"rejected",reason:"too-large",cause:null}),Ie=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},Jr=(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:i,workerHeapMb:c,jobsPerScope:m,maxQueuedJobs:y}=e??{},x=le("workers",r,vr,Fr),h=le("jobsPerScope",m,Nr(t,x),Number.MAX_SAFE_INTEGER),g=Object.freeze({workers:x,deadlineMs:le("deadlineMs",n,Or,Br),maxHtmlBytes:le("maxHtmlBytes",a,Rr,Ur),cacheBytes:le("cacheBytes",i,_r,Number.MAX_SAFE_INTEGER),workerHeapMb:le("workerHeapMb",c,Mr,Xr),jobsPerScope:h,maxQueuedJobs:le("maxQueuedJobs",y,Pr*h,Number.MAX_SAFE_INTEGER)});if(g.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(g.jobsPerScope)}`);if(g.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(g.maxQueuedJobs)}`);if(xt(g)<qe)throw new RangeError(`[markdown-explorer] sanitizer.workerHeapMb (${String(g.workerHeapMb)} MiB) must leave room for ${String(qe)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(g.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`);return g},Yr=()=>{const e=typeof document>"u"?require("url").pathToFileURL(__filename).href:Ae&&Ae.tagName.toUpperCase()==="SCRIPT"&&Ae.src||new URL("server.cjs",document.baseURI).href,t=new URL(`./sanitizeWorker${ne.extname(_e.fileURLToPath(e))}`,e);if(!ie.existsSync(_e.fileURLToPath(t)))throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${_e.fileURLToPath(t)}`);return t},tt=new Map,Wr=(e,t)=>{const r=[e.href,t.workers,t.deadlineMs,t.workerHeapMb,t.jobsPerScope,t.maxQueuedJobs].map(String).join("\0");let n=tt.get(r);return n===void 0&&(n=xr({url:e,size:t.workers,deadlineMs:t.deadlineMs,jobsPerScope:t.jobsPerScope,maxQueuedJobs:t.maxQueuedJobs,heapLimits:{maxOldGenerationSizeMb:t.workerHeapMb,maxYoungGenerationSizeMb:Ir}}),tt.set(r,n)),n},Kr=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"},Vr=e=>e instanceof Error&&e.code==="ERR_WORKER_OUT_OF_MEMORY",Qr=({iframeHosts:e,dataPath:t,options:r,pool:n})=>{const a=Object.freeze([...e]),i=xt(r),c=zr(r),m=Cr(r),y=St(Hr,{max:r.cacheBytes,of:(N,_)=>2*N.length+(_.status==="sanitized"?2*_.html.length:Gr)}),x=new Map,h=new Map,g=N=>{x.get(N.key)===N&&x.delete(N.key);const _=h.get(N.hash);_?.delete(N),_?.size===0&&h.delete(N.hash)},k=async(N,_,z)=>{const v=await n.run({html:N,iframeHosts:a,dataPath:t,maxNodes:i,maxAttributeChars:c,maxSanitizedChars:m},{scope:_,signal:z});if(v.status==="refused"){const C=v.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: ${C}`)},lasting:!1}}if(v.status==="aborted")return{outcome:Ie,lasting:!1};if(v.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(v.status==="unavailable")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker could not start",{cause:v.error})},lasting:!1};if(v.status==="crashed"&&Vr(v.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:v.error})},lasting:!0};if(v.status==="crashed")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker failed",{cause:v.error})},lasting:!0};const{output:I}=v;return Kr(I)?I.status==="too-large"?{outcome:et,lasting:!0}:I.status==="error"?{outcome:{status:"rejected",reason:"failed",cause:new Error(`[markdown-explorer] the HTML sanitizer failed: ${I.message}`)},lasting:!0}:I.html.length>m?{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer's output of ${String(I.html.length)} characters exceeds its limit of ${String(m)}`)},lasting:!0}:{outcome:{status:"sanitized",html:I.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,_,z,v)=>{let I=()=>{};const C=new Promise(E=>{I=E}),F={hash:_,key:z,outcome:C,answer:I,controller:new AbortController,waiters:0};x.set(z,F);const p=h.get(_);return p===void 0?h.set(_,new Set([F])):p.add(F),k(N,v,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(g(F),F.answer(E),!b)return;const R=y.get(_),S=R??(E.status==="rejected"?{...E,cause:null}:E);R===void 0&&y.set(_,S);for(const P of h.get(_)??[])g(P),P.answer(S),P.controller.abort()}),F},$=(N,_)=>new Promise(z=>{N.waiters+=1;const v=()=>{N.waiters-=1,z(Ie),!(N.waiters>0)&&(g(N),N.controller.abort())};_.addEventListener("abort",v,{once:!0}),N.outcome.then(I=>{_.removeEventListener("abort",v),z(I)})});return(N,{scope:_,signal:z})=>{if(N.length>r.maxHtmlBytes||Buffer.byteLength(N,"utf8")>r.maxHtmlBytes)return Promise.resolve(et);const v=wt.createHash("sha256").update(N,"utf8").digest("base64"),I=y.get(v);if(I!==void 0)return Promise.resolve(I);if(z.aborted)return Promise.resolve(Ie);const C=`${v}\0${_}`,F=x.get(C);return $(F===void 0?A(N,v,C,_):F,z)}},xe=e=>({result:e,json:JSON.stringify(e)}),Me=Object.freeze(xe(Object.freeze({status:"error",failure:Object.freeze({reason:"failed"})}))),Zr=e=>e.status==="ok"&&e.entries.length>0,qr=({ttlMs:e,maxEntries:t,maxBytes:r,now:n})=>{const a=St(t,{max:r,of:(h,g)=>2*g.tree.json.length}),i=new Map,c=new Map,m=(h,g)=>{const k=new AbortController,A={waiters:0,superseded:!1,started:!1,loadTree:g},$=c.get(h),N=(C,F)=>{const p=xe(C);return!(A.superseded||k.signal.aborted)&&Zr(C)&&a.set(h,{tree:p,loadedAt:F}),p},z=(async()=>{if($!==void 0&&await $,k.signal.aborted)return Me;const C=n();return A.started=!0,N(await A.loadTree(k.signal,C),C)})().finally(()=>{i.get(h)===v&&i.delete(h)}),v={promise:z,controller:k,state:A};i.set(h,v);const I=z.then(()=>{},()=>{});return c.set(h,I),I.then(()=>{c.get(h)===I&&c.delete(h)}),v},y=(h,g,k)=>{g.state.waiters+=1;const A=()=>{g.state.waiters-=1,!(g.state.waiters>0)&&(i.get(h)===g&&i.delete(h),g.controller.abort())};return k.addEventListener("abort",A,{once:!0}),g.promise.finally(()=>{k.removeEventListener("abort",A)})},x=h=>{a.delete(h);const g=i.get(h);g?.state.started&&(g.state.superseded=!0,i.delete(h))};return{load:(h,g,k)=>{if(g.aborted)return Promise.resolve(Me);const A=a.get(h);if(A!==void 0){if(n()-A.loadedAt<e)return Promise.resolve(A.tree);a.delete(h)}const $=i.get(h);return y(h,$===void 0?m(h,k):$,g)},refresh:(h,g,k)=>{if(g.aborted)return Promise.resolve(Me);x(h);const A=i.get(h);return A===void 0?y(h,m(h,k),g):(A.state.loadTree=k,y(h,A,g))},forget:x}},en=e=>({load:(t,r,n)=>n(r,e()).then(xe),refresh:(t,r,n)=>n(r,e()).then(xe),forget:()=>{}}),O=e=>{throw new TypeError(`[markdown-explorer] ${e}`)},tn=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)"}},rn=(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 i of e){if(typeof i!="string"||!w.isAcceptableDocumentPath(i))throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");if(r.deniesPath(i))throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");if(!n(i))throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");if(i===t)throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");if(a.has(i))throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");a.add(i)}return Object.freeze([...a])},nn=(e,t,r,n,a)=>{const i=new Set,c=y=>{if(!Array.isArray(y))return O("a source returned entries that are not an array");const x=[];for(const h of y){const g=m(h);g!==null&&x.push(g)}return x},m=y=>{const x=tn(y);if(x!==null)return n(x),null;const h=w.entryViolation(y);if(h!==null)return O(h);const g=y;if(i.has(g))return O("a source returned entries that contain themselves");const{name:k,path:A,type:$,mimeType:N,modifiedAt:_,children:z,lazy:v}=g;if(t.deniesName(k)||t.deniesPath(A))return null;if(!a(A))return n({path:A,reason:"a path outside the source's boundary"}),null;const I={name:k,path:A,...N===void 0?{}:{mimeType:N},..._===void 0?{}:{modifiedAt:_}};if($==="file")return{...I,type:$};if(v===!0)return r?{...I,type:$,lazy:!0,children:[]}:O("a lazy directory came from a source without a children function");if(z===void 0)return{...I,type:$};i.add(g);const C=c(z);return i.delete(g),{...I,type:$,children:C}};return c(e)},on=/^[\x21\x23-\x7E]{1,256}$/u,Ot=e=>typeof e=="string"&&on.test(e),sn=new Set(["text","image","media","file"]),an=e=>typeof e=="string"&&sn.has(e),cn=(e,t,r)=>{if(e!==null&&typeof e=="object"){const i=e,{kind:c}=i;if(an(c)){if(Object.hasOwn(i,"url"))return O(`a ${c} document carries its version, not a url`);if(typeof i.name!="string")return O("a document needs a name string");if(!Ot(i.version))return O(`a ${c} document needs a version of 1 to 256 visible ASCII characters other than '"'`);const m=t(i.version);switch(c){case"image":case"file":return{kind:c,name:i.name,url:m};case"media":{const{mediaType:y}=i;return w.isExplorerMediaType(y)?{kind:c,name:i.name,url:m,mediaType:y}:O(`unknown media type ${typeof y=="string"?JSON.stringify(y.slice(0,64)):typeof y}`)}case"text":return typeof i.text!="string"||typeof i.truncated!="boolean"?O("a text document needs text and truncated"):{kind:c,name:i.name,text:i.text,truncated:i.truncated,url:m}}}}const n=w.documentViolation(e);if(n!==null)return O(n);const a=e;switch(a.kind){case"failure":{const{reason:i,code:c}=a.failure;return{kind:"failure",failure:w.failureOf(i,c)}}case"markdown":return a.headings.length>w.EXPLORER_MAX_HEADINGS?{kind:"failure",failure:w.failureOf("too-large")}:(a.edit?.kind==="inline"||a.edit?.kind==="draft")&&!r?O(`a markdown document offers ${a.edit.kind} editing, but the server has no edit ports`):{kind:"unsanitized-markdown",name:a.name,html:a.htmlContent,headings:a.headings.map(({text:i,depth:c,id:m})=>({text:i,depth:c,id:m})),edit:un(a.edit)}}},un=e=>{if(e===null)return null;switch(e.kind){case"inline":return{kind:"inline"};case"draft":return{kind:"draft"};case"external":return{kind:"external",href:e.href}}},Oe=(e,t,r)=>typeof e!="string"?O(`${r} needs a text string`):e.includes("\0")?O(`${r} holds NUL, which no text editor can keep`):new TextEncoder().encode(e).byteLength>t?O(`${r} is over editMaxBytes (${t} bytes); refuse a longer source with ExplorerError "too-large"`):e,Rt=e=>w.isRootRelativeUrl(e.href)?{kind:"grant",href:e.href}:O("a grant needs a root-relative href"),dn=(e,t)=>{if(e===null||typeof e!="object")return O("an edit source must be an object");const r=e;return r.kind==="grant"?Rt(r):r.kind==="draft"?{kind:"draft",text:Oe(r.text,t,"a draft source")}:r.kind!=="edit"?O(`an edit source's kind must be "edit", "draft" or "grant"`):w.isExplorerEditToken(r.version)?typeof r.history!="boolean"?O("an edit source needs history"):{kind:"edit",text:Oe(r.text,t,"an edit source"),version:r.version,history:r.history}:O("an edit source needs a version of 1 to 1024 characters")},ln=(e,t)=>{if(e===null||typeof e!="object")return O("a save result must be an object");const r=e;switch(r.kind){case"grant":return Rt(r);case"saved":return w.isExplorerEditToken(r.version)?{kind:"saved",version:r.version}:O("a saved result needs a version of 1 to 1024 characters");case"conflict":return w.isExplorerEditToken(r.version)?{kind:"conflict",version:r.version,text:Oe(r.text,t,"a conflict's current text")}:O("a conflict needs the current version of 1 to 1024 characters");default:return O(`a save result's kind must be "saved", "conflict" or "grant"`)}},fn=e=>{if(e===null||typeof e!="object")return O("a preview must be an object");const{htmlContent:t,headings:r}=e;if(typeof t!="string"||!Array.isArray(r))return O("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 O(a)}return{html:t,headings:r.map(({text:n,depth:a,id:i})=>({text:n,depth:a,id:i}))}},mn=e=>{if(!Array.isArray(e))return O("revisions must be an array");const t=new Set;return e.map(r=>{const n=w.revisionViolation(r);if(n!==null)return O(n);const{id:a,modifiedAt:i,size:c,author:m,kept:y,current:x}=r;return t.has(a)?O(`two revisions share the id ${JSON.stringify(a.slice(0,64))}`):(t.add(a),{id:a,modifiedAt:i,size:c,author:m,kept:y,current:x})})},pn=(e,t)=>Oe(e,t,"a revision"),rt=e=>{if(e===null||typeof e!="object")return O("an asset file must be an object");const{name:t,contentType:r,size:n,version:a,open:i}=e;return typeof t!="string"||t===""?O("an asset file needs a non-empty name"):typeof r!="string"?O("an asset file needs a contentType string ('' when unknown)"):n!==null&&!(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)?O("an asset file's size must be null or a non-negative safe integer"):Ot(a)?typeof i!="function"?O("an asset file needs an open function"):Object.freeze({name:t,contentType:r,size:n,version:a,open:i}):O(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`)},hn=e=>Array.isArray(e)?e.map(t=>{if(t===null||typeof t!="object")return O("a notice must be an object");const{id:r,tone:n,title:a,body:i,action:c}=t;if(typeof r!="string"||r===""||typeof a!="string")return O("a notice needs an id and a title");if(!w.isExplorerNoticeTone(n))return O(`unknown notice tone ${typeof n=="string"?JSON.stringify(n.slice(0,64)):typeof n}`);if(i!==void 0&&typeof i!="string")return O("a notice body must be a string");const y={id:r,tone:n,title:a,...i===void 0?{}:{body:i}};if(c===void 0)return y;if(c===null||typeof c!="object")return O("a notice action must be an object");const{label:x,href:h}=c;return typeof x!="string"||!w.isAcceptableUrl(h,w.EXPLORER_LINK_PROTOCOLS)?O("a notice action needs a label and an http(s), mailto or relative href"):{...y,action:{label:x,href:h}}}):O("notices must be an array"),wn=4e3,be=Object.freeze({ttlMs:3e5,maxEntries:64,maxBytes:64*1024*1024}),nt=32,_t="private, no-store",yn=Object.freeze({"Content-Type":"application/json; charset=utf-8","Cache-Control":_t,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; frame-ancestors 'none'; sandbox","Cross-Origin-Resource-Policy":"same-origin"}),gn=22,En=2147483647,Le=Object.freeze([]),bn=Object.freeze({status:"ok",source:null,ancestors:null}),ot=Object.freeze(["contains","confirm"]),st=Object.freeze({readOnly:!1}),Tn=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}`)},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},Sn=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)},it=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)")}},at=e=>e instanceof Response?new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`):e,kn=e=>{if(typeof e!="string")throw new TypeError(`[markdown-explorer] scopeSecret must be a string; got ${typeof e}`);if(e.length<nt)throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(nt)} characters; got ${String(e.length)}`);return e},xn=(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(!ot.includes(r))throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${ot.join(", ")}`);V(`${e}.boundary.contains`,t.contains,!1),V(`${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:i,label:c,boundary:m,tree:y,children:x,ancestors:h,cacheScope:g}=a;if(!se.isExplorerSourceId(i))throw new RangeError(`[markdown-explorer] sources[${String(n)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${typeof i=="string"?JSON.stringify(i):typeof i}`);const k=`source ${JSON.stringify(i)}`;if(r.has(i))throw new RangeError(`[markdown-explorer] source ids must be unique; ${JSON.stringify(i)} repeats at sources[${String(n)}]`);if(r.add(i),typeof c!="string"&&typeof c!="function")throw new TypeError(`[markdown-explorer] ${k}.label must be a string or a function`);if(typeof c=="string"&&c.trim()==="")throw new RangeError(`[markdown-explorer] ${k}.label must not be blank`);if(xn(k,m),V(`${k}.tree`,y,!1),V(`${k}.children`,x,!0),V(`${k}.ancestors`,h,!0),g!==void 0&&g!=="principal"&&g!=="shared")throw new RangeError(`[markdown-explorer] ${k}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(g)}`)}return t},Rn=e=>{if(e===!1)return!1;if(e===void 0)return be;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?be.ttlMs:pe("treeCache.ttlMs",t,Number.MAX_SAFE_INTEGER),maxEntries:r===void 0?be.maxEntries:pe("treeCache.maxEntries",r,Number.MAX_SAFE_INTEGER),maxBytes:n===void 0?be.maxBytes:pe("treeCache.maxBytes",n,Number.MAX_SAFE_INTEGER)}},ct=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},ut=(e,t)=>{if(!(t instanceof Response))throw new TypeError(`[markdown-explorer] ${e} must return a Response`);return t},dt=(e,t)=>{if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");return wt.createHmac("sha256",e).update(t,"utf8").digest("base64url").slice(0,gn)},_n=e=>e.view==="multi"?e.docs:e.doc===null?[]:[e.doc],ue=(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[i,c]of Object.entries({...yn,...n}))a.set(i,c);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),An=new Set(["refresh","save","preview"]),vn=new Set(["edit","save","preview","revisions","revision"]),lt=(e,t)=>{const r=An.has(t)?["POST"]:["GET","HEAD"];return r.includes(e.method.toUpperCase())?null:K(405,JSON.stringify({failure:{reason:"invalid"}}),void 0,{Allow:r.join(", ")})},ft=e=>e.headers.get(w.EXPLORER_PROOF_HEADER)===w.EXPLORER_REFRESH_PROOF&&ke.crossOriginRefusal(e,ke.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Nn=e=>e.headers.get(w.EXPLORER_PROOF_HEADER)===w.EXPLORER_EDIT_PROOF&&ke.crossOriginRefusal(e,ke.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Pn=async(e,t)=>{const[r,...n]=(e.headers.get("Content-Type")??"").split(";").map(k=>k.trim().toLowerCase()),a=n.find(k=>k.startsWith("charset="));if(r!==w.EXPLORER_DRAFT_MEDIA_TYPE||a!==void 0&&a!=="charset=utf-8")return{status:"error",failure:{reason:"invalid"}};const i=Number(e.headers.get("Content-Length")??"0");if(Number.isFinite(i)&&i>t)return{status:"error",failure:{reason:"too-large"}};if(e.body===null)return{status:"ok",text:""};const c=e.body.getReader(),m=[];let y=0;for(;;){const{done:k,value:A}=await c.read();if(k)break;if(y+=A.byteLength,y>t)return await c.cancel(),{status:"error",failure:{reason:"too-large"}};m.push(A)}const x=new Uint8Array(y);let h=0;for(const k of m)x.set(k,h),h+=k.byteLength;let g;try{g=new TextDecoder("utf-8",{fatal:!0}).decode(x)}catch{return{status:"error",failure:{reason:"invalid"}}}return g.includes("\0")?{status:"error",failure:{reason:"invalid"}}:{status:"ok",text:g}},In=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},Mn=({parentHeaders:e,loaderHeaders:t,errorHeaders:r})=>{const n=new Headers,a=r===void 0?[e,t]:[e,t,r];for(const i of a)for(const[c,m]of i)c!=="set-cookie"&&n.set(c,m);return n},Ln=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the server configuration must be an object");const t=Sn(e.config),r=kn(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=On(e.sources),a=se.withExplorerSources(t,n.map(o=>o.id)),i=e.logger;if(i!==void 0&&(i===null||typeof i!="object"||typeof i.error!="function"))throw new TypeError("[markdown-explorer] logger must be an object with an error function");const c=e.logger===void 0?hr:e.logger,m=w.resolvePathRules(e.deny),y=e.deferredTimeoutMs===void 0?wn:pe("deferredTimeoutMs",e.deferredTimeoutMs,En),x=e.textMaxBytes===void 0?Ke:pe("textMaxBytes",e.textMaxBytes,Ve),h=In(e.edit);if(h===void 0&&e.editMaxBytes!==void 0)throw new TypeError("[markdown-explorer] editMaxBytes needs the edit ports");const g=e.editMaxBytes===void 0?Ke:pe("editMaxBytes",e.editMaxBytes,Ve),k=Rn(e.treeCache),A=()=>Date.now(),$=k===!1?en(A):qr({...k,now:A}),N=Jr(e.sanitizer,t.multiView.maxPanels),_=Qr({iframeHosts:t.iframeHosts,dataPath:t.dataPath,options:N,pool:Wr(Yr(),N)}),z=new Map(n.map(o=>[o.id,o])),v=se.documentStyleNames(t),{authenticate:I,principalKey:C,signedOutPage:F,forbiddenPage:p,onTreeRefreshed:E}=e,b=(o,u)=>{if(typeof o.label=="string")return o.label;const s=o.label(u);if(typeof s!="string"||s.trim()==="")throw new TypeError(`[markdown-explorer] the label of source ${JSON.stringify(o.id)} must be a non-blank string`);return s},R=(o,u)=>o.cacheScope==="shared"?o.id:`${o.id}\0${u}`,S=(o,u)=>{const s=l=>oe(c,{operation:"boundary",sourceId:o.id,path:u,error:l});let d;try{d=o.boundary.contains(u)}catch(l){return s(l),!1}return typeof d=="boolean"?d:(We(d,s),s(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(o.id)} must return a boolean; got ${typeof d}`)),!1)},P=async(o,u,s)=>{const{confirm:d}=o.boundary;if(d===void 0)return{status:"inside",readPath:s};let l;try{l=await d(u,s)}catch(U){return{status:"error",failure:Y(U,{operation:"boundary",sourceId:o.id,path:s},u.signal,c)}}const f=U=>(oe(c,{operation:"boundary",sourceId:o.id,path:s,error:new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} ${U}`)}),{status:"outside"});if(l===null||typeof l!="object")return f(`must resolve to { inside, readPath? }; got ${l===null?"null":typeof l}`);const{inside:T,readPath:M}=l;return T===!1?{status:"outside"}:T!==!0||typeof M!="string"?f("must resolve to { inside: false } or { inside: true, readPath: string }"):!w.isAcceptableDocumentPath(M)||m.deniesPath(M)?(oe(c,{operation:"boundary",sourceId:o.id,path:s,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:M}},L=async(o,u)=>{const s=n.filter(l=>S(l,u));if(s.length===0)return{status:"error",failure:{reason:"forbidden"}};if(s.some(l=>l.boundary.confirm===void 0))return{status:"inside",readPath:u};let d=null;for(const l of s){const f=await P(l,o,u);if(f.status==="inside")return f;f.status==="error"&&d===null&&(d=f.failure)}return{status:"error",failure:d===null?{reason:"forbidden"}:d}},X=(o,u,s)=>{const d=({path:l,reason:f})=>gr(c,{operation:s.operation,sourceId:s.sourceId,path:l,error:new TypeError(`[markdown-explorer] an entry with ${f} was left out`)});try{return{status:"ok",entries:nn(o,m,u.children!==void 0,d,l=>S(u,l))}}catch(l){return oe(c,{...s,error:l}),{status:"error",failure:{reason:"failed"}}}},D=async(o,u,s)=>{let d;try{d=await o.tree(u)}catch(f){return{status:"error",failure:Y(f,{operation:"tree",sourceId:o.id},u.signal,c)}}const l=X(d,o,{operation:"tree",sourceId:o.id});return l.status==="ok"?{status:"ok",entries:l.entries,loadedAt:s}:l},G=(o,u,s,d)=>(l,f)=>D(o,{principal:u,request:s,signal:l,refresh:d},f),Q=(o,u,s,d,l)=>$.load(R(o,s),l,G(o,u,d,!1)),J=(o,u,s,d)=>$.refresh(R(o,s),d.signal,G(o,u,d,!0)),ae=(o,u)=>{if(E===void 0)return;const s=d=>oe(c,{operation:"refresh",sourceId:o.id,error:d});try{We(E(u),s)}catch(d){s(d)}},H=async(o,u,s,d)=>{if(m.deniesPath(d)||!S(o,d))return{status:"error",failure:{reason:"forbidden"}};const l=await P(o,s,d);if(l.status==="outside")return{status:"error",failure:{reason:"forbidden"}};if(l.status==="error")return{status:"error",failure:l.failure};let f;try{f=await u(s,d,l.readPath)}catch(T){return{status:"error",failure:Y(T,{operation:"children",sourceId:o.id,path:d},s.signal,c)}}return X(f,o,{operation:"children",sourceId:o.id,path:d})},Z=async(o,u,s,d)=>{const l=await P(o,s,d);if(l.status==="outside")return{status:"ok",ancestors:null};if(l.status==="error")return{status:"error",failure:l.failure};let f;try{f=await u(s,d,l.readPath,{maxDepth:t.revealDocument.maxDepth})}catch(T){return{status:"error",failure:Y(T,{operation:"ancestors",sourceId:o.id,path:d},s.signal,c)}}if(Array.isArray(f)&&f.length>t.revealDocument.maxDepth)return{status:"ok",ancestors:null};try{return{status:"ok",ancestors:rn(f,d,m,T=>S(o,T))}}catch(T){return oe(c,{operation:"ancestors",sourceId:o.id,path:d,error:T}),{status:"error",failure:{reason:"failed"}}}},q=async(o,u,s,d)=>m.deniesPath(d)?{status:"error",failure:{reason:"forbidden"}}:S(o,d)?Z(o,u,s,d):{status:"ok",ancestors:null},ee=async(o,u,s)=>{if(m.deniesPath(s))return{status:"error",failure:{reason:"forbidden"}};for(const d of[o,...n.filter(l=>l!==o)]){if(u.signal.aborted)break;const l=d.ancestors;if(l===void 0||!S(d,s))continue;const f=await Z(d,l,u,s);if(f.status==="ok"&&f.ancestors!==null)return{status:"ok",source:d.id,ancestors:f.ancestors}}return bn},ce=async(o,u,s)=>{if(m.deniesPath(s))return w.failureDocument("forbidden");const d=await L(o,s);if(d.status==="error")return{kind:"failure",failure:d.failure};let l;try{l=await e.document(o,s,d.readPath)}catch(M){return{kind:"failure",failure:Y(M,{operation:"document",path:s},o.signal,c)}}let f;try{f=cn(l,M=>w.explorerAssetHref(t.dataPath,s,M),h!==void 0)}catch(M){return oe(c,{operation:"document",path:s,error:M}),w.failureDocument("failed")}if(f.kind!=="unsanitized-markdown")return f;const T=await _(f.html,{scope:u,signal:o.signal});return T.status==="sanitized"?{kind:"markdown",name:f.name,htmlContent:T.html,headings:f.headings,edit:f.edit}:(T.cause!==null&&oe(c,{operation:"document",path:s,error:T.cause}),w.failureDocument(T.reason))},ge=async o=>{if(e.notices===void 0)return Le;try{return hn(await e.notices(o))}catch(u){return Y(u,{operation:"notices"},o.signal,c),Le}},Lt=async(o,u,s)=>{const d=ue(u,w.EXPLORER_DATA_QUERY.path);if(d===null||!w.isAcceptableDocumentPath(d))return j({reason:"invalid"},s);const l=w.readExplorerAssetDisplay(u);if(l===null)return j({reason:"invalid"},s);if(m.deniesPath(d))return Pe(c,{operation:"asset",path:d}),j({reason:"forbidden"},s);const f=await L(o,d);if(f.status==="error")return j(f.failure,s);try{const T=rt(await e.asset(o,d,f.readPath));return await pr(o.request,T,s,l)}catch(T){return j(Y(T,{operation:"asset",path:d},o.signal,c),s)}},Dt=async(o,u)=>{if(m.deniesPath(u))return Pe(c,{operation:"text",path:u}),w.failureDocument("forbidden");const s=await L(o,u);if(s.status==="error")return{kind:"failure",failure:s.failure};try{const d=rt(await e.asset(o,u,s.readPath)),l=await br(d,x);return l===null?w.failureDocument("unsupported"):{kind:"text",name:d.name,text:l.text,truncated:l.truncated,url:w.explorerAssetHref(t.dataPath,u,d.version)}}catch(d){return{kind:"failure",failure:Y(d,{operation:"text",path:u},o.signal,c)}}},he=async(o,u,s)=>m.deniesPath(s)?(Pe(c,{operation:u,path:s}),{status:"error",failure:{reason:"forbidden"}}):L(o,s),$t=async(o,u,s)=>{const d=await he(u,"edit",s);if(d.status==="error")return{kind:"failure",failure:d.failure};try{return dn(await o.source(u,s,d.readPath),g)}catch(l){return{kind:"failure",failure:Y(l,{operation:"edit",path:s},u.signal,c)}}},jt=async(o,u,s,d,l)=>{const f=await he(u,"save",s);if(f.status==="error")return{kind:"failure",failure:f.failure};try{return ln(await o.save(u,s,f.readPath,{text:l,baseVersion:d}),g)}catch(T){return{kind:"failure",failure:Y(T,{operation:"save",path:s},u.signal,c)}}},zt=async(o,u,s,d,l)=>{const f=await he(u,"preview",d);if(f.status==="error")return{kind:"failure",failure:f.failure};let T;try{T=fn(await o.preview(u,d,f.readPath,l))}catch(U){return{kind:"failure",failure:Y(U,{operation:"preview",path:d},u.signal,c)}}if("kind"in T)return T.kind==="failure"?T:w.failureDocument("failed");const M=await _(T.html,{scope:s,signal:u.signal});return M.status==="sanitized"?{kind:"preview",htmlContent:M.html,headings:T.headings}:(M.cause!==null&&oe(c,{operation:"preview",path:d,error:M.cause}),w.failureDocument(M.reason))},Ct=async(o,u,s)=>{const d=await he(u,"revisions",s);if(d.status==="error")return{kind:"failure",failure:d.failure};try{return{kind:"revisions",revisions:mn(await o.revisions(u,s,d.readPath))}}catch(l){return{kind:"failure",failure:Y(l,{operation:"revisions",path:s},u.signal,c)}}},Ht=async(o,u,s,d)=>{const l=await he(u,"revision",s);if(l.status==="error")return{kind:"failure",failure:l.failure};try{return{kind:"revision",id:d,text:pn(await o.revision(u,s,l.readPath,d),g)}}catch(f){return{kind:"failure",failure:Y(f,{operation:"revision",path:s},u.signal,c)}}},Bt=async(o,u,s,d,l,f)=>{const T=ue(l,w.EXPLORER_DATA_QUERY.path);if(T===null||!w.isAcceptableDocumentPath(T))return j({reason:"invalid"},f);if(u==="edit")return K(200,JSON.stringify(await $t(o,s,T)),f);if(u==="revisions")return K(200,JSON.stringify(await Ct(o,s,T)),f);if(u==="revision"){const te=ue(l,w.EXPLORER_DATA_QUERY.revision);return w.isExplorerEditToken(te)?K(200,JSON.stringify(await Ht(o,s,T,te)),f):j({reason:"invalid"},f)}const M=ue(l,w.EXPLORER_DATA_QUERY.base);if(u==="save"&&!w.isExplorerEditToken(M))return j({reason:"invalid"},f);const U=await Pn(s.request,g);return U.status==="error"?j(U.failure,f):u==="preview"?K(200,JSON.stringify(await zt(o,s,d,T,U.text)),f):K(200,JSON.stringify(await jt(o,s,T,M,U.text)),f)},Ft=async({request:o,url:u,params:s})=>{const d=ct(await I(o,st)),l=it(d.headers);if(l.set("Cache-Control",_t),d.status==="signed-out")throw ut("signedOutPage",F(o,l));if(d.status==="forbidden")throw p===void 0?Re.data(null,{status:403,headers:l}):ut("forbiddenPage",p(o,l));const f=se.resolveExplorerLocation(a,s["*"],u.searchParams);if(f.kind==="redirect")throw Re.redirect(f.href,{headers:l});const{location:T}=f,{principal:M}=d,U=dt(r,C(M)),te=z.get(T.source);if(te===void 0)throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(T.source)}`);const we={signal:o.signal,timeoutMs:y,late:null,handOverMs:y},re={scope:U,sources:n.map(B=>({id:B.id,label:b(B,M)})),settings:se.parseViewSettings(se.readCookieValue(o.headers.get("Cookie"),t.settingsCookie),v),tree:T.view==="single"?null:{sourceId:T.source,result:Ne(we,B=>Q(te,M,U,o,B).then(W=>W.result))},documents:_n(T).map(B=>({path:B,document:Ne(we,W=>ce({principal:M,request:o,signal:W,refresh:!1},U,B))})),notices:Ne({signal:o.signal,timeoutMs:y,late:Le,handOverMs:0},B=>ge({principal:M,request:o,signal:B,refresh:!1}))};return Re.data(re,{headers:l})},Ce=async(o,u)=>{const s=ct(await I(o,u));return{authentication:s,headers:it(s.headers)}},Ut=async(o,u,s)=>{let d;try{d=await Ce(u,st)}catch(W){return j(Y(at(W),{operation:"authenticate"},u.signal,c))}const{authentication:l,headers:f}=d;if(l.status==="signed-out")return j({reason:"unauthorized"},f);if(l.status==="forbidden")return j({reason:"forbidden"},f);const{principal:T}=l;if(o==="asset")return Lt({principal:T,request:u,signal:u.signal,refresh:!1},s,f);const M=dt(r,C(T));f.set(w.EXPLORER_SCOPE_HEADER,M);const U={principal:T,request:u,signal:u.signal,refresh:!1},te=()=>j({reason:"invalid"},f);if(o==="document"){const W=ue(s,w.EXPLORER_DATA_QUERY.path);if(W===null||!w.isAcceptableDocumentPath(W))return te();const Fe=u.headers.has(w.EXPLORER_PROOF_HEADER);return Fe&&!ft(u)?j({reason:"forbidden"},f):K(200,JSON.stringify(await ce({...U,refresh:Fe},M,W)),f)}if(o==="text"){const W=ue(s,w.EXPLORER_DATA_QUERY.path);return W===null||!w.isAcceptableDocumentPath(W)?te():K(200,JSON.stringify(await Dt(U,W)),f)}if(o==="edit"||o==="save"||o==="preview"||o==="revisions"||o==="revision")return h===void 0?j({reason:"not-found"},f):Bt(h,o,U,M,s,f);const we=ue(s,w.EXPLORER_DATA_QUERY.source),re=ue(s,w.EXPLORER_DATA_QUERY.path);if(we===null||(o==="children"||o==="ancestors"||o==="reveal")&&(re===null||!w.isAcceptableDocumentPath(re)))return te();const B=z.get(we);if(B===void 0)return j({reason:"not-found"},f);if(o==="tree")return K(200,(await Q(B,T,M,u,u.signal)).json,f);if(o==="refresh"){const W=await J(B,T,M,u);return u.signal.aborted||ae(B,R(B,M)),K(200,W.json,f)}return o==="ancestors"?B.ancestors===void 0||re===null?j({reason:"not-found"},f):K(200,JSON.stringify(await q(B,B.ancestors,U,re)),f):o==="reveal"?re===null?te():K(200,JSON.stringify(await ee(B,U,re)),f):B.children===void 0||re===null?j({reason:"not-found"},f):K(200,JSON.stringify(await H(B,B.children,U,re)),f)},Xt=async o=>{const{authentication:u,headers:s}=await Ce(o,Tn);if(!s.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 u.status==="signed-in"},He=t.embeds.linkCardEndpoint===null?null:Jt.createLinkCardHandler({authorize:Xt}),Gt=async(o,u)=>{try{return await o(u)}catch(s){return j(Y(at(s),{operation:"authenticate"},u.signal,c))}},Be=async(o,u,s)=>{if(new URL(o.url).pathname.endsWith(".data"))return j({reason:"not-found"});if(!w.isExplorerDataOperation(s))return j({reason:"not-found"});if(s==="link-card"){if(He===null)return j({reason:"not-found"});const l=lt(o,s);return l!==null?l:Gt(He,o)}if(vn.has(s)&&h===void 0)return j({reason:"not-found"});const d=lt(o,s);if(d!==null)return d;if(s==="refresh"&&!ft(o))return j({reason:"forbidden"});if((s==="save"||s==="preview")&&!Nn(o))return j({reason:"forbidden"});try{return await Ut(s,o,u.searchParams)}catch(l){return j(Y(l,{operation:s},o.signal,c))}};return Object.freeze({loader:Ft,headers:Mn,dataLoader:({request:o,url:u,params:s})=>Be(o,u,s["*"]),dataAction:({request:o,url:u,params:s})=>Be(o,u,s["*"]),forgetTree:o=>{if(typeof o!="string")throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof o}`);$.forget(o)}})},Te=Object.freeze({maxEntries:2e4,maxDocumentBytes:2*1024*1024,textPreviewBytes:8*1024,walkConcurrency:8}),Dn=new Set(["md","markdown","mdx"]),At=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"}]]),$n=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"]),jn=new Set(["readme","license","licence","copying","notice","authors","contributors","changelog","changes","todo","makefile","dockerfile","containerfile","procfile","gemfile","rakefile","vagrantfile","jenkinsfile","brewfile","codeowners"]),vt=typeof ie.constants.O_NOFOLLOW=="number"?ie.constants.O_NOFOLLOW:0,Nt=typeof ie.constants.O_NONBLOCK=="number"?ie.constants.O_NONBLOCK:0,mt=e=>`${e.size}-${e.mtimeNs}`,zn=e=>e!==""&&e!=="."&&e!==".."&&!e.includes(":")&&!e.endsWith(".")&&!e.endsWith(" "),pt=e=>w.isAcceptableDocumentPath(e)&&e===e.normalize("NFC")&&e.split("/").every(zn),Pt=e=>{const t=e.toLowerCase(),r=t.lastIndexOf(".");return r<0?"":t.slice(r+1)},Cn=e=>{const t=Pt(e);if(Dn.has(t))return{kind:"markdown"};const r=At.get(t);if(r!==void 0)return r.kind==="image"?{kind:"image"}:{kind:"media",mediaType:r.mediaType};const n=e.toLowerCase();return $n.has(t)||!n.includes(".")&&jn.has(n)?{kind:"text"}:{kind:"file"}},$e=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}},It=e=>{const t=$e(e);return t===null?e:new ye(t)},Mt=e=>{const t=typeof e=="object"&&e!==null?e.code:void 0;return t==="EACCES"||t==="EPERM"||t==="ENOENT"||t==="ENOTDIR"},Hn=async e=>{try{return Math.trunc((await me.lstat(e)).mtimeMs)}catch(t){if(Mt(t))return;throw t}},ht=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)},Bn=(e,t)=>e!==null?{start:e.offset,end:e.offset+e.length-1}:t===0n?{}:{start:0,end:Number(t)-1},Fn=async(e,t,r,n)=>{let a;try{a=await me.open(e,ie.constants.O_RDONLY|vt|Nt);const y=await a.stat({bigint:!0});if(!y.isFile()||y.ino!==t.ino||y.dev!==t.dev||y.size!==t.size||y.mtimeNs!==t.mtimeNs)throw new ye("not-found")}catch(y){throw await a?.close(),It(y)}const i=a.createReadStream(Bn(r,t.size)),c=Wt.Readable.toWeb(i),m=()=>{i.destroy(n.reason)};return n.aborted?m():n.addEventListener("abort",m,{once:!0}),c},Un=(e,t)=>{const r=se.NAME_COLLATOR.compare(e,t);return r!==0?r:e===t?0:e<t?-1:1},Xn=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()}}},Gn=(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"},Jn=new Set(["id","label","root","pathPrefix","parse","deny","maxEntries","maxDocumentBytes","textPreviewBytes","walkConcurrency","cacheScope","reportSkipped"]),Se=(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},Yn=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(!Jn.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"||!ne.isAbsolute(n))throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);let i;try{i=ie.statSync(n).isDirectory()}catch(b){throw new RangeError(`[markdown-explorer] root does not exist: ${n}`,{cause:b})}if(!i)throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);const c=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("/")&&pt(m.slice(0,-1))))throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(m)}`);const y=w.resolvePathRules(e.deny),x=Se("maxEntries",e.maxEntries,Te.maxEntries),h=Se("maxDocumentBytes",e.maxDocumentBytes,Te.maxDocumentBytes),g=Se("textPreviewBytes",e.textPreviewBytes,Te.textPreviewBytes),k=Se("walkConcurrency",e.walkConcurrency,Te.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 $=e.reportSkipped;if($!==void 0&&typeof $!="function")throw new TypeError("[markdown-explorer] reportSkipped must be a function");const N=$===void 0?b=>{console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(b.sourceId)} does not list ${JSON.stringify(b.path)}: ${b.reason}`)}:$,_=new Set,z=b=>{const R=ne.resolve(c,...b.split("/")),S=ne.relative(c,R);return S===""||S===".."||S.startsWith(`..${ne.sep}`)||ne.isAbsolute(S)?null:R},v=(b,R)=>{const S=`${R}\0${b}`;_.has(S)||_.size>=x||(_.add(S),N({sourceId:t,path:b,reason:R}))},I=async({signal:b})=>{b.throwIfAborted();const R=new AbortController,S=()=>{R.abort(b.reason)};b.addEventListener("abort",S,{once:!0});const P=Xn(k);let L=0;const X=async(D,G)=>{const Q=await P(async()=>{R.signal.throwIfAborted();try{return await me.readdir(D,{withFileTypes:!0})}catch(H){if(G===""||!Mt(H))throw H;return null}});if(R.signal.throwIfAborted(),Q===null)return v(`${m}${G}`,"unreadable-directory"),null;const J=[];for(const H of Q){if(y.deniesName(H.name))continue;const Z=G===""?H.name:`${G}/${H.name}`,q=`${m}${Z}`,ee=Gn(H,q);if(ee!==null){v(q,ee);continue}J.push({dirent:H,relativePath:Z,path:q})}if(L+=J.length,L>x)throw new ye("too-large");return J.sort((H,Z)=>Un(H.dirent.name,Z.dirent.name)),(await Promise.all(J.map(async({dirent:H,relativePath:Z,path:q})=>{const ee=await Hn(ne.join(D,H.name)),ce=ee===void 0?{}:{modifiedAt:ee};if(!H.isDirectory())return{name:H.name,path:q,type:"file",...ce};const ge=await X(ne.join(D,H.name),Z);return ge===null?null:{name:H.name,path:q,type:"directory",...ce,children:ge}}))).filter(H=>H!==null)};try{const D=await X(c,"");if(D===null)throw new Error("[markdown-explorer] the source's root could not be listed");return D}catch(D){throw R.abort(),D}finally{b.removeEventListener("abort",S)}},C=async b=>{if(!b.startsWith(m))return{status:"refused",reason:"not-found"};const R=b.slice(m.length);if(!pt(R))return{status:"refused",reason:"invalid"};if(y.deniesPath(R))return{status:"refused",reason:"forbidden"};const S=z(R);if(S===null)return{status:"refused",reason:"forbidden"};const P=await me.lstat(S,{bigint:!0});if(P.isSymbolicLink())return{status:"refused",reason:"forbidden"};if(!P.isFile())return{status:"refused",reason:"unsupported"};const L=await me.realpath(S);return L!==S||y.deniesPath(ne.relative(c,L).split(ne.sep).join("/"))?{status:"refused",reason:"forbidden"}:{status:"file",target:S,name:R.slice(R.lastIndexOf("/")+1),stats:P}},F=async(b,R,S)=>{let P;try{const L=await C(S);if(L.status==="refused")return w.failureDocument(L.reason);const{target:X,name:D,stats:G}=L,Q=Cn(D),J=mt(G);if(Q.kind==="image")return{kind:"image",name:D,version:J};if(Q.kind==="media")return{kind:"media",name:D,mediaType:Q.mediaType,version:J};if(Q.kind==="file")return{kind:"file",name:D,version:J};P=await me.open(X,ie.constants.O_RDONLY|vt|Nt);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 ht(P,h+1);if(ee.length>h)return w.failureDocument("too-large");const ce=await a(new TextDecoder("utf-8").decode(ee),R);return{kind:"markdown",name:D,htmlContent:ce.htmlContent,headings:ce.headings,edit:null}}const H=await ht(P,g);if(H.includes(0))return{kind:"file",name:D,version:J};const Z=ae.size>BigInt(g),q=new TextDecoder("utf-8").decode(H,{stream:Z});return{kind:"text",name:D,text:q,truncated:Z,version:J}}catch(L){const X=$e(L);if(X===null)throw L;return w.failureDocument(X)}finally{await P?.close()}},p=async(b,R,S)=>{let P;try{P=await C(S)}catch(J){throw It(J)}if(P.status==="refused")throw new ye(P.reason);const{target:L,name:X,stats:D}=P,G=At.get(Pt(X)),Q=G===void 0?"":G.contentType;return{name:X,contentType:Q,size:Number(D.size),version:mt(D),open:J=>Fn(L,D,J,b.signal)}},E=async(b,R,S)=>{let P;try{P=await C(S)}catch(D){if($e(D)!==null)return null;throw D}if(P.status==="refused")return null;const L=S.slice(m.length).split("/");if(L.some(D=>y.deniesName(D)))return null;const X=L.slice(0,-1);return X.map((D,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:I,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=ye;exports.anonymousAccess=Kt;exports.createFileSystemSource=Yn;exports.createMarkdownExplorer=Ln;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("./dataRoute-BONacTPi.cjs"),wt=require("node:crypto"),Jt=require("@aiquants/markdown/server"),Se=require("@aiquants/request-isolation"),Re=require("react-router"),se=require("./location-D6RE3wAN.cjs"),ie=require("node:fs"),ne=require("node:path"),_e=require("node:url"),Yt=require("node:worker_threads"),me=require("node:fs/promises"),Wt=require("node:stream");var Ae=typeof document<"u"?document.currentScript:null;const Xe=Object.freeze({kind:"anonymous"}),Kt=Object.freeze({authenticate:async()=>({status:"signed-in",principal:Xe}),principalKey:()=>Xe.kind,signedOutPage:(e,t)=>new Response(null,{status:401,headers:t})}),Vt="application/octet-stream",yt="application/pdf",Qt=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",yt]),gt="default-src 'none'; media-src 'self'; style-src 'unsafe-inline'",Et=`${gt}; sandbox`,Zt=`${gt}; sandbox allow-same-origin`,Ge=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,qt=/^[\t\n\r ]+|[\t\n\r ]+$/gu,De=/^[\t ]+|[\t ]+$/gu,er=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 i=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(i,n),n<e.length)continue}if(t.push(r.replace(De,"")),r="",n>=e.length)return t;n+=1}},tr=e=>{const t=e.replace(qt,""),r=t.indexOf("/");if(r<0)return null;const n=t.slice(0,r),i=t.indexOf(";",r+1),a=t.slice(r+1,i<0?t.length:i).replace(/[\t\n\r ]+$/u,"");return Ge.test(n)&&Ge.test(a)?`${n}/${a}`.toLowerCase():null},rr=e=>{let t=null;for(const r of er(e)){const n=tr(r);n!==null&&n!=="*/*"&&(t=n)}return t},nr=/['()*]/gu,bt=e=>encodeURIComponent(e).replace(nr,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),or=Object.freeze({"Cache-Control":"private, max-age=60, stale-while-revalidate=600, no-transform",Vary:"Cookie"}),sr=(e,t)=>{const r=rr(e),n=r!==null&&Qt.has(r),i=n&&(r.startsWith("audio/")||r.startsWith("video/"));return{contentType:r===null?Vt:r,inline:n,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`${n?"inline":"attachment"}; filename*=UTF-8''${bt(t)}`,...r===yt?{}:{"Content-Security-Policy":i?Zt:Et},"Cross-Origin-Resource-Policy":"same-origin"}}},ir="text/plain; charset=utf-8",ar=e=>({contentType:ir,inline:!0,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`inline; filename*=UTF-8''${bt(e)}`,"Content-Security-Policy":Et,"Cross-Origin-Resource-Policy":"same-origin"}}),cr=/^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu,Ee=Object.freeze({kind:"whole"}),Je=Object.freeze({kind:"unsatisfiable"}),ur=(e,t,r)=>{const n=e.get("Range");if(n===null)return Ee;const i=e.get("If-Range");if(i!==null&&i!==r)return Ee;const a=cr.exec(n);if(a===null)return Ee;const[,c,m,y]=a;if(y!==void 0){const g=Number(y);if(g===0)return Je;const S=Math.max(0,t-g);return{kind:"partial",range:{offset:S,length:t-S}}}const x=Number(c),h=m===""?Number.POSITIVE_INFINITY:Number(m);return h<x?Ee:x>=t?Je:{kind:"partial",range:{offset:x,length:Math.min(h,t-1)-x+1}}},Ye="W/",dr=e=>{const t=[];let r=0,n=!1;for(let i=0;i<e.length;i+=1)e[i]==='"'?n=!n:e[i]===","&&!n&&(t.push(e.slice(r,i).replace(De,"")),r=i+1);return t.push(e.slice(r).replace(De,"")),t},We=e=>e.startsWith(Ye)?e.slice(Ye.length):e,lr=(e,t)=>{if(e===null)return!1;const r=dr(e);if(r.length===1&&r[0]==="*")return!0;const n=We(t);return r.some(i=>We(i)===n)},fr=(e,t)=>{let r=t;return e.pipeThrough(new TransformStream({transform:(n,i)=>{const a=n.byteLength>r?n.subarray(0,r):n;r-=a.byteLength,i.enqueue(a),r===0&&i.terminate()},flush:n=>{r>0&&n.error(new RangeError("[markdown-explorer] the asset ended before its declared length"))}}))},ve=async(e,t,r,n,i)=>{if(n!==null&&r.set("Content-Length",String(n)),e.method.toUpperCase()==="HEAD")return new Response(null,{status:t,headers:r});const a=await i();return new Response(n===null?a:fr(a,n),{status:t,headers:r})},mr=(e,t)=>{const r=new Headers(e);for(const[n,i]of Object.entries({"Accept-Ranges":"bytes","Content-Range":`bytes */${t}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff"}))r.set(n,i);return new Response(null,{status:416,headers:r})},pr=async(e,t,r,n)=>{const i=`"${t.version}"`,a=n==="text"?ar(t.name):sr(t.contentType,t.name),c=new Headers(r);for(const[x,h]of Object.entries({...a.headers,...or,ETag:i}))c.set(x,h);if(lr(e.headers.get("If-None-Match"),i))return new Response(null,{status:304,headers:c});if(c.set("Content-Type",a.contentType),t.size===null)return ve(e,200,c,null,()=>t.open(null));if(t.size===0)return c.set("Content-Length","0"),new Response(null,{status:200,headers:c});c.set("Accept-Ranges","bytes");const m=ur(e.headers,t.size,i);if(m.kind==="unsatisfiable")return mr(r,t.size);if(m.kind==="whole")return ve(e,200,c,t.size,()=>t.open(null));const{range:y}=m;return c.set("Content-Range",`bytes ${y.offset}-${y.offset+y.length-1}/${t.size}`),ve(e,206,c,y.length,()=>t.open(y))},hr=Object.freeze({"Cache-Control":"private, no-store","Referrer-Policy":"no-referrer"}),wr=(e,t)=>{const r=new Headers(t);for(const[n,i]of Object.entries(hr))r.set(n,i);return r.set("Location",e),new Response(null,{status:302,headers:r})},Ne=(e,t)=>{const r=new AbortController,n=t(AbortSignal.any([e.signal,r.signal]));return new Promise(i=>{let a;const c=setTimeout(()=>{i(e.late),a=setTimeout(()=>r.abort(),e.handOverMs)},e.timeoutMs),m=()=>{clearTimeout(c),clearTimeout(a)};n.then(y=>{m(),i(y)},()=>{m(),i(e.late)})})},yr=Object.freeze({error:(e,t)=>{console.error(e,t)}}),Tt=Symbol.for("@aiquants/markdown-explorer:ExplorerError");class ye 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,Tt,{value:!0})}}const gr=e=>e instanceof Error&&Object.hasOwn(e,Tt)&&w.isExplorerFailureReason(e.reason),Er=e=>typeof e=="object"&&e!==null&&e.name==="AbortError",ze=(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})}},oe=(e,t)=>ze(e,`[markdown-explorer] ${t.operation} failed`,t),br=(e,t)=>ze(e,`[markdown-explorer] ${t.operation} left out an entry`,t),Pe=(e,t)=>ze(e,`[markdown-explorer] ${t.operation} refused a path the deny rules match`,{...t,error:new RangeError("[markdown-explorer] the path matches a deny rule")}),Ke=(e,t)=>{e===null||typeof e!="object"&&typeof e!="function"||Promise.resolve(e).then(void 0,t)},Y=(e,t,r,n)=>gr(e)?w.failureOf(e.reason,e.code):(Er(e)||r.aborted||oe(n,{...t,error:e}),{reason:"failed"}),Ve=2*1024*1024,Qe=256*1024*1024,Tr=async(e,t)=>{const r=e.getReader(),n=new Uint8Array(t);let i=0;for(;i<t;){const{done:a,value:c}=await r.read();if(a)return n.subarray(0,i);const m=c.subarray(0,t-i);n.set(m,i),i+=m.byteLength}return r.cancel().catch(()=>{}),n},kr=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),i=await Tr(await e.open(r?{offset:0,length:t}:null),n);if(e.size!==null&&i.byteLength<n)throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");const a=r||i.byteLength>t,c=a?i.subarray(0,t):i;return c.includes(0)?null:{text:new TextDecoder("utf-8").decode(c,{stream:a}),truncated:a}},Ze=(e,t)=>{if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] a cache ${e} must be a positive integer; got ${String(t)}`)},kt=(e,t)=>{Ze("capacity",e),t!==void 0&&Ze("weight budget",t.max);const r=new Map;let n=0;const i=a=>{const c=r.get(a);c!==void 0&&(r.delete(a),n-=c.weight)};return{get:a=>{const c=r.get(a);if(c!==void 0)return r.delete(a),r.set(a,c),c.value},set:(a,c)=>{i(a);const m=t===void 0?0:t.of(a,c);if(!(t!==void 0&&m>t.max)){r.set(a,{value:c,weight:m}),n+=m;for(const y of r.keys()){if(r.size<=e&&(t===void 0||n<=t.max))break;i(y)}}},delete:i,size:()=>r.size,weight:()=>n}},St=e=>Math.max(1,e-1),Sr=2147483647,qe=Object.freeze({status:"aborted"}),de=(e,t,r)=>{const n=(e.get(t)??0)+r;n===0?e.delete(t):e.set(t,n)},fe=(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)}`)},Or=e=>e!==null&&typeof e=="object"&&e.ready===!0&&!("id"in e),xr=(e,t)=>e!==null&&typeof e=="object"&&e.id===t&&"output"in e,Rr=({url:e,size:t,deadlineMs:r,jobsPerScope:n,maxQueuedJobs:i,heapLimits:a})=>{fe("size",t,Number.MAX_SAFE_INTEGER),fe("deadline",r,Sr),fe("jobsPerScope",n,Number.MAX_SAFE_INTEGER),fe("maxQueuedJobs",i,Number.MAX_SAFE_INTEGER),fe("maxOldGenerationSizeMb",a.maxOldGenerationSizeMb,Number.MAX_SAFE_INTEGER),fe("maxYoungGenerationSizeMb",a.maxYoungGenerationSizeMb,Number.MAX_SAFE_INTEGER);const c=Object.freeze({maxOldGenerationSizeMb:a.maxOldGenerationSizeMb,maxYoungGenerationSizeMb:a.maxYoungGenerationSizeMb}),m=new Set,y=[],x=new Map,h=new Map,g=St(t);let S=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&&(de(x,b.scope,-1),de(h,b.scope,-1),b.settle(E))},$=p=>{const[E]=y.splice(p,1);E?.detach()},N=()=>{let p=-1,E=g,b=Number.POSITIVE_INFINITY;for(const[R,k]of y.entries()){const I=x.get(k.scope)??0,L=h.get(k.scope)??0;(I<E||I===E&&p>=0&&L<b)&&(p=R,E=I,b=L)}return p},_=(p,E)=>{m.has(p)&&(m.delete(p),A(p,E),p.worker.terminate().catch(()=>{}),U())},C=p=>{p.timer=setTimeout(()=>{_(p,{status:"timeout"})},r)},v=(p,E)=>p.sent?{status:"crashed",error:E}:{status:"unavailable",error:E},M=(p,E)=>{p.sent=!0,C(p);try{p.worker.postMessage({id:E.id,input:E.input})}catch(b){A(p,{status:"crashed",error:b}),p.worker.unref()}},H=()=>{const p={worker:new Yt.Worker(e,{resourceLimits:c}),job:null,sent:!1,timer:null,ready:!1};return p.worker.unref(),p.timer=setTimeout(()=>{_(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&&Or(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&&U();return}const{job:b}=p;if(b===null||!xr(E,b.id)){_(p,v(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(),U()}),p.worker.on("error",E=>{_(p,v(p,E))}),p.worker.on("messageerror",E=>{_(p,v(p,E))}),p.worker.on("exit",E=>{_(p,v(p,new Error(`[markdown-explorer] a worker exited with code ${String(E)}`)))}),m.add(p),p},U=()=>{for(;;){const p=N(),E=y[p];if(E===void 0)return;let b;for(const k of m)if(k.job===null){b=k;break}if(b===void 0&&m.size<t)try{b=H()}catch(k){$(p),de(h,E.scope,-1),E.settle({status:"unavailable",error:k});continue}if(b===void 0)return;$(p),de(x,E.scope,1);const R=b;R.job=E,R.worker.ref(),R.ready&&M(R,E)}};return{run:(p,{scope:E,signal:b})=>new Promise(R=>{if(b.aborted){R(qe);return}if((h.get(E)??0)>=n){R({status:"refused",limit:"scope"});return}S+=1;const k={id:S,input:p,scope:E,settle:R,detach:()=>{}};y.push(k),de(h,E,1),U();const I=y.indexOf(k);if(I<0)return;if(y.length>i){$(I),de(h,E,-1),R({status:"refused",limit:"queue"});return}const L=()=>{const X=y.indexOf(k);X<0||($(X),de(h,E,-1),R(qe))};b.addEventListener("abort",L,{once:!0}),k.detach=()=>{b.removeEventListener("abort",L)}}),workers:()=>m.size}},Ce=1024*1024,_r=3e4,Ar=4*Ce,vr=64*Ce,Nr=3,Pr=2,Ir=(e,t)=>e+St(t)+Nr,Mr=4,Lr=32,Dr=512,$r=64,jr=4096,zr=32,et=4096,Cr=4,Ot=({workerHeapMb:e,maxHtmlBytes:t})=>Math.floor(((e-$r)*Ce-t*zr)/jr),Hr=({maxHtmlBytes:e})=>e,Br=({maxHtmlBytes:e})=>Cr*e,Fr=1024,Ur=2147483647,Xr=64,Gr=2**29,Jr=1024*1024,Yr=64,tt=Object.freeze({status:"rejected",reason:"too-large",cause:null}),Ie=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},Wr=(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:i,cacheBytes:a,workerHeapMb:c,jobsPerScope:m,maxQueuedJobs:y}=e??{},x=le("workers",r,Pr,Xr),h=le("jobsPerScope",m,Ir(t,x),Number.MAX_SAFE_INTEGER),g=Object.freeze({workers:x,deadlineMs:le("deadlineMs",n,_r,Ur),maxHtmlBytes:le("maxHtmlBytes",i,Ar,Gr),cacheBytes:le("cacheBytes",a,vr,Number.MAX_SAFE_INTEGER),workerHeapMb:le("workerHeapMb",c,Dr,Jr),jobsPerScope:h,maxQueuedJobs:le("maxQueuedJobs",y,Mr*h,Number.MAX_SAFE_INTEGER)});if(g.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(g.jobsPerScope)}`);if(g.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(g.maxQueuedJobs)}`);if(Ot(g)<et)throw new RangeError(`[markdown-explorer] sanitizer.workerHeapMb (${String(g.workerHeapMb)} MiB) must leave room for ${String(et)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(g.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`);return g},Kr=()=>{const e=typeof document>"u"?require("url").pathToFileURL(__filename).href:Ae&&Ae.tagName.toUpperCase()==="SCRIPT"&&Ae.src||new URL("server.cjs",document.baseURI).href,t=new URL(`./sanitizeWorker${ne.extname(_e.fileURLToPath(e))}`,e);if(!ie.existsSync(_e.fileURLToPath(t)))throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${_e.fileURLToPath(t)}`);return t},rt=new Map,Vr=(e,t)=>{const r=[e.href,t.workers,t.deadlineMs,t.workerHeapMb,t.jobsPerScope,t.maxQueuedJobs].map(String).join("\0");let n=rt.get(r);return n===void 0&&(n=Rr({url:e,size:t.workers,deadlineMs:t.deadlineMs,jobsPerScope:t.jobsPerScope,maxQueuedJobs:t.maxQueuedJobs,heapLimits:{maxOldGenerationSizeMb:t.workerHeapMb,maxYoungGenerationSizeMb:Lr}}),rt.set(r,n)),n},Qr=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"},Zr=e=>e instanceof Error&&e.code==="ERR_WORKER_OUT_OF_MEMORY",qr=({iframeHosts:e,dataPath:t,options:r,pool:n})=>{const i=Object.freeze([...e]),a=Ot(r),c=Hr(r),m=Br(r),y=kt(Fr,{max:r.cacheBytes,of:(N,_)=>2*N.length+(_.status==="sanitized"?2*_.html.length:Yr)}),x=new Map,h=new Map,g=N=>{x.get(N.key)===N&&x.delete(N.key);const _=h.get(N.hash);_?.delete(N),_?.size===0&&h.delete(N.hash)},S=async(N,_,C)=>{const v=await n.run({html:N,iframeHosts:i,dataPath:t,maxNodes:a,maxAttributeChars:c,maxSanitizedChars:m},{scope:_,signal:C});if(v.status==="refused"){const H=v.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: ${H}`)},lasting:!1}}if(v.status==="aborted")return{outcome:Ie,lasting:!1};if(v.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(v.status==="unavailable")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker could not start",{cause:v.error})},lasting:!1};if(v.status==="crashed"&&Zr(v.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:v.error})},lasting:!0};if(v.status==="crashed")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker failed",{cause:v.error})},lasting:!0};const{output:M}=v;return Qr(M)?M.status==="too-large"?{outcome:tt,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,_,C,v)=>{let M=()=>{};const H=new Promise(E=>{M=E}),U={hash:_,key:C,outcome:H,answer:M,controller:new AbortController,waiters:0};x.set(C,U);const p=h.get(_);return p===void 0?h.set(_,new Set([U])):p.add(U),S(N,v,U.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(g(U),U.answer(E),!b)return;const R=y.get(_),k=R??(E.status==="rejected"?{...E,cause:null}:E);R===void 0&&y.set(_,k);for(const I of h.get(_)??[])g(I),I.answer(k),I.controller.abort()}),U},$=(N,_)=>new Promise(C=>{N.waiters+=1;const v=()=>{N.waiters-=1,C(Ie),!(N.waiters>0)&&(g(N),N.controller.abort())};_.addEventListener("abort",v,{once:!0}),N.outcome.then(M=>{_.removeEventListener("abort",v),C(M)})});return(N,{scope:_,signal:C})=>{if(N.length>r.maxHtmlBytes||Buffer.byteLength(N,"utf8")>r.maxHtmlBytes)return Promise.resolve(tt);const v=wt.createHash("sha256").update(N,"utf8").digest("base64"),M=y.get(v);if(M!==void 0)return Promise.resolve(M);if(C.aborted)return Promise.resolve(Ie);const H=`${v}\0${_}`,U=x.get(H);return $(U===void 0?A(N,v,H,_):U,C)}},Oe=e=>({result:e,json:JSON.stringify(e)}),Me=Object.freeze(Oe(Object.freeze({status:"error",failure:Object.freeze({reason:"failed"})}))),en=e=>e.status==="ok"&&e.entries.length>0,tn=({ttlMs:e,maxEntries:t,maxBytes:r,now:n})=>{const i=kt(t,{max:r,of:(h,g)=>2*g.tree.json.length}),a=new Map,c=new Map,m=(h,g)=>{const S=new AbortController,A={waiters:0,superseded:!1,started:!1,loadTree:g},$=c.get(h),N=(H,U)=>{const p=Oe(H);return!(A.superseded||S.signal.aborted)&&en(H)&&i.set(h,{tree:p,loadedAt:U}),p},C=(async()=>{if($!==void 0&&await $,S.signal.aborted)return Me;const H=n();return A.started=!0,N(await A.loadTree(S.signal,H),H)})().finally(()=>{a.get(h)===v&&a.delete(h)}),v={promise:C,controller:S,state:A};a.set(h,v);const M=C.then(()=>{},()=>{});return c.set(h,M),M.then(()=>{c.get(h)===M&&c.delete(h)}),v},y=(h,g,S)=>{g.state.waiters+=1;const A=()=>{g.state.waiters-=1,!(g.state.waiters>0)&&(a.get(h)===g&&a.delete(h),g.controller.abort())};return S.addEventListener("abort",A,{once:!0}),g.promise.finally(()=>{S.removeEventListener("abort",A)})},x=h=>{i.delete(h);const g=a.get(h);g?.state.started&&(g.state.superseded=!0,a.delete(h))};return{load:(h,g,S)=>{if(g.aborted)return Promise.resolve(Me);const A=i.get(h);if(A!==void 0){if(n()-A.loadedAt<e)return Promise.resolve(A.tree);i.delete(h)}const $=a.get(h);return y(h,$===void 0?m(h,S):$,g)},refresh:(h,g,S)=>{if(g.aborted)return Promise.resolve(Me);x(h);const A=a.get(h);return A===void 0?y(h,m(h,S),g):(A.state.loadTree=S,y(h,A,g))},forget:x}},rn=e=>({load:(t,r,n)=>n(r,e()).then(Oe),refresh:(t,r,n)=>n(r,e()).then(Oe),forget:()=>{}}),O=e=>{throw new TypeError(`[markdown-explorer] ${e}`)},nn=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)"}},on=(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 i=new Set;for(const a of e){if(typeof a!="string"||!w.isAcceptableDocumentPath(a))throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");if(r.deniesPath(a))throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");if(!n(a))throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");if(a===t)throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");if(i.has(a))throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");i.add(a)}return Object.freeze([...i])},sn=(e,t,r,n,i)=>{const a=new Set,c=y=>{if(!Array.isArray(y))return O("a source returned entries that are not an array");const x=[];for(const h of y){const g=m(h);g!==null&&x.push(g)}return x},m=y=>{const x=nn(y);if(x!==null)return n(x),null;const h=w.entryViolation(y);if(h!==null)return O(h);const g=y;if(a.has(g))return O("a source returned entries that contain themselves");const{name:S,path:A,type:$,mimeType:N,modifiedAt:_,children:C,lazy:v}=g;if(t.deniesName(S)||t.deniesPath(A))return null;if(!i(A))return n({path:A,reason:"a path outside the source's boundary"}),null;const M={name:S,path:A,...N===void 0?{}:{mimeType:N},..._===void 0?{}:{modifiedAt:_}};if($==="file")return{...M,type:$};if(v===!0)return r?{...M,type:$,lazy:!0,children:[]}:O("a lazy directory came from a source without a children function");if(C===void 0)return{...M,type:$};a.add(g);const H=c(C);return a.delete(g),{...M,type:$,children:H}};return c(e)},an=/^[\x21\x23-\x7E]{1,256}$/u,xt=e=>typeof e=="string"&&an.test(e),cn=new Set(["text","image","media","file"]),un=e=>typeof e=="string"&&cn.has(e),dn=(e,t,r)=>{if(e!==null&&typeof e=="object"){const a=e,{kind:c}=a;if(un(c)){if(Object.hasOwn(a,"url"))return O(`a ${c} document carries its version, not a url`);if(typeof a.name!="string")return O("a document needs a name string");if(!xt(a.version))return O(`a ${c} document needs a version of 1 to 256 visible ASCII characters other than '"'`);const m=t(a.version);switch(c){case"image":case"file":return{kind:c,name:a.name,url:m};case"media":{const{mediaType:y}=a;return w.isExplorerMediaType(y)?{kind:c,name:a.name,url:m,mediaType:y}:O(`unknown media type ${typeof y=="string"?JSON.stringify(y.slice(0,64)):typeof y}`)}case"text":return typeof a.text!="string"||typeof a.truncated!="boolean"?O("a text document needs text and truncated"):{kind:c,name:a.name,text:a.text,truncated:a.truncated,url:m}}}}const n=w.documentViolation(e);if(n!==null)return O(n);const i=e;switch(i.kind){case"failure":{const{reason:a,code:c}=i.failure;return{kind:"failure",failure:w.failureOf(a,c)}}case"markdown":return i.headings.length>w.EXPLORER_MAX_HEADINGS?{kind:"failure",failure:w.failureOf("too-large")}:(i.edit?.kind==="inline"||i.edit?.kind==="draft")&&!r?O(`a markdown document offers ${i.edit.kind} editing, but the server has no edit ports`):{kind:"unsanitized-markdown",name:i.name,html:i.htmlContent,headings:i.headings.map(({text:a,depth:c,id:m})=>({text:a,depth:c,id:m})),edit:ln(i.edit)}}},ln=e=>{if(e===null)return null;switch(e.kind){case"inline":return{kind:"inline"};case"draft":return{kind:"draft"};case"external":return{kind:"external",href:e.href}}},xe=(e,t,r)=>typeof e!="string"?O(`${r} needs a text string`):e.includes("\0")?O(`${r} holds NUL, which no text editor can keep`):new TextEncoder().encode(e).byteLength>t?O(`${r} is over editMaxBytes (${t} bytes); refuse a longer source with ExplorerError "too-large"`):e,Rt=e=>w.isRootRelativeUrl(e.href)?{kind:"grant",href:e.href}:O("a grant needs a root-relative href"),fn=(e,t)=>{if(e===null||typeof e!="object")return O("an edit source must be an object");const r=e;return r.kind==="grant"?Rt(r):r.kind==="draft"?{kind:"draft",text:xe(r.text,t,"a draft source")}:r.kind!=="edit"?O(`an edit source's kind must be "edit", "draft" or "grant"`):w.isExplorerEditToken(r.version)?typeof r.history!="boolean"?O("an edit source needs history"):{kind:"edit",text:xe(r.text,t,"an edit source"),version:r.version,history:r.history}:O("an edit source needs a version of 1 to 1024 characters")},mn=(e,t)=>{if(e===null||typeof e!="object")return O("a save result must be an object");const r=e;switch(r.kind){case"grant":return Rt(r);case"saved":return w.isExplorerEditToken(r.version)?{kind:"saved",version:r.version}:O("a saved result needs a version of 1 to 1024 characters");case"conflict":return w.isExplorerEditToken(r.version)?{kind:"conflict",version:r.version,text:xe(r.text,t,"a conflict's current text")}:O("a conflict needs the current version of 1 to 1024 characters");default:return O(`a save result's kind must be "saved", "conflict" or "grant"`)}},pn=e=>{if(e===null||typeof e!="object")return O("a preview must be an object");const{htmlContent:t,headings:r}=e;if(typeof t!="string"||!Array.isArray(r))return O("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 i=w.headingViolation(n);if(i!==null)return O(i)}return{html:t,headings:r.map(({text:n,depth:i,id:a})=>({text:n,depth:i,id:a}))}},hn=e=>{if(!Array.isArray(e))return O("revisions must be an array");const t=new Set;return e.map(r=>{const n=w.revisionViolation(r);if(n!==null)return O(n);const{id:i,modifiedAt:a,size:c,author:m,kept:y,current:x}=r;return t.has(i)?O(`two revisions share the id ${JSON.stringify(i.slice(0,64))}`):(t.add(i),{id:i,modifiedAt:a,size:c,author:m,kept:y,current:x})})},wn=(e,t)=>xe(e,t,"a revision"),$e=e=>{if(e===null||typeof e!="object")return O("an asset file must be an object");const{name:t,contentType:r,size:n,version:i,open:a,kind:c}=e;return c!==void 0?O(c==="redirect"?"an asset redirect answers only a request for the stored file (options.redirect), never one that reads the bytes":'an asset file has no kind (the only kind is "redirect")'):typeof t!="string"||t===""?O("an asset file needs a non-empty name"):typeof r!="string"?O("an asset file needs a contentType string ('' when unknown)"):n!==null&&!(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)?O("an asset file's size must be null or a non-negative safe integer"):xt(i)?typeof a!="function"?O("an asset file needs an open function"):Object.freeze({name:t,contentType:r,size:n,version:i,open:a}):O(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`)},yn=e=>{if(e===null||typeof e!="object"||e.kind!=="redirect")return $e(e);const{url:t}=e;if(typeof t!="string"||!URL.canParse(t))return O("an asset redirect needs an absolute https URL");const r=new URL(t);return r.protocol!=="https:"||r.username!==""||r.password!==""?O("an asset redirect's URL must be https and carry no credentials"):Object.freeze({kind:"redirect",url:r.href})},gn=e=>Array.isArray(e)?e.map(t=>{if(t===null||typeof t!="object")return O("a notice must be an object");const{id:r,tone:n,title:i,body:a,action:c}=t;if(typeof r!="string"||r===""||typeof i!="string")return O("a notice needs an id and a title");if(!w.isExplorerNoticeTone(n))return O(`unknown notice tone ${typeof n=="string"?JSON.stringify(n.slice(0,64)):typeof n}`);if(a!==void 0&&typeof a!="string")return O("a notice body must be a string");const y={id:r,tone:n,title:i,...a===void 0?{}:{body:a}};if(c===void 0)return y;if(c===null||typeof c!="object")return O("a notice action must be an object");const{label:x,href:h}=c;return typeof x!="string"||!w.isAcceptableUrl(h,w.EXPLORER_LINK_PROTOCOLS)?O("a notice action needs a label and an http(s), mailto or relative href"):{...y,action:{label:x,href:h}}}):O("notices must be an array"),En=4e3,be=Object.freeze({ttlMs:3e5,maxEntries:64,maxBytes:64*1024*1024}),nt=32,_t="private, no-store",bn=Object.freeze({"Content-Type":"application/json; charset=utf-8","Cache-Control":_t,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; frame-ancestors 'none'; sandbox","Cross-Origin-Resource-Policy":"same-origin"}),Tn=22,kn=2147483647,Le=Object.freeze([]),Sn=Object.freeze({status:"ok",source:null,ancestors:null}),ot=Object.freeze(["contains","confirm"]),st=Object.freeze({readOnly:!1}),On=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}`)},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},xn=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)},it=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)")}},at=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<nt)throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(nt)} characters; got ${String(e.length)}`);return e},_n=(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(!ot.includes(r))throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${ot.join(", ")}`);V(`${e}.boundary.contains`,t.contains,!1),V(`${e}.boundary.confirm`,t.confirm,!0)},An=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,i]of t.entries()){if(i===null||typeof i!="object")throw new TypeError(`[markdown-explorer] sources[${String(n)}] must be an object`);const{id:a,label:c,boundary:m,tree:y,children:x,ancestors:h,cacheScope:g}=i;if(!se.isExplorerSourceId(a))throw new RangeError(`[markdown-explorer] sources[${String(n)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${typeof a=="string"?JSON.stringify(a):typeof a}`);const S=`source ${JSON.stringify(a)}`;if(r.has(a))throw new RangeError(`[markdown-explorer] source ids must be unique; ${JSON.stringify(a)} repeats at sources[${String(n)}]`);if(r.add(a),typeof c!="string"&&typeof c!="function")throw new TypeError(`[markdown-explorer] ${S}.label must be a string or a function`);if(typeof c=="string"&&c.trim()==="")throw new RangeError(`[markdown-explorer] ${S}.label must not be blank`);if(_n(S,m),V(`${S}.tree`,y,!1),V(`${S}.children`,x,!0),V(`${S}.ancestors`,h,!0),g!==void 0&&g!=="principal"&&g!=="shared")throw new RangeError(`[markdown-explorer] ${S}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(g)}`)}return t},vn=e=>{if(e===!1)return!1;if(e===void 0)return be;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?be.ttlMs:pe("treeCache.ttlMs",t,Number.MAX_SAFE_INTEGER),maxEntries:r===void 0?be.maxEntries:pe("treeCache.maxEntries",r,Number.MAX_SAFE_INTEGER),maxBytes:n===void 0?be.maxBytes:pe("treeCache.maxBytes",n,Number.MAX_SAFE_INTEGER)}},ct=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},ut=(e,t)=>{if(!(t instanceof Response))throw new TypeError(`[markdown-explorer] ${e} must return a Response`);return t},dt=(e,t)=>{if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");return wt.createHmac("sha256",e).update(t,"utf8").digest("base64url").slice(0,Tn)},Nn=e=>e.view==="multi"?e.docs:e.doc===null?[]:[e.doc],ue=(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 i=new Headers(r);for(const[a,c]of Object.entries({...bn,...n}))i.set(a,c);return new Response(t,{status:e,headers:i})},j=(e,t,r)=>K(w.EXPLORER_FAILURE_STATUS[e.reason],JSON.stringify({failure:e}),t,r),Pn=new Set(["refresh","save","preview"]),In=new Set(["edit","save","preview","revisions","revision"]),lt=(e,t)=>{const r=Pn.has(t)?["POST"]:["GET","HEAD"];return r.includes(e.method.toUpperCase())?null:K(405,JSON.stringify({failure:{reason:"invalid"}}),void 0,{Allow:r.join(", ")})},ft=e=>e.headers.get(w.EXPLORER_PROOF_HEADER)===w.EXPLORER_REFRESH_PROOF&&Se.crossOriginRefusal(e,Se.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Mn=e=>e.headers.get(w.EXPLORER_PROOF_HEADER)===w.EXPLORER_EDIT_PROOF&&Se.crossOriginRefusal(e,Se.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Ln=async(e,t)=>{const[r,...n]=(e.headers.get("Content-Type")??"").split(";").map(S=>S.trim().toLowerCase()),i=n.find(S=>S.startsWith("charset="));if(r!==w.EXPLORER_DRAFT_MEDIA_TYPE||i!==void 0&&i!=="charset=utf-8")return{status:"error",failure:{reason:"invalid"}};const a=Number(e.headers.get("Content-Length")??"0");if(Number.isFinite(a)&&a>t)return{status:"error",failure:{reason:"too-large"}};if(e.body===null)return{status:"ok",text:""};const c=e.body.getReader(),m=[];let y=0;for(;;){const{done:S,value:A}=await c.read();if(S)break;if(y+=A.byteLength,y>t)return await c.cancel(),{status:"error",failure:{reason:"too-large"}};m.push(A)}const x=new Uint8Array(y);let h=0;for(const S of m)x.set(S,h),h+=S.byteLength;let g;try{g=new TextDecoder("utf-8",{fatal:!0}).decode(x)}catch{return{status:"error",failure:{reason:"invalid"}}}return g.includes("\0")?{status:"error",failure:{reason:"invalid"}}:{status:"ok",text:g}},Dn=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},$n=({parentHeaders:e,loaderHeaders:t,errorHeaders:r})=>{const n=new Headers,i=r===void 0?[e,t]:[e,t,r];for(const a of i)for(const[c,m]of a)c!=="set-cookie"&&n.set(c,m);return n},jn=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the server configuration must be an object");const t=xn(e.config),r=Rn(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=An(e.sources),i=se.withExplorerSources(t,n.map(o=>o.id)),a=e.logger;if(a!==void 0&&(a===null||typeof a!="object"||typeof a.error!="function"))throw new TypeError("[markdown-explorer] logger must be an object with an error function");const c=e.logger===void 0?yr:e.logger,m=w.resolvePathRules(e.deny),y=e.deferredTimeoutMs===void 0?En:pe("deferredTimeoutMs",e.deferredTimeoutMs,kn),x=e.textMaxBytes===void 0?Ve:pe("textMaxBytes",e.textMaxBytes,Qe),h=Dn(e.edit);if(h===void 0&&e.editMaxBytes!==void 0)throw new TypeError("[markdown-explorer] editMaxBytes needs the edit ports");const g=e.editMaxBytes===void 0?Ve:pe("editMaxBytes",e.editMaxBytes,Qe),S=vn(e.treeCache),A=()=>Date.now(),$=S===!1?rn(A):tn({...S,now:A}),N=Wr(e.sanitizer,t.multiView.maxPanels),_=qr({iframeHosts:t.iframeHosts,dataPath:t.dataPath,options:N,pool:Vr(Kr(),N)}),C=new Map(n.map(o=>[o.id,o])),v=se.documentStyleNames(t),{authenticate:M,principalKey:H,signedOutPage:U,forbiddenPage:p,onTreeRefreshed:E}=e,b=(o,u)=>{if(typeof o.label=="string")return o.label;const s=o.label(u);if(typeof s!="string"||s.trim()==="")throw new TypeError(`[markdown-explorer] the label of source ${JSON.stringify(o.id)} must be a non-blank string`);return s},R=(o,u)=>o.cacheScope==="shared"?o.id:`${o.id}\0${u}`,k=(o,u)=>{const s=l=>oe(c,{operation:"boundary",sourceId:o.id,path:u,error:l});let d;try{d=o.boundary.contains(u)}catch(l){return s(l),!1}return typeof d=="boolean"?d:(Ke(d,s),s(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(o.id)} must return a boolean; got ${typeof d}`)),!1)},I=async(o,u,s)=>{const{confirm:d}=o.boundary;if(d===void 0)return{status:"inside",readPath:s};let l;try{l=await d(u,s)}catch(z){return{status:"error",failure:Y(z,{operation:"boundary",sourceId:o.id,path:s},u.signal,c)}}const f=z=>(oe(c,{operation:"boundary",sourceId:o.id,path:s,error:new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} ${z}`)}),{status:"outside"});if(l===null||typeof l!="object")return f(`must resolve to { inside, readPath? }; got ${l===null?"null":typeof l}`);const{inside:T,readPath:P}=l;return T===!1?{status:"outside"}:T!==!0||typeof P!="string"?f("must resolve to { inside: false } or { inside: true, readPath: string }"):!w.isAcceptableDocumentPath(P)||m.deniesPath(P)?(oe(c,{operation:"boundary",sourceId:o.id,path:s,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:P}},L=async(o,u)=>{const s=n.filter(l=>k(l,u));if(s.length===0)return{status:"error",failure:{reason:"forbidden"}};if(s.some(l=>l.boundary.confirm===void 0))return{status:"inside",readPath:u};let d=null;for(const l of s){const f=await I(l,o,u);if(f.status==="inside")return f;f.status==="error"&&d===null&&(d=f.failure)}return{status:"error",failure:d===null?{reason:"forbidden"}:d}},X=(o,u,s)=>{const d=({path:l,reason:f})=>br(c,{operation:s.operation,sourceId:s.sourceId,path:l,error:new TypeError(`[markdown-explorer] an entry with ${f} was left out`)});try{return{status:"ok",entries:sn(o,m,u.children!==void 0,d,l=>k(u,l))}}catch(l){return oe(c,{...s,error:l}),{status:"error",failure:{reason:"failed"}}}},D=async(o,u,s)=>{let d;try{d=await o.tree(u)}catch(f){return{status:"error",failure:Y(f,{operation:"tree",sourceId:o.id},u.signal,c)}}const l=X(d,o,{operation:"tree",sourceId:o.id});return l.status==="ok"?{status:"ok",entries:l.entries,loadedAt:s}:l},G=(o,u,s,d)=>(l,f)=>D(o,{principal:u,request:s,signal:l,refresh:d},f),Q=(o,u,s,d,l)=>$.load(R(o,s),l,G(o,u,d,!1)),J=(o,u,s,d)=>$.refresh(R(o,s),d.signal,G(o,u,d,!0)),ae=(o,u)=>{if(E===void 0)return;const s=d=>oe(c,{operation:"refresh",sourceId:o.id,error:d});try{Ke(E(u),s)}catch(d){s(d)}},B=async(o,u,s,d)=>{if(m.deniesPath(d)||!k(o,d))return{status:"error",failure:{reason:"forbidden"}};const l=await I(o,s,d);if(l.status==="outside")return{status:"error",failure:{reason:"forbidden"}};if(l.status==="error")return{status:"error",failure:l.failure};let f;try{f=await u(s,d,l.readPath)}catch(T){return{status:"error",failure:Y(T,{operation:"children",sourceId:o.id,path:d},s.signal,c)}}return X(f,o,{operation:"children",sourceId:o.id,path:d})},Z=async(o,u,s,d)=>{const l=await I(o,s,d);if(l.status==="outside")return{status:"ok",ancestors:null};if(l.status==="error")return{status:"error",failure:l.failure};let f;try{f=await u(s,d,l.readPath,{maxDepth:t.revealDocument.maxDepth})}catch(T){return{status:"error",failure:Y(T,{operation:"ancestors",sourceId:o.id,path:d},s.signal,c)}}if(Array.isArray(f)&&f.length>t.revealDocument.maxDepth)return{status:"ok",ancestors:null};try{return{status:"ok",ancestors:on(f,d,m,T=>k(o,T))}}catch(T){return oe(c,{operation:"ancestors",sourceId:o.id,path:d,error:T}),{status:"error",failure:{reason:"failed"}}}},q=async(o,u,s,d)=>m.deniesPath(d)?{status:"error",failure:{reason:"forbidden"}}:k(o,d)?Z(o,u,s,d):{status:"ok",ancestors:null},ee=async(o,u,s)=>{if(m.deniesPath(s))return{status:"error",failure:{reason:"forbidden"}};for(const d of[o,...n.filter(l=>l!==o)]){if(u.signal.aborted)break;const l=d.ancestors;if(l===void 0||!k(d,s))continue;const f=await Z(d,l,u,s);if(f.status==="ok"&&f.ancestors!==null)return{status:"ok",source:d.id,ancestors:f.ancestors}}return Sn},ce=async(o,u,s)=>{if(m.deniesPath(s))return w.failureDocument("forbidden");const d=await L(o,s);if(d.status==="error")return{kind:"failure",failure:d.failure};let l;try{l=await e.document(o,s,d.readPath)}catch(P){return{kind:"failure",failure:Y(P,{operation:"document",path:s},o.signal,c)}}let f;try{f=dn(l,P=>w.explorerAssetHref(t.dataPath,s,P),h!==void 0)}catch(P){return oe(c,{operation:"document",path:s,error:P}),w.failureDocument("failed")}if(f.kind!=="unsanitized-markdown")return f;const T=await _(f.html,{scope:u,signal:o.signal});return T.status==="sanitized"?{kind:"markdown",name:f.name,htmlContent:T.html,headings:f.headings,edit:f.edit}:(T.cause!==null&&oe(c,{operation:"document",path:s,error:T.cause}),w.failureDocument(T.reason))},ge=async o=>{if(e.notices===void 0)return Le;try{return gn(await e.notices(o))}catch(u){return Y(u,{operation:"notices"},o.signal,c),Le}},Lt=async(o,u,s)=>{const d=ue(u,w.EXPLORER_DATA_QUERY.path);if(d===null||!w.isAcceptableDocumentPath(d))return j({reason:"invalid"},s);const l=w.readExplorerAssetDisplay(u);if(l===null)return j({reason:"invalid"},s);if(m.deniesPath(d))return Pe(c,{operation:"asset",path:d}),j({reason:"forbidden"},s);const f=await L(o,d);if(f.status==="error")return j(f.failure,s);try{const T=l==="file",P=await e.asset(o,d,f.readPath,{redirect:T}),z=T?yn(P):$e(P);return"kind"in z?wr(z.url,s):await pr(o.request,z,s,l)}catch(T){return j(Y(T,{operation:"asset",path:d},o.signal,c),s)}},Dt=async(o,u)=>{if(m.deniesPath(u))return Pe(c,{operation:"text",path:u}),w.failureDocument("forbidden");const s=await L(o,u);if(s.status==="error")return{kind:"failure",failure:s.failure};try{const d=$e(await e.asset(o,u,s.readPath,{redirect:!1})),l=await kr(d,x);return l===null?w.failureDocument("unsupported"):{kind:"text",name:d.name,text:l.text,truncated:l.truncated,url:w.explorerAssetHref(t.dataPath,u,d.version)}}catch(d){return{kind:"failure",failure:Y(d,{operation:"text",path:u},o.signal,c)}}},he=async(o,u,s)=>m.deniesPath(s)?(Pe(c,{operation:u,path:s}),{status:"error",failure:{reason:"forbidden"}}):L(o,s),$t=async(o,u,s)=>{const d=await he(u,"edit",s);if(d.status==="error")return{kind:"failure",failure:d.failure};try{return fn(await o.source(u,s,d.readPath),g)}catch(l){return{kind:"failure",failure:Y(l,{operation:"edit",path:s},u.signal,c)}}},jt=async(o,u,s,d,l)=>{const f=await he(u,"save",s);if(f.status==="error")return{kind:"failure",failure:f.failure};try{return mn(await o.save(u,s,f.readPath,{text:l,baseVersion:d}),g)}catch(T){return{kind:"failure",failure:Y(T,{operation:"save",path:s},u.signal,c)}}},zt=async(o,u,s,d,l)=>{const f=await he(u,"preview",d);if(f.status==="error")return{kind:"failure",failure:f.failure};let T;try{T=pn(await o.preview(u,d,f.readPath,l))}catch(z){return{kind:"failure",failure:Y(z,{operation:"preview",path:d},u.signal,c)}}if("kind"in T)return T.kind==="failure"?T:w.failureDocument("failed");const P=await _(T.html,{scope:s,signal:u.signal});return P.status==="sanitized"?{kind:"preview",htmlContent:P.html,headings:T.headings}:(P.cause!==null&&oe(c,{operation:"preview",path:d,error:P.cause}),w.failureDocument(P.reason))},Ct=async(o,u,s)=>{const d=await he(u,"revisions",s);if(d.status==="error")return{kind:"failure",failure:d.failure};try{return{kind:"revisions",revisions:hn(await o.revisions(u,s,d.readPath))}}catch(l){return{kind:"failure",failure:Y(l,{operation:"revisions",path:s},u.signal,c)}}},Ht=async(o,u,s,d)=>{const l=await he(u,"revision",s);if(l.status==="error")return{kind:"failure",failure:l.failure};try{return{kind:"revision",id:d,text:wn(await o.revision(u,s,l.readPath,d),g)}}catch(f){return{kind:"failure",failure:Y(f,{operation:"revision",path:s},u.signal,c)}}},Bt=async(o,u,s,d,l,f)=>{const T=ue(l,w.EXPLORER_DATA_QUERY.path);if(T===null||!w.isAcceptableDocumentPath(T))return j({reason:"invalid"},f);if(u==="edit")return K(200,JSON.stringify(await $t(o,s,T)),f);if(u==="revisions")return K(200,JSON.stringify(await Ct(o,s,T)),f);if(u==="revision"){const te=ue(l,w.EXPLORER_DATA_QUERY.revision);return w.isExplorerEditToken(te)?K(200,JSON.stringify(await Ht(o,s,T,te)),f):j({reason:"invalid"},f)}const P=ue(l,w.EXPLORER_DATA_QUERY.base);if(u==="save"&&!w.isExplorerEditToken(P))return j({reason:"invalid"},f);const z=await Ln(s.request,g);return z.status==="error"?j(z.failure,f):u==="preview"?K(200,JSON.stringify(await zt(o,s,d,T,z.text)),f):K(200,JSON.stringify(await jt(o,s,T,P,z.text)),f)},Ft=async({request:o,url:u,params:s})=>{const d=ct(await M(o,st)),l=it(d.headers);if(l.set("Cache-Control",_t),d.status==="signed-out")throw ut("signedOutPage",U(o,l));if(d.status==="forbidden")throw p===void 0?Re.data(null,{status:403,headers:l}):ut("forbiddenPage",p(o,l));const f=se.resolveExplorerLocation(i,s["*"],u.searchParams);if(f.kind==="redirect")throw Re.redirect(f.href,{headers:l});const{location:T}=f,{principal:P}=d,z=dt(r,H(P)),te=C.get(T.source);if(te===void 0)throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(T.source)}`);const we={signal:o.signal,timeoutMs:y,late:null,handOverMs:y},re={scope:z,sources:n.map(F=>({id:F.id,label:b(F,P)})),settings:se.parseViewSettings(se.readCookieValue(o.headers.get("Cookie"),t.settingsCookie),v),tree:T.view==="single"?null:{sourceId:T.source,result:Ne(we,F=>Q(te,P,z,o,F).then(W=>W.result))},documents:Nn(T).map(F=>({path:F,document:Ne(we,W=>ce({principal:P,request:o,signal:W,refresh:!1},z,F))})),notices:Ne({signal:o.signal,timeoutMs:y,late:Le,handOverMs:0},F=>ge({principal:P,request:o,signal:F,refresh:!1}))};return Re.data(re,{headers:l})},He=async(o,u)=>{const s=ct(await M(o,u));return{authentication:s,headers:it(s.headers)}},Ut=async(o,u,s)=>{let d;try{d=await He(u,st)}catch(W){return j(Y(at(W),{operation:"authenticate"},u.signal,c))}const{authentication:l,headers:f}=d;if(l.status==="signed-out")return j({reason:"unauthorized"},f);if(l.status==="forbidden")return j({reason:"forbidden"},f);const{principal:T}=l;if(o==="asset")return Lt({principal:T,request:u,signal:u.signal,refresh:!1},s,f);const P=dt(r,H(T));f.set(w.EXPLORER_SCOPE_HEADER,P);const z={principal:T,request:u,signal:u.signal,refresh:!1},te=()=>j({reason:"invalid"},f);if(o==="document"){const W=ue(s,w.EXPLORER_DATA_QUERY.path);if(W===null||!w.isAcceptableDocumentPath(W))return te();const Ue=u.headers.has(w.EXPLORER_PROOF_HEADER);return Ue&&!ft(u)?j({reason:"forbidden"},f):K(200,JSON.stringify(await ce({...z,refresh:Ue},P,W)),f)}if(o==="text"){const W=ue(s,w.EXPLORER_DATA_QUERY.path);return W===null||!w.isAcceptableDocumentPath(W)?te():K(200,JSON.stringify(await Dt(z,W)),f)}if(o==="edit"||o==="save"||o==="preview"||o==="revisions"||o==="revision")return h===void 0?j({reason:"not-found"},f):Bt(h,o,z,P,s,f);const we=ue(s,w.EXPLORER_DATA_QUERY.source),re=ue(s,w.EXPLORER_DATA_QUERY.path);if(we===null||(o==="children"||o==="ancestors"||o==="reveal")&&(re===null||!w.isAcceptableDocumentPath(re)))return te();const F=C.get(we);if(F===void 0)return j({reason:"not-found"},f);if(o==="tree")return K(200,(await Q(F,T,P,u,u.signal)).json,f);if(o==="refresh"){const W=await J(F,T,P,u);return u.signal.aborted||ae(F,R(F,P)),K(200,W.json,f)}return o==="ancestors"?F.ancestors===void 0||re===null?j({reason:"not-found"},f):K(200,JSON.stringify(await q(F,F.ancestors,z,re)),f):o==="reveal"?re===null?te():K(200,JSON.stringify(await ee(F,z,re)),f):F.children===void 0||re===null?j({reason:"not-found"},f):K(200,JSON.stringify(await B(F,F.children,z,re)),f)},Xt=async o=>{const{authentication:u,headers:s}=await He(o,On);if(!s.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 u.status==="signed-in"},Be=t.embeds.linkCardEndpoint===null?null:Jt.createLinkCardHandler({authorize:Xt}),Gt=async(o,u)=>{try{return await o(u)}catch(s){return j(Y(at(s),{operation:"authenticate"},u.signal,c))}},Fe=async(o,u,s)=>{if(new URL(o.url).pathname.endsWith(".data"))return j({reason:"not-found"});if(!w.isExplorerDataOperation(s))return j({reason:"not-found"});if(s==="link-card"){if(Be===null)return j({reason:"not-found"});const l=lt(o,s);return l!==null?l:Gt(Be,o)}if(In.has(s)&&h===void 0)return j({reason:"not-found"});const d=lt(o,s);if(d!==null)return d;if(s==="refresh"&&!ft(o))return j({reason:"forbidden"});if((s==="save"||s==="preview")&&!Mn(o))return j({reason:"forbidden"});try{return await Ut(s,o,u.searchParams)}catch(l){return j(Y(l,{operation:s},o.signal,c))}};return Object.freeze({loader:Ft,headers:$n,dataLoader:({request:o,url:u,params:s})=>Fe(o,u,s["*"]),dataAction:({request:o,url:u,params:s})=>Fe(o,u,s["*"]),forgetTree:o=>{if(typeof o!="string")throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof o}`);$.forget(o)}})},Te=Object.freeze({maxEntries:2e4,maxDocumentBytes:2*1024*1024,textPreviewBytes:8*1024,walkConcurrency:8}),zn=new Set(["md","markdown","mdx"]),At=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"}]]),Cn=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"]),Hn=new Set(["readme","license","licence","copying","notice","authors","contributors","changelog","changes","todo","makefile","dockerfile","containerfile","procfile","gemfile","rakefile","vagrantfile","jenkinsfile","brewfile","codeowners"]),vt=typeof ie.constants.O_NOFOLLOW=="number"?ie.constants.O_NOFOLLOW:0,Nt=typeof ie.constants.O_NONBLOCK=="number"?ie.constants.O_NONBLOCK:0,mt=e=>`${e.size}-${e.mtimeNs}`,Bn=e=>e!==""&&e!=="."&&e!==".."&&!e.includes(":")&&!e.endsWith(".")&&!e.endsWith(" "),pt=e=>w.isAcceptableDocumentPath(e)&&e===e.normalize("NFC")&&e.split("/").every(Bn),Pt=e=>{const t=e.toLowerCase(),r=t.lastIndexOf(".");return r<0?"":t.slice(r+1)},Fn=e=>{const t=Pt(e);if(zn.has(t))return{kind:"markdown"};const r=At.get(t);if(r!==void 0)return r.kind==="image"?{kind:"image"}:{kind:"media",mediaType:r.mediaType};const n=e.toLowerCase();return Cn.has(t)||!n.includes(".")&&Hn.has(n)?{kind:"text"}:{kind:"file"}},je=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}},It=e=>{const t=je(e);return t===null?e:new ye(t)},Mt=e=>{const t=typeof e=="object"&&e!==null?e.code:void 0;return t==="EACCES"||t==="EPERM"||t==="ENOENT"||t==="ENOTDIR"},Un=async e=>{try{return Math.trunc((await me.lstat(e)).mtimeMs)}catch(t){if(Mt(t))return;throw t}},ht=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)},Xn=(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 i;try{i=await me.open(e,ie.constants.O_RDONLY|vt|Nt);const y=await i.stat({bigint:!0});if(!y.isFile()||y.ino!==t.ino||y.dev!==t.dev||y.size!==t.size||y.mtimeNs!==t.mtimeNs)throw new ye("not-found")}catch(y){throw await i?.close(),It(y)}const a=i.createReadStream(Xn(r,t.size)),c=Wt.Readable.toWeb(a),m=()=>{a.destroy(n.reason)};return n.aborted?m():n.addEventListener("abort",m,{once:!0}),c},Jn=(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(i=>r.push(i));try{return await n()}finally{const i=r.shift();i===void 0?t-=1:i()}}},Wn=(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"},Kn=new Set(["id","label","root","pathPrefix","parse","deny","maxEntries","maxDocumentBytes","textPreviewBytes","walkConcurrency","cacheScope","reportSkipped"]),ke=(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},Vn=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(!Kn.has(b))throw new TypeError(`[markdown-explorer] createFileSystemSource does not know the option ${JSON.stringify(b)}`);const{id:t,label:r,root:n,parse:i}=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 i!="function")throw new TypeError("[markdown-explorer] a file-system source needs a parse function");if(typeof n!="string"||!ne.isAbsolute(n))throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);let a;try{a=ie.statSync(n).isDirectory()}catch(b){throw new RangeError(`[markdown-explorer] root does not exist: ${n}`,{cause:b})}if(!a)throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);const c=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("/")&&pt(m.slice(0,-1))))throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(m)}`);const y=w.resolvePathRules(e.deny),x=ke("maxEntries",e.maxEntries,Te.maxEntries),h=ke("maxDocumentBytes",e.maxDocumentBytes,Te.maxDocumentBytes),g=ke("textPreviewBytes",e.textPreviewBytes,Te.textPreviewBytes),S=ke("walkConcurrency",e.walkConcurrency,Te.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 $=e.reportSkipped;if($!==void 0&&typeof $!="function")throw new TypeError("[markdown-explorer] reportSkipped must be a function");const N=$===void 0?b=>{console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(b.sourceId)} does not list ${JSON.stringify(b.path)}: ${b.reason}`)}:$,_=new Set,C=b=>{const R=ne.resolve(c,...b.split("/")),k=ne.relative(c,R);return k===""||k===".."||k.startsWith(`..${ne.sep}`)||ne.isAbsolute(k)?null:R},v=(b,R)=>{const k=`${R}\0${b}`;_.has(k)||_.size>=x||(_.add(k),N({sourceId:t,path:b,reason:R}))},M=async({signal:b})=>{b.throwIfAborted();const R=new AbortController,k=()=>{R.abort(b.reason)};b.addEventListener("abort",k,{once:!0});const I=Yn(S);let L=0;const X=async(D,G)=>{const Q=await I(async()=>{R.signal.throwIfAborted();try{return await me.readdir(D,{withFileTypes:!0})}catch(B){if(G===""||!Mt(B))throw B;return null}});if(R.signal.throwIfAborted(),Q===null)return v(`${m}${G}`,"unreadable-directory"),null;const J=[];for(const B of Q){if(y.deniesName(B.name))continue;const Z=G===""?B.name:`${G}/${B.name}`,q=`${m}${Z}`,ee=Wn(B,q);if(ee!==null){v(q,ee);continue}J.push({dirent:B,relativePath:Z,path:q})}if(L+=J.length,L>x)throw new ye("too-large");return J.sort((B,Z)=>Jn(B.dirent.name,Z.dirent.name)),(await Promise.all(J.map(async({dirent:B,relativePath:Z,path:q})=>{const ee=await Un(ne.join(D,B.name)),ce=ee===void 0?{}:{modifiedAt:ee};if(!B.isDirectory())return{name:B.name,path:q,type:"file",...ce};const ge=await X(ne.join(D,B.name),Z);return ge===null?null:{name:B.name,path:q,type:"directory",...ce,children:ge}}))).filter(B=>B!==null)};try{const D=await X(c,"");if(D===null)throw new Error("[markdown-explorer] the source's root could not be listed");return D}catch(D){throw R.abort(),D}finally{b.removeEventListener("abort",k)}},H=async b=>{if(!b.startsWith(m))return{status:"refused",reason:"not-found"};const R=b.slice(m.length);if(!pt(R))return{status:"refused",reason:"invalid"};if(y.deniesPath(R))return{status:"refused",reason:"forbidden"};const k=C(R);if(k===null)return{status:"refused",reason:"forbidden"};const I=await me.lstat(k,{bigint:!0});if(I.isSymbolicLink())return{status:"refused",reason:"forbidden"};if(!I.isFile())return{status:"refused",reason:"unsupported"};const L=await me.realpath(k);return L!==k||y.deniesPath(ne.relative(c,L).split(ne.sep).join("/"))?{status:"refused",reason:"forbidden"}:{status:"file",target:k,name:R.slice(R.lastIndexOf("/")+1),stats:I}},U=async(b,R,k)=>{let I;try{const L=await H(k);if(L.status==="refused")return w.failureDocument(L.reason);const{target:X,name:D,stats:G}=L,Q=Fn(D),J=mt(G);if(Q.kind==="image")return{kind:"image",name:D,version:J};if(Q.kind==="media")return{kind:"media",name:D,mediaType:Q.mediaType,version:J};if(Q.kind==="file")return{kind:"file",name:D,version:J};I=await me.open(X,ie.constants.O_RDONLY|vt|Nt);const ae=await I.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 ht(I,h+1);if(ee.length>h)return w.failureDocument("too-large");const ce=await i(new TextDecoder("utf-8").decode(ee),R);return{kind:"markdown",name:D,htmlContent:ce.htmlContent,headings:ce.headings,edit:null}}const B=await ht(I,g);if(B.includes(0))return{kind:"file",name:D,version:J};const Z=ae.size>BigInt(g),q=new TextDecoder("utf-8").decode(B,{stream:Z});return{kind:"text",name:D,text:q,truncated:Z,version:J}}catch(L){const X=je(L);if(X===null)throw L;return w.failureDocument(X)}finally{await I?.close()}},p=async(b,R,k)=>{let I;try{I=await H(k)}catch(J){throw It(J)}if(I.status==="refused")throw new ye(I.reason);const{target:L,name:X,stats:D}=I,G=At.get(Pt(X)),Q=G===void 0?"":G.contentType;return{name:X,contentType:Q,size:Number(D.size),version:mt(D),open:J=>Gn(L,D,J,b.signal)}},E=async(b,R,k)=>{let I;try{I=await H(k)}catch(D){if(je(D)!==null)return null;throw D}if(I.status==="refused")return null;const L=k.slice(m.length).split("/");if(L.some(D=>y.deniesName(D)))return null;const X=L.slice(0,-1);return X.map((D,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:U,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=ye;exports.anonymousAccess=Kt;exports.createFileSystemSource=Vn;exports.createMarkdownExplorer=jn;
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, ExplorerDraft, ExplorerEditPorts, ExplorerHostDocument, ExplorerHostEditSource, ExplorerHostPreview, ExplorerHostSaveResult, ExplorerPageLoaderResult, ExplorerSource, ExplorerSourceBoundary, ExplorerSourceContext, MarkdownExplorerServer, MarkdownExplorerServerConfig, } from "./server/ports.cjs";
6
+ export type { ExplorerAncestorsOptions, ExplorerAssetFile, ExplorerAssetOptions, ExplorerAssetRedirect, 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, ExplorerDraft, ExplorerEditPorts, ExplorerHostDocument, ExplorerHostEditSource, ExplorerHostPreview, ExplorerHostSaveResult, ExplorerPageLoaderResult, ExplorerSource, ExplorerSourceBoundary, ExplorerSourceContext, MarkdownExplorerServer, MarkdownExplorerServerConfig, } from "./server/ports.js";
6
+ export type { ExplorerAncestorsOptions, ExplorerAssetFile, ExplorerAssetOptions, ExplorerAssetRedirect, 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";