@aiquants/markdown-explorer 0.4.0 → 0.6.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 +31 -0
- package/README.md +30 -4
- package/dist/ExplorerSplit-CN5TvRj6.js +1495 -0
- package/dist/ExplorerSplit-CUIbSLQm.cjs +1 -0
- package/dist/MultiLayout-BDcQSpa6.cjs +1 -0
- package/dist/{MultiLayout-8s7q3-Hm.js → MultiLayout-hPmV-bae.js} +69 -66
- package/dist/{NativeScrollBar-DqkutcGb.cjs → NativeScrollBar-CHEQgaVx.cjs} +1 -1
- package/dist/{NativeScrollBar-D3VDRQqf.js → NativeScrollBar-DYEv2GLV.js} +1 -1
- package/dist/TreeLayout-BDaIyoGT.cjs +1 -0
- package/dist/TreeLayout-CqzxLpoM.js +23 -0
- package/dist/core/contracts.d.cts +23 -7
- package/dist/core/contracts.d.ts +23 -7
- package/dist/core/labels.d.cts +4 -0
- package/dist/core/labels.d.ts +4 -0
- package/dist/dataRoute-CUXlMhUJ.cjs +1 -0
- package/dist/{dataRoute-Dl6xmEFs.js → dataRoute-Ce6EIuu4.js} +69 -63
- package/dist/index-B3nShkkt.cjs +3 -0
- package/dist/{index-Dv9lUZqD.js → index-gJp1iXTc.js} +1020 -916
- package/dist/index.cjs +1 -1
- package/dist/index.js +3 -3
- package/dist/{location-CaNtUswk.js → location-CtM94G0O.js} +1 -1
- package/dist/{location-2QZADLiv.cjs → location-FavgY_gB.cjs} +1 -1
- package/dist/sanitizeWorker.cjs +1 -1
- package/dist/sanitizeWorker.js +1 -1
- package/dist/server/errors.d.cts +1 -1
- package/dist/server/errors.d.ts +1 -1
- package/dist/server/ports.d.cts +1 -0
- package/dist/server/ports.d.ts +1 -0
- package/dist/server.cjs +1 -1
- package/dist/server.js +753 -716
- package/dist/styles/markdown-explorer.css +1 -1
- package/docs/behavior/dom-hooks.md +6 -3
- package/docs/behavior/layout.md +6 -0
- package/docs/behavior/localization.md +4 -1
- package/docs/behavior/security.md +11 -4
- package/docs/behavior/url-contract.md +1 -0
- package/package.json +4 -3
- package/dist/ExplorerSplit-rUVsf5i-.cjs +0 -1
- package/dist/ExplorerSplit-uX2ojZe8.js +0 -1479
- package/dist/MultiLayout-ZK2V9nms.cjs +0 -1
- package/dist/TreeLayout-C7ZNnaOr.js +0 -22
- package/dist/TreeLayout-DkTVgxxb.cjs +0 -1
- package/dist/dataRoute-DYjYBiXF.cjs +0 -1
- package/dist/index-CLe6vRXs.cjs +0 -3
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("./index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("./index-B3nShkkt.cjs"),e=require("./storage-Bkb2Axdi.cjs"),E=require("./location-FavgY_gB.cjs"),_=require("./dataRoute-CUXlMhUJ.cjs");exports.DEFAULT_MARKDOWN_EXPLORER_LOCALE=L.DEFAULT_MARKDOWN_EXPLORER_LOCALE;exports.EXPLORER_THEMES=L.EXPLORER_THEMES;exports.MARKDOWN_EXPLORER_LABEL_CATALOGS=L.MARKDOWN_EXPLORER_LABEL_CATALOGS;exports.MARKDOWN_EXPLORER_LABEL_KEYS=L.MARKDOWN_EXPLORER_LABEL_KEYS;exports.MARKDOWN_EXPLORER_LABEL_TEMPLATES=L.MARKDOWN_EXPLORER_LABEL_TEMPLATES;exports.MARKDOWN_EXPLORER_LOCALES=L.MARKDOWN_EXPLORER_LOCALES;exports.MarkdownExplorer=L.MarkdownExplorer;exports.resolveMarkdownExplorerLabels=L.resolveMarkdownExplorerLabels;exports.shouldRevalidateExplorer=L.shouldRevalidateExplorer;exports.clearExplorerStorage=e.clearExplorerStorage;exports.COLUMN_MIN_MEASURE=E.COLUMN_MIN_MEASURE;exports.DEFAULT_TREE_SETTINGS=E.DEFAULT_TREE_SETTINGS;exports.DEFAULT_VIEW_SLUGS=E.DEFAULT_VIEW_SLUGS;exports.EXPAND_ALL_DEPTH_LIMITS=E.EXPAND_ALL_DEPTH_LIMITS;exports.EXPAND_ALL_FOLDER_LIMITS=E.EXPAND_ALL_FOLDER_LIMITS;exports.EXPLORER_DEFAULT_PERCENT=E.EXPLORER_DEFAULT_PERCENT;exports.EXPLORER_MAX_PERCENT=E.EXPLORER_MAX_PERCENT;exports.EXPLORER_MIN_REM=E.EXPLORER_MIN_REM;exports.EXPLORER_MULTI_DEFAULT_PERCENT=E.EXPLORER_MULTI_DEFAULT_PERCENT;exports.GOLDEN_RATIO=E.GOLDEN_RATIO;exports.MULTI_VIEW_COLUMN_LIMITS=E.MULTI_VIEW_COLUMN_LIMITS;exports.MULTI_VIEW_PANEL_LIMITS=E.MULTI_VIEW_PANEL_LIMITS;exports.REVEAL_DOCUMENT_DEPTH_LIMITS=E.REVEAL_DOCUMENT_DEPTH_LIMITS;exports.defineExplorerConfig=E.defineExplorerConfig;exports.explorerHref=E.explorerHref;exports.isExplorerSourceId=E.isExplorerSourceId;exports.resolveExplorerLocation=E.resolveExplorerLocation;exports.withExplorerSources=E.withExplorerSources;exports.DEFAULT_DENIED_PATH_SEGMENTS=_.DEFAULT_DENIED_PATH_SEGMENTS;exports.EXPLORER_FAILURE_REASONS=_.EXPLORER_FAILURE_REASONS;exports.EXPLORER_MAX_HEADINGS=_.EXPLORER_MAX_HEADINGS;exports.MAX_DOCUMENT_PATH_LENGTH=_.MAX_DOCUMENT_PATH_LENGTH;exports.failureDocument=_.failureDocument;exports.failureOf=_.failureOf;exports.isAcceptableDocumentPath=_.isAcceptableDocumentPath;exports.isDeniedPath=_.isDeniedPath;exports.isExplorerChildrenResult=_.isExplorerChildrenResult;exports.isExplorerFailureCode=_.isExplorerFailureCode;exports.isExplorerFailureReason=_.isExplorerFailureReason;
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { l as _, m as s, M as L, n as r, o as e, p as R, q as o, r as A, s as T } from "./index-
|
|
1
|
+
import { l as _, m as s, M as L, n as r, o as e, p as R, q as o, r as A, s as T } from "./index-gJp1iXTc.js";
|
|
2
2
|
import { c as O } from "./storage-DA4ItHzl.js";
|
|
3
|
-
import { J as D, K as P, L as I, M as N, O as S, q as i, o as p, Q as U, s as X, G as x, R as t, T as C, U as f, V as n, e as u, i as c, a as F, w as d } from "./location-
|
|
4
|
-
import { D as H,
|
|
3
|
+
import { J as D, K as P, L as I, M as N, O as S, q as i, o as p, Q as U, s as X, G as x, R as t, T as C, U as f, V as n, e as u, i as c, a as F, w as d } from "./location-CtM94G0O.js";
|
|
4
|
+
import { D as H, G as W, E as m, M as K, t as h, f as V, i as w, u as b, A as v, c as B, b as g } from "./dataRoute-Ce6EIuu4.js";
|
|
5
5
|
export {
|
|
6
6
|
D as COLUMN_MIN_MEASURE,
|
|
7
7
|
H as DEFAULT_DENIED_PATH_SEGMENTS,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { NO_EMBEDS as Q, isEmbedProviderId as ee, EMBED_PROVIDER_IDS as te, isLinkCardSize as re, LINK_CARD_SIZES as ne } from "@aiquants/markdown/embeds";
|
|
2
2
|
import { CONTENT_ALIGNS as b, DEFAULT_MARKDOWN_STYLES as oe } from "@aiquants/markdown/viewer-settings";
|
|
3
|
-
import { a as se, i as A } from "./dataRoute-
|
|
3
|
+
import { a as se, i as A } from "./dataRoute-Ce6EIuu4.js";
|
|
4
4
|
const $ = (e) => {
|
|
5
5
|
if (e === null || typeof e != "object") return !1;
|
|
6
6
|
const t = Object.getPrototypeOf(e);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const _=require("@aiquants/markdown/embeds"),O=require("@aiquants/markdown/viewer-settings"),T=require("./dataRoute-DYjYBiXF.cjs"),R=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},P=new Intl.Collator("en",{numeric:!0,sensitivity:"variant"}),C=Object.freeze({sortMode:"native",folderPlacement:"mixed",selectionMode:"single",doubleClickAction:"recursive",expandIconSize:8,alwaysExpanded:!1,revealDocument:!1,removeRootIndent:!1,lines:!0,expandIcons:!0,directoryIcons:!0,fileIcons:!0}),me=[!0,!1],fe=(e,t)=>t?e.settingOn:e.settingOff,E=(e,t)=>({key:e,labelKey:t,values:me,formatValue:fe,requiresItemSelection:!1}),S=Object.freeze([{key:"sortMode",labelKey:"settingSortMode",values:["native","asc","desc"],formatValue:(e,t)=>t==="native"?e.sortNative:t==="asc"?e.sortAscending:e.sortDescending,requiresItemSelection:!1},{key:"folderPlacement",labelKey:"settingFolderPlacement",values:["mixed","first","last"],formatValue:(e,t)=>t==="mixed"?e.folderPlacementMixed:t==="first"?e.folderPlacementFirst:e.folderPlacementLast,requiresItemSelection:!1},{key:"selectionMode",labelKey:"settingSelectionMode",values:["single","multiple","none"],formatValue:(e,t)=>t==="single"?e.selectionSingle:t==="multiple"?e.selectionMultiple:e.selectionNone,requiresItemSelection:!0},{key:"doubleClickAction",labelKey:"settingDoubleClick",values:["recursive","toggle"],formatValue:(e,t)=>t==="recursive"?e.doubleClickRecursive:e.doubleClickToggle,requiresItemSelection:!1},{key:"expandIconSize",labelKey:"settingExpandIconSize",values:[8,13,5],formatValue:(e,t)=>e.expandIconSizeValue(t),requiresItemSelection:!1},E("alwaysExpanded","settingAlwaysExpanded"),E("revealDocument","settingRevealDocument"),E("removeRootIndent","settingRemoveRootIndent"),E("lines","settingTreeLines"),E("expandIcons","settingExpandIcons"),E("directoryIcons","settingDirectoryIcons"),E("fileIcons","settingFileIcons")]),ue=e=>e?S:S.filter(t=>!t.requiresItemSelection),G=e=>{const t=S.find(r=>r.key===e);if(t===void 0)throw new RangeError(`[markdown-explorer] no tree setting descriptor for ${e}`);return t},ge=(e,t)=>{const r=G(t).values,n=r[(r.indexOf(e[t])+1)%r.length];return{...e,[t]:n}},Ee=(e,t,r)=>G(r).formatValue(e,t[r]),W=2,v=Object.freeze({}),D=(e,t)=>Object.freeze(Object.fromEntries(S.filter(r=>t(r,e[r.key])).map(r=>[r.key,e[r.key]]))),j="directoriesFirst",we=e=>{if(!Object.hasOwn(e,j))return e;const{[j]:t,...r}=e;return Object.hasOwn(r,"folderPlacement")||typeof t!="boolean"?r:{...r,folderPlacement:t?"first":"mixed"}},Se=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return v;const t=e;return t.version!==W||t.settings===null||typeof t.settings!="object"||Array.isArray(t.settings)?v:D(we(t.settings),(r,n)=>r.values.includes(n))},pe=(e,t)=>{const r=D(t,(n,o)=>o!==void 0&&o!==e[n.key]);return Object.keys(r).length===0?e:Object.freeze({...e,...r})},he=(e,t,r,n)=>D({...e,[t]:r},(o,i)=>i!==void 0&&!(o.key===t&&i===n[t])),_e=e=>JSON.stringify({version:W,settings:e}),xe=e=>{const{sortMode:t,folderPlacement:r}=e;if(t==="native"&&r==="mixed")return;const n=t==="desc"?-1:1;return(o,i)=>{if(r!=="mixed"&&o.type!==i.type)return o.type==="directory"==(r==="first")?-1:1;if(t==="native")return 0;const s=P.compare(o.name,i.name);return n*(s!==0?s:P.compare(o.path,i.path))}},f=(1+Math.sqrt(5))/2,Oe=100/f**3,be=100/f**4,z=100/f**2,H=13,ye=16,Te=Object.freeze({gripThickness:5,gripLength:34,barThickness:2,barLength:21}),Re=Object.freeze([89,144,233,377]),Ie=34,Ne=44,Ae=24,Le=1/f,ke=1/f**3,Pe="40ch",Ce=e=>{if(!Number.isFinite(e)||e<=0)throw new RangeError(`[markdown-explorer] rootFontPixels must be a finite number > 0; got ${String(e)}`)},J=e=>(Ce(e),H*e),ve=e=>J(e)*f**2,Me=233,$e=Re[0],V=(e,t)=>{if(!Number.isFinite(t)||t<0)throw new RangeError(`[markdown-explorer] ${e} must be a finite number >= 0; got ${String(t)}`)},De=({trackInlineSize:e,gap:t,minColumnInlineSize:r,logicalColumns:n})=>{if(V("trackInlineSize",e),V("gap",t),!Number.isFinite(r)||r<=0)throw new RangeError(`[markdown-explorer] minColumnInlineSize must be a finite number > 0; got ${String(r)}`);if(!Number.isInteger(n)||n<1)throw new RangeError(`[markdown-explorer] logicalColumns must be a positive integer; got ${String(n)}`);const o=Math.floor((e+t)/(r+t));return Math.min(n,Math.max(1,o))},ze=(e,t)=>{const{trackInlineSize:r,gap:n,minColumnInlineSize:o,logicalColumns:i}=t;if(!([r,n,o].every(Number.isFinite)&&r>0&&n>=0&&o>0))return e;const c=De(t);if(e===null||c===e)return c;const a=Math.min(i,Math.max(1,e));if(c>a){const I=(a+1)*o+a*n+n/f;return r>=I?c:a}return r>=a*o+(a-1)*n?a:c},je=(e,t)=>{if(!(Number.isInteger(e)&&Number.isInteger(t))||t<1||t>e)throw new RangeError(`[markdown-explorer] visible columns must be an integer in 1..${String(e)}; got ${String(t)}`);return Array.from({length:t},(r,n)=>[Math.floor(n*e/t),Math.floor((n+1)*e/t)])},Ve=31536e3,Fe=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,Ue=e=>{if(typeof e!="string"||!Fe.test(e))throw new RangeError(`[markdown-explorer] settingsCookie must be a cookie-name token; got ${JSON.stringify(e)}`)},F=e=>typeof e=="number"&&Number.isFinite(e)&&e>0&&e<=z,Xe=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))return{};const r=e,{treeExplorer:n,multiExplorer:o,style:i,align:s}=r;return{...F(n)?{treeExplorer:n}:{},...F(o)?{multiExplorer:o}:{},...typeof i=="string"&&t.includes(i)?{style:i}:{},...typeof s=="string"&&O.CONTENT_ALIGNS.includes(s)?{align:s}:{}}},Ge=(e,t)=>{if(e!==null)for(const r of e.split(";")){const n=r.indexOf("=");if(!(n<0)&&r.slice(0,n).trim()===t)return r.slice(n+1).trim()}},We=(e,t)=>{if(e===void 0||e==="")return{};try{return Xe(JSON.parse(decodeURIComponent(e)),t)}catch{return{}}},y=100,He=Math.floor(z*y)/y,Je=e=>{const t=r=>Math.min(He,Math.max(1,Math.round(r*y))/y);return encodeURIComponent(JSON.stringify({...e.treeExplorer===void 0?{}:{treeExplorer:t(e.treeExplorer)},...e.multiExplorer===void 0?{}:{multiExplorer:t(e.multiExplorer)},...e.style===void 0?{}:{style:e.style},...e.align===void 0?{}:{align:e.align}}))},qe=(e,t,r)=>`${e}=${Je(t)}; Path=/; Max-Age=${String(Ve)}; SameSite=Lax${r?"; Secure":""}`,M=Object.freeze({tree:"tree",multi:"multi",single:"single"}),q=Object.freeze({default:12,min:1,max:64}),B=Object.freeze({default:4,min:1,max:6}),K=Object.freeze({default:500,min:1,max:1e4}),Z=Object.freeze({default:16,min:1,max:64}),Y=Object.freeze({default:16,min:1,max:64}),Be=/^\/(?:[A-Za-z0-9._~-]+\/)*[A-Za-z0-9._~-]+$/u,Ke=/^[A-Za-z0-9][A-Za-z0-9_-]*$/u,Ze=/^[a-z0-9][a-z0-9-]*$/u,Ye=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/u,U=(e,t)=>{if(typeof t!="string")throw new TypeError(`[markdown-explorer] ${e} must be a string; got ${typeof t}`);if(!Be.test(t)||t.split("/").some(r=>r==="."||r===".."))throw new RangeError(`[markdown-explorer] ${e} must start with "/", have no trailing "/", and use only letters, digits and "._~-" in each segment; got ${JSON.stringify(t)}`)},d=e=>typeof e=="string"?JSON.stringify(e):typeof e=="bigint"?`${String(e)}n`:Object.is(e,-0)?"-0":typeof e=="function"?"a function":Array.isArray(e)?"an array":e!==null&&typeof e=="object"?R(e)?"a plain object":`a non-plain object (${Object.prototype.toString.call(e)})`:String(e),w=(e,t,r)=>{if(t===void 0)return[];if(!R(t))throw new TypeError(`[markdown-explorer] ${e} must be a plain object; got ${d(t)}`);const n=Object.entries(t);for(const[o]of n)if(!r.includes(o))throw new RangeError(`[markdown-explorer] ${e}.${o} is not an option; expected ${r.join(", ")}`);return n.filter(([,o])=>o!==void 0)},Qe=e=>{const t={...M};for(const[r,n]of w("views",e,Object.keys(M)))t[r]=n;for(const[r,n]of Object.entries(t))if(typeof n!="string"||!Ke.test(n))throw new RangeError(`[markdown-explorer] views.${r} must start with a letter or digit and use only letters, digits, "_" and "-"; got ${JSON.stringify(n)}`);return Object.freeze(t)},x=(e,t,r)=>{if(t===void 0)return r.default;if(typeof t!="number"||!Number.isInteger(t)||t<r.min||t>r.max)throw new RangeError(`[markdown-explorer] ${e} must be an integer in ${String(r.min)}..${String(r.max)}; got ${d(t)}`);return t},et=(e,t)=>{const r=new Map(w("embeds",e,["providers","linkCards","linkCardSize"]));if(r.size===0)return _.NO_EMBEDS;const n=r.has("providers")?r.get("providers"):[];if(!Array.isArray(n))throw new RangeError(`[markdown-explorer] embeds.providers must be an array of provider ids; got ${d(n)}`);for(const c of n)if(!_.isEmbedProviderId(c))throw new RangeError(`[markdown-explorer] embeds.providers must hold only ${_.EMBED_PROVIDER_IDS.join(", ")}; got ${d(c)}`);const o=r.has("linkCards")?r.get("linkCards"):!1;if(typeof o!="boolean")throw new RangeError(`[markdown-explorer] embeds.linkCards must be a boolean; got ${d(o)}`);const i={providers:Object.freeze([...new Set(n)]),linkCardEndpoint:o?T.explorerLinkCardEndpoint(t):null};if(!r.has("linkCardSize"))return Object.freeze(i);const s=r.get("linkCardSize");if(!_.isLinkCardSize(s))throw new RangeError(`[markdown-explorer] embeds.linkCardSize must be one of ${_.LINK_CARD_SIZES.join(", ")}; got ${d(s)}`);if(!o)throw new RangeError(`[markdown-explorer] embeds.linkCardSize needs embeds.linkCards: true; got linkCardSize ${d(s)} with linkCards ${d(o)}`);return Object.freeze({...i,linkCardSize:s})},tt=e=>{const t=new Map(w("defaultTreeSettings",e,S.map(n=>n.key)));if(t.size===0)return C;const r={...C};for(const n of S){if(!t.has(n.key))continue;const o=t.get(n.key),i=n.values;if(!i.includes(o))throw new RangeError(`[markdown-explorer] defaultTreeSettings.${n.key} must be one of ${i.map(d).join(", ")}; got ${d(o)}`);r[n.key]=o}return Object.freeze(r)},Q=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the explorer configuration must be an object");U("basePath",e.basePath),U("dataPath",e.dataPath);const t=Qe(e.views);if(new Set([t.tree,t.multi,t.single]).size!==3)throw new RangeError(`[markdown-explorer] the view slugs must differ; got ${JSON.stringify(t)}`);if(e.dataPath===e.basePath)throw new RangeError("[markdown-explorer] dataPath must differ from basePath");if(e.dataPath.startsWith(`${e.basePath}/`)){const a=e.dataPath.slice(e.basePath.length+1).split("/")[0];if(a===t.tree||a===t.multi||a===t.single)throw new RangeError(`[markdown-explorer] dataPath must not start with a view slug under basePath; got ${JSON.stringify(e.dataPath)}`)}Ue(e.settingsCookie);const r=e.iframeHosts??[];if(!Array.isArray(r)||r.some(a=>typeof a!="string"||!Ye.test(a)))throw new RangeError(`[markdown-explorer] iframeHosts must be lowercase host names without scheme, port or path; got ${JSON.stringify(r)}`);const n=Object.fromEntries(w("multiView",e.multiView,["maxPanels","columns"])),o=Object.fromEntries(w("expandAll",e.expandAll,["maxFolders","maxDepth"])),i=Object.fromEntries(w("revealDocument",e.revealDocument,["maxDepth"])),s=e.documentStyles??O.DEFAULT_MARKDOWN_STYLES;if(!Array.isArray(s)||s.length===0)throw new RangeError("[markdown-explorer] documentStyles must be a non-empty array");const c=new Set;for(const a of s){if(a===null||typeof a!="object"||typeof a.name!="string"||a.name.trim()===""||typeof a.className!="string")throw new RangeError("[markdown-explorer] each document style needs a non-blank name and a className string");if(c.has(a.name))throw new RangeError(`[markdown-explorer] document style names must be unique; ${JSON.stringify(a.name)} repeats`);c.add(a.name)}return Object.freeze({basePath:e.basePath,dataPath:e.dataPath,settingsCookie:e.settingsCookie,views:t,multiView:Object.freeze({maxPanels:x("multiView.maxPanels",n.maxPanels,q),columns:x("multiView.columns",n.columns,B)}),expandAll:Object.freeze({maxFolders:x("expandAll.maxFolders",o.maxFolders,K),maxDepth:x("expandAll.maxDepth",o.maxDepth,Z)}),revealDocument:Object.freeze({maxDepth:x("revealDocument.maxDepth",i.maxDepth,Y)}),documentStyles:Object.freeze(s.map(a=>Object.freeze({name:a.name,className:a.className}))),iframeHosts:Object.freeze([...new Set(r)]),embeds:et(e.embeds,e.dataPath),defaultTreeSettings:tt(e.defaultTreeSettings)})},rt=e=>{const t=e.embeds;if(!R(t))throw new TypeError(`[markdown-explorer] config.embeds must be the embeds defineExplorerConfig resolved; got ${d(t)}`);if(Object.hasOwn(t,"linkCards"))throw new RangeError(`[markdown-explorer] config.embeds.linkCards is an option of defineExplorerConfig, not a key of the embeds it resolves; pass the option to defineExplorerConfig (got linkCards ${d(t.linkCards)})`);const{linkCardEndpoint:r,...n}=t,o=Q({...e,embeds:{...n,linkCards:r!==null}});if(o.embeds.linkCardEndpoint!==r)throw new RangeError(`[markdown-explorer] config.embeds.linkCardEndpoint must be ${d(o.embeds.linkCardEndpoint)} (the data route's link-card path) or null; got ${d(r)}`);return o},ee=e=>typeof e=="string"&&Ze.test(e),nt=(e,t)=>{if(e===null||typeof e!="object")throw new TypeError(`[markdown-explorer] withExplorerSources needs the configuration of defineExplorerConfig; got ${d(e)}`);if(!Array.isArray(t)||t.length===0)throw new RangeError(`[markdown-explorer] sourceIds must be a non-empty array; got ${d(t)}`);for(const r of t)if(!ee(r))throw new RangeError(`[markdown-explorer] each source id must use lowercase letters, digits and "-" and start with a letter or digit; got ${d(r)}`);if(new Set(t).size!==t.length)throw new RangeError(`[markdown-explorer] source ids must be unique; got ${JSON.stringify(t)}`);return Object.freeze({...e,sourceIds:Object.freeze([...t])})},ot=e=>e.documentStyles.map(t=>t.name),l=Object.freeze({source:"source",doc:"doc",maximized:"maximized",style:"style",align:"align",showToc:"showToc",showStyle:"showStyle",showAlign:"showAlign",padding:"padding",width:"width",maxWidth:"maxWidth"}),X=".data",te=256,re=/^\d+(?:\.\d+)?$/u,$=/^\d+(?:\.\d+)?(?:px|rem|em|ch|vw|%)$/u,ne=Object.freeze(["showToc","showStyle","showAlign"]),it=e=>{const t=encodeURIComponent(e.replaceAll("%","%25"));return t.endsWith(X)?`${t.slice(0,-X.length)}%2Edata`:t},st=e=>e.replaceAll("%25","%"),oe=e=>{const{sourceIds:t}=e;if(t===void 0)throw new TypeError("[markdown-explorer] the configuration has no source ids; join the server's sources with withExplorerSources(config, sourceIds)");return t},at=(e,t,r)=>{const n=r.getAll(l.source);if(n.length===0)return t;const[o]=n;return n.length>1||o===void 0||o===t||!e.includes(o)?null:o},lt=(e,t)=>{const r=t.get(l.style),n=t.get(l.align);return{...r!==null&&e.documentStyles.some(o=>o.name===r)?{style:r}:{},...n!==null&&O.CONTENT_ALIGNS.includes(n)?{align:n}:{}}},ie=e=>Number.isFinite(e)&&e>=0&&e<=te&&re.test(String(e)),ct=e=>{const t=e.get(l.padding),r=t!==null&&re.test(t)?Number(t):Number.NaN,n=e.get(l.width),o=e.get(l.maxWidth);return{...e.get(l.showToc)==="false"?{showToc:!1}:{},...e.get(l.showStyle)==="false"?{showStyle:!1}:{},...e.get(l.showAlign)==="false"?{showAlign:!1}:{},...ie(r)?{padding:r}:{},...n!==null&&$.test(n)?{width:n}:{},...o!==null&&$.test(o)?{maxWidth:o}:{}}},se=(e,t)=>[...new Set(t.filter(T.isAcceptableDocumentPath))].slice(0,e.multiView.maxPanels),dt=(e,t,r)=>{for(const n of t)ae(n);if(new Set(t).size!==t.length)throw new RangeError(`[markdown-explorer] multi-view documents must each appear once; got ${String(t.length)} with repeats`);if(t.length>e.multiView.maxPanels)throw new RangeError(`[markdown-explorer] the multi view opens at most ${String(e.multiView.maxPanels)} documents; got ${String(t.length)}`);if(r!==null&&!t.includes(r))throw new RangeError(`[markdown-explorer] the maximized document must be one of the open documents; got ${JSON.stringify(r.slice(0,80))}`)},ae=e=>{if(!T.isAcceptableDocumentPath(e))throw new RangeError(`[markdown-explorer] not an acceptable document path: ${JSON.stringify(String(e).slice(0,80))}`);return e},mt=(e,t)=>{if(t.style!==void 0&&!e.documentStyles.some(r=>r.name===t.style))throw new RangeError(`[markdown-explorer] overrides.style must name a configured document style (${e.documentStyles.map(r=>JSON.stringify(r.name)).join(", ")}); got ${JSON.stringify(t.style)}`);if(t.align!==void 0&&!O.CONTENT_ALIGNS.includes(t.align))throw new RangeError(`[markdown-explorer] overrides.align must be one of ${O.CONTENT_ALIGNS.join(", ")}; got ${JSON.stringify(t.align)}`)},ft=e=>{for(const t of ne)if(e[t]!==void 0&&typeof e[t]!="boolean")throw new RangeError(`[markdown-explorer] embed.${t} must be a boolean; got ${JSON.stringify(e[t])}`);if(e.padding!==void 0&&!ie(e.padding))throw new RangeError(`[markdown-explorer] embed.padding must be 0..${String(te)} px in plain decimal digits; got ${String(e.padding)}`);for(const t of["width","maxWidth"]){const r=e[t];if(r!==void 0&&!$.test(r))throw new RangeError(`[markdown-explorer] embed.${t} must be a CSS length in px, rem, em, ch, vw or %; got ${JSON.stringify(r)}`)}},le=(e,t)=>{const r=new URLSearchParams;let n=`${e.basePath}/${e.views[t.view]}`;if(t.view==="multi"){const i=t.docs??[],s=t.maximized??null;dt(e,i,s);for(const c of i)r.append(l.doc,c);s!==null&&r.set(l.maximized,s)}else t.doc!==void 0&&t.doc!==null&&(n+=`/${it(ae(t.doc))}`);if(t.source!==void 0){const i=oe(e);if(!i.includes(t.source))throw new RangeError(`[markdown-explorer] unknown source ${JSON.stringify(t.source)}; expected one of ${i.join(", ")}`);t.source!==i[0]&&r.set(l.source,t.source)}if(t.view!=="multi"&&t.overrides!==void 0&&(mt(e,t.overrides),t.overrides.style!==void 0&&r.set(l.style,t.overrides.style),t.overrides.align!==void 0&&r.set(l.align,t.overrides.align)),t.view==="single"&&t.embed!==void 0){const{embed:i}=t;ft(i);for(const s of ne)i[s]===!1&&r.set(l[s],"false");i.padding!==void 0&&r.set(l.padding,String(i.padding)),i.width!==void 0&&r.set(l.width,i.width),i.maxWidth!==void 0&&r.set(l.maxWidth,i.maxWidth)}const o=r.toString();return o===""?n:`${n}?${o}`},ut=(e,t)=>Object.keys(e.views).find(r=>e.views[r]===t),gt=(e,t,r)=>{const n=oe(e),[o]=n;if(o===void 0)throw new RangeError("[markdown-explorer] the configuration has no source");const i=at(n,o,r),s=i===null?o:i,c=m=>({kind:"redirect",href:le(e,m),location:m}),a=()=>c({view:"tree",source:s,doc:null,overrides:{}});if(t===void 0||t==="")return a();const p=t.indexOf("/"),I=p<0?t:t.slice(0,p),N=p<0?null:t.slice(p+1),u=ut(e,I);if(u===void 0)return a();if(u==="multi"){const m=r.getAll(l.doc),h=se(e,m),A=r.getAll(l.maximized),[L]=A,k=A.length===1&&L!==void 0&&h.includes(L)?L:null;return N===null&&i!==null&&h.length===m.length&&h.every((ce,de)=>ce===m[de])&&(A.length===0||k!==null)?{kind:"location",location:{view:"multi",source:s,docs:h,maximized:k}}:c({view:"multi",source:s,docs:h,maximized:k})}const g=N===null?null:st(N);if(g!==null&&!T.isAcceptableDocumentPath(g))return a();const b=lt(e,r);if(u==="single"){if(g===null)return a();const m=ct(r);return i===null?c({view:u,source:s,doc:g,overrides:b,embed:m}):{kind:"location",location:{view:u,source:s,doc:g,overrides:b,embed:m}}}return i===null?c({view:u,source:s,doc:g,overrides:b}):{kind:"location",location:{view:u,source:s,doc:g,overrides:b}}};exports.ASSUMED_ROOT_FONT_PIXELS=ye;exports.COARSE_TARGET_PIXELS=Ne;exports.COLUMN_MIN_MEASURE=Pe;exports.CONTROL_BLOCK_PIXELS=Ie;exports.DEFAULT_TREE_SETTINGS=C;exports.DEFAULT_VIEW_SLUGS=M;exports.EXPAND_ALL_DEPTH_LIMITS=Z;exports.EXPAND_ALL_FOLDER_LIMITS=K;exports.EXPLORER_DEFAULT_PERCENT=Oe;exports.EXPLORER_MAX_PERCENT=z;exports.EXPLORER_MIN_REM=H;exports.EXPLORER_MULTI_DEFAULT_PERCENT=be;exports.EXPLORER_WIDTH_PERSIST_DELAY_MS=Me;exports.FINE_TARGET_PIXELS=Ae;exports.GOLDEN_RATIO=f;exports.MULTI_VIEW_COLUMN_LIMITS=B;exports.MULTI_VIEW_PANEL_LIMITS=q;exports.NAME_COLLATOR=P;exports.NO_TREE_SETTING_CHANGES=v;exports.PANEL_MAX_BLOCK_RATIO=Le;exports.PANEL_MIN_BLOCK_RATIO=ke;exports.PREFETCH_DWELL_MS=$e;exports.REVEAL_DOCUMENT_DEPTH_LIMITS=Y;exports.SPLIT_HANDLE_PIXELS=Te;exports.advanceTreeSetting=ge;exports.applyTreeSettingChanges=pe;exports.canonicalMultiDocuments=se;exports.columnGroups=je;exports.createEntryComparator=xe;exports.defineExplorerConfig=Q;exports.documentStyleNames=ot;exports.explorerHref=le;exports.explorerMinPixels=J;exports.explorerSheetBelowPixels=ve;exports.formatTreeSettingValue=Ee;exports.isExplorerSourceId=ee;exports.isPlainObject=R;exports.parseViewSettings=We;exports.readCookieValue=Ge;exports.readTreeSettingChanges=Se;exports.recordTreeSettingChange=he;exports.replanVisibleColumns=ze;exports.resolveExplorerLocation=gt;exports.revalidateExplorerConfig=rt;exports.serializeTreeSettingChanges=_e;exports.viewSettingsCookieString=qe;exports.visibleTreeSettingDescriptors=ue;exports.withExplorerSources=nt;
|
|
1
|
+
"use strict";const _=require("@aiquants/markdown/embeds"),O=require("@aiquants/markdown/viewer-settings"),T=require("./dataRoute-CUXlMhUJ.cjs"),R=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},P=new Intl.Collator("en",{numeric:!0,sensitivity:"variant"}),C=Object.freeze({sortMode:"native",folderPlacement:"mixed",selectionMode:"single",doubleClickAction:"recursive",expandIconSize:8,alwaysExpanded:!1,revealDocument:!1,removeRootIndent:!1,lines:!0,expandIcons:!0,directoryIcons:!0,fileIcons:!0}),me=[!0,!1],fe=(e,t)=>t?e.settingOn:e.settingOff,E=(e,t)=>({key:e,labelKey:t,values:me,formatValue:fe,requiresItemSelection:!1}),S=Object.freeze([{key:"sortMode",labelKey:"settingSortMode",values:["native","asc","desc"],formatValue:(e,t)=>t==="native"?e.sortNative:t==="asc"?e.sortAscending:e.sortDescending,requiresItemSelection:!1},{key:"folderPlacement",labelKey:"settingFolderPlacement",values:["mixed","first","last"],formatValue:(e,t)=>t==="mixed"?e.folderPlacementMixed:t==="first"?e.folderPlacementFirst:e.folderPlacementLast,requiresItemSelection:!1},{key:"selectionMode",labelKey:"settingSelectionMode",values:["single","multiple","none"],formatValue:(e,t)=>t==="single"?e.selectionSingle:t==="multiple"?e.selectionMultiple:e.selectionNone,requiresItemSelection:!0},{key:"doubleClickAction",labelKey:"settingDoubleClick",values:["recursive","toggle"],formatValue:(e,t)=>t==="recursive"?e.doubleClickRecursive:e.doubleClickToggle,requiresItemSelection:!1},{key:"expandIconSize",labelKey:"settingExpandIconSize",values:[8,13,5],formatValue:(e,t)=>e.expandIconSizeValue(t),requiresItemSelection:!1},E("alwaysExpanded","settingAlwaysExpanded"),E("revealDocument","settingRevealDocument"),E("removeRootIndent","settingRemoveRootIndent"),E("lines","settingTreeLines"),E("expandIcons","settingExpandIcons"),E("directoryIcons","settingDirectoryIcons"),E("fileIcons","settingFileIcons")]),ue=e=>e?S:S.filter(t=>!t.requiresItemSelection),G=e=>{const t=S.find(r=>r.key===e);if(t===void 0)throw new RangeError(`[markdown-explorer] no tree setting descriptor for ${e}`);return t},ge=(e,t)=>{const r=G(t).values,n=r[(r.indexOf(e[t])+1)%r.length];return{...e,[t]:n}},Ee=(e,t,r)=>G(r).formatValue(e,t[r]),W=2,v=Object.freeze({}),D=(e,t)=>Object.freeze(Object.fromEntries(S.filter(r=>t(r,e[r.key])).map(r=>[r.key,e[r.key]]))),j="directoriesFirst",we=e=>{if(!Object.hasOwn(e,j))return e;const{[j]:t,...r}=e;return Object.hasOwn(r,"folderPlacement")||typeof t!="boolean"?r:{...r,folderPlacement:t?"first":"mixed"}},Se=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return v;const t=e;return t.version!==W||t.settings===null||typeof t.settings!="object"||Array.isArray(t.settings)?v:D(we(t.settings),(r,n)=>r.values.includes(n))},pe=(e,t)=>{const r=D(t,(n,o)=>o!==void 0&&o!==e[n.key]);return Object.keys(r).length===0?e:Object.freeze({...e,...r})},he=(e,t,r,n)=>D({...e,[t]:r},(o,i)=>i!==void 0&&!(o.key===t&&i===n[t])),_e=e=>JSON.stringify({version:W,settings:e}),xe=e=>{const{sortMode:t,folderPlacement:r}=e;if(t==="native"&&r==="mixed")return;const n=t==="desc"?-1:1;return(o,i)=>{if(r!=="mixed"&&o.type!==i.type)return o.type==="directory"==(r==="first")?-1:1;if(t==="native")return 0;const s=P.compare(o.name,i.name);return n*(s!==0?s:P.compare(o.path,i.path))}},f=(1+Math.sqrt(5))/2,Oe=100/f**3,be=100/f**4,z=100/f**2,H=13,ye=16,Te=Object.freeze({gripThickness:5,gripLength:34,barThickness:2,barLength:21}),Re=Object.freeze([89,144,233,377]),Ie=34,Ne=44,Ae=24,Le=1/f,ke=1/f**3,Pe="40ch",Ce=e=>{if(!Number.isFinite(e)||e<=0)throw new RangeError(`[markdown-explorer] rootFontPixels must be a finite number > 0; got ${String(e)}`)},J=e=>(Ce(e),H*e),ve=e=>J(e)*f**2,Me=233,$e=Re[0],V=(e,t)=>{if(!Number.isFinite(t)||t<0)throw new RangeError(`[markdown-explorer] ${e} must be a finite number >= 0; got ${String(t)}`)},De=({trackInlineSize:e,gap:t,minColumnInlineSize:r,logicalColumns:n})=>{if(V("trackInlineSize",e),V("gap",t),!Number.isFinite(r)||r<=0)throw new RangeError(`[markdown-explorer] minColumnInlineSize must be a finite number > 0; got ${String(r)}`);if(!Number.isInteger(n)||n<1)throw new RangeError(`[markdown-explorer] logicalColumns must be a positive integer; got ${String(n)}`);const o=Math.floor((e+t)/(r+t));return Math.min(n,Math.max(1,o))},ze=(e,t)=>{const{trackInlineSize:r,gap:n,minColumnInlineSize:o,logicalColumns:i}=t;if(!([r,n,o].every(Number.isFinite)&&r>0&&n>=0&&o>0))return e;const c=De(t);if(e===null||c===e)return c;const a=Math.min(i,Math.max(1,e));if(c>a){const I=(a+1)*o+a*n+n/f;return r>=I?c:a}return r>=a*o+(a-1)*n?a:c},je=(e,t)=>{if(!(Number.isInteger(e)&&Number.isInteger(t))||t<1||t>e)throw new RangeError(`[markdown-explorer] visible columns must be an integer in 1..${String(e)}; got ${String(t)}`);return Array.from({length:t},(r,n)=>[Math.floor(n*e/t),Math.floor((n+1)*e/t)])},Ve=31536e3,Fe=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,Ue=e=>{if(typeof e!="string"||!Fe.test(e))throw new RangeError(`[markdown-explorer] settingsCookie must be a cookie-name token; got ${JSON.stringify(e)}`)},F=e=>typeof e=="number"&&Number.isFinite(e)&&e>0&&e<=z,Xe=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))return{};const r=e,{treeExplorer:n,multiExplorer:o,style:i,align:s}=r;return{...F(n)?{treeExplorer:n}:{},...F(o)?{multiExplorer:o}:{},...typeof i=="string"&&t.includes(i)?{style:i}:{},...typeof s=="string"&&O.CONTENT_ALIGNS.includes(s)?{align:s}:{}}},Ge=(e,t)=>{if(e!==null)for(const r of e.split(";")){const n=r.indexOf("=");if(!(n<0)&&r.slice(0,n).trim()===t)return r.slice(n+1).trim()}},We=(e,t)=>{if(e===void 0||e==="")return{};try{return Xe(JSON.parse(decodeURIComponent(e)),t)}catch{return{}}},y=100,He=Math.floor(z*y)/y,Je=e=>{const t=r=>Math.min(He,Math.max(1,Math.round(r*y))/y);return encodeURIComponent(JSON.stringify({...e.treeExplorer===void 0?{}:{treeExplorer:t(e.treeExplorer)},...e.multiExplorer===void 0?{}:{multiExplorer:t(e.multiExplorer)},...e.style===void 0?{}:{style:e.style},...e.align===void 0?{}:{align:e.align}}))},qe=(e,t,r)=>`${e}=${Je(t)}; Path=/; Max-Age=${String(Ve)}; SameSite=Lax${r?"; Secure":""}`,M=Object.freeze({tree:"tree",multi:"multi",single:"single"}),q=Object.freeze({default:12,min:1,max:64}),B=Object.freeze({default:4,min:1,max:6}),K=Object.freeze({default:500,min:1,max:1e4}),Z=Object.freeze({default:16,min:1,max:64}),Y=Object.freeze({default:16,min:1,max:64}),Be=/^\/(?:[A-Za-z0-9._~-]+\/)*[A-Za-z0-9._~-]+$/u,Ke=/^[A-Za-z0-9][A-Za-z0-9_-]*$/u,Ze=/^[a-z0-9][a-z0-9-]*$/u,Ye=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/u,U=(e,t)=>{if(typeof t!="string")throw new TypeError(`[markdown-explorer] ${e} must be a string; got ${typeof t}`);if(!Be.test(t)||t.split("/").some(r=>r==="."||r===".."))throw new RangeError(`[markdown-explorer] ${e} must start with "/", have no trailing "/", and use only letters, digits and "._~-" in each segment; got ${JSON.stringify(t)}`)},d=e=>typeof e=="string"?JSON.stringify(e):typeof e=="bigint"?`${String(e)}n`:Object.is(e,-0)?"-0":typeof e=="function"?"a function":Array.isArray(e)?"an array":e!==null&&typeof e=="object"?R(e)?"a plain object":`a non-plain object (${Object.prototype.toString.call(e)})`:String(e),w=(e,t,r)=>{if(t===void 0)return[];if(!R(t))throw new TypeError(`[markdown-explorer] ${e} must be a plain object; got ${d(t)}`);const n=Object.entries(t);for(const[o]of n)if(!r.includes(o))throw new RangeError(`[markdown-explorer] ${e}.${o} is not an option; expected ${r.join(", ")}`);return n.filter(([,o])=>o!==void 0)},Qe=e=>{const t={...M};for(const[r,n]of w("views",e,Object.keys(M)))t[r]=n;for(const[r,n]of Object.entries(t))if(typeof n!="string"||!Ke.test(n))throw new RangeError(`[markdown-explorer] views.${r} must start with a letter or digit and use only letters, digits, "_" and "-"; got ${JSON.stringify(n)}`);return Object.freeze(t)},x=(e,t,r)=>{if(t===void 0)return r.default;if(typeof t!="number"||!Number.isInteger(t)||t<r.min||t>r.max)throw new RangeError(`[markdown-explorer] ${e} must be an integer in ${String(r.min)}..${String(r.max)}; got ${d(t)}`);return t},et=(e,t)=>{const r=new Map(w("embeds",e,["providers","linkCards","linkCardSize"]));if(r.size===0)return _.NO_EMBEDS;const n=r.has("providers")?r.get("providers"):[];if(!Array.isArray(n))throw new RangeError(`[markdown-explorer] embeds.providers must be an array of provider ids; got ${d(n)}`);for(const c of n)if(!_.isEmbedProviderId(c))throw new RangeError(`[markdown-explorer] embeds.providers must hold only ${_.EMBED_PROVIDER_IDS.join(", ")}; got ${d(c)}`);const o=r.has("linkCards")?r.get("linkCards"):!1;if(typeof o!="boolean")throw new RangeError(`[markdown-explorer] embeds.linkCards must be a boolean; got ${d(o)}`);const i={providers:Object.freeze([...new Set(n)]),linkCardEndpoint:o?T.explorerLinkCardEndpoint(t):null};if(!r.has("linkCardSize"))return Object.freeze(i);const s=r.get("linkCardSize");if(!_.isLinkCardSize(s))throw new RangeError(`[markdown-explorer] embeds.linkCardSize must be one of ${_.LINK_CARD_SIZES.join(", ")}; got ${d(s)}`);if(!o)throw new RangeError(`[markdown-explorer] embeds.linkCardSize needs embeds.linkCards: true; got linkCardSize ${d(s)} with linkCards ${d(o)}`);return Object.freeze({...i,linkCardSize:s})},tt=e=>{const t=new Map(w("defaultTreeSettings",e,S.map(n=>n.key)));if(t.size===0)return C;const r={...C};for(const n of S){if(!t.has(n.key))continue;const o=t.get(n.key),i=n.values;if(!i.includes(o))throw new RangeError(`[markdown-explorer] defaultTreeSettings.${n.key} must be one of ${i.map(d).join(", ")}; got ${d(o)}`);r[n.key]=o}return Object.freeze(r)},Q=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the explorer configuration must be an object");U("basePath",e.basePath),U("dataPath",e.dataPath);const t=Qe(e.views);if(new Set([t.tree,t.multi,t.single]).size!==3)throw new RangeError(`[markdown-explorer] the view slugs must differ; got ${JSON.stringify(t)}`);if(e.dataPath===e.basePath)throw new RangeError("[markdown-explorer] dataPath must differ from basePath");if(e.dataPath.startsWith(`${e.basePath}/`)){const a=e.dataPath.slice(e.basePath.length+1).split("/")[0];if(a===t.tree||a===t.multi||a===t.single)throw new RangeError(`[markdown-explorer] dataPath must not start with a view slug under basePath; got ${JSON.stringify(e.dataPath)}`)}Ue(e.settingsCookie);const r=e.iframeHosts??[];if(!Array.isArray(r)||r.some(a=>typeof a!="string"||!Ye.test(a)))throw new RangeError(`[markdown-explorer] iframeHosts must be lowercase host names without scheme, port or path; got ${JSON.stringify(r)}`);const n=Object.fromEntries(w("multiView",e.multiView,["maxPanels","columns"])),o=Object.fromEntries(w("expandAll",e.expandAll,["maxFolders","maxDepth"])),i=Object.fromEntries(w("revealDocument",e.revealDocument,["maxDepth"])),s=e.documentStyles??O.DEFAULT_MARKDOWN_STYLES;if(!Array.isArray(s)||s.length===0)throw new RangeError("[markdown-explorer] documentStyles must be a non-empty array");const c=new Set;for(const a of s){if(a===null||typeof a!="object"||typeof a.name!="string"||a.name.trim()===""||typeof a.className!="string")throw new RangeError("[markdown-explorer] each document style needs a non-blank name and a className string");if(c.has(a.name))throw new RangeError(`[markdown-explorer] document style names must be unique; ${JSON.stringify(a.name)} repeats`);c.add(a.name)}return Object.freeze({basePath:e.basePath,dataPath:e.dataPath,settingsCookie:e.settingsCookie,views:t,multiView:Object.freeze({maxPanels:x("multiView.maxPanels",n.maxPanels,q),columns:x("multiView.columns",n.columns,B)}),expandAll:Object.freeze({maxFolders:x("expandAll.maxFolders",o.maxFolders,K),maxDepth:x("expandAll.maxDepth",o.maxDepth,Z)}),revealDocument:Object.freeze({maxDepth:x("revealDocument.maxDepth",i.maxDepth,Y)}),documentStyles:Object.freeze(s.map(a=>Object.freeze({name:a.name,className:a.className}))),iframeHosts:Object.freeze([...new Set(r)]),embeds:et(e.embeds,e.dataPath),defaultTreeSettings:tt(e.defaultTreeSettings)})},rt=e=>{const t=e.embeds;if(!R(t))throw new TypeError(`[markdown-explorer] config.embeds must be the embeds defineExplorerConfig resolved; got ${d(t)}`);if(Object.hasOwn(t,"linkCards"))throw new RangeError(`[markdown-explorer] config.embeds.linkCards is an option of defineExplorerConfig, not a key of the embeds it resolves; pass the option to defineExplorerConfig (got linkCards ${d(t.linkCards)})`);const{linkCardEndpoint:r,...n}=t,o=Q({...e,embeds:{...n,linkCards:r!==null}});if(o.embeds.linkCardEndpoint!==r)throw new RangeError(`[markdown-explorer] config.embeds.linkCardEndpoint must be ${d(o.embeds.linkCardEndpoint)} (the data route's link-card path) or null; got ${d(r)}`);return o},ee=e=>typeof e=="string"&&Ze.test(e),nt=(e,t)=>{if(e===null||typeof e!="object")throw new TypeError(`[markdown-explorer] withExplorerSources needs the configuration of defineExplorerConfig; got ${d(e)}`);if(!Array.isArray(t)||t.length===0)throw new RangeError(`[markdown-explorer] sourceIds must be a non-empty array; got ${d(t)}`);for(const r of t)if(!ee(r))throw new RangeError(`[markdown-explorer] each source id must use lowercase letters, digits and "-" and start with a letter or digit; got ${d(r)}`);if(new Set(t).size!==t.length)throw new RangeError(`[markdown-explorer] source ids must be unique; got ${JSON.stringify(t)}`);return Object.freeze({...e,sourceIds:Object.freeze([...t])})},ot=e=>e.documentStyles.map(t=>t.name),l=Object.freeze({source:"source",doc:"doc",maximized:"maximized",style:"style",align:"align",showToc:"showToc",showStyle:"showStyle",showAlign:"showAlign",padding:"padding",width:"width",maxWidth:"maxWidth"}),X=".data",te=256,re=/^\d+(?:\.\d+)?$/u,$=/^\d+(?:\.\d+)?(?:px|rem|em|ch|vw|%)$/u,ne=Object.freeze(["showToc","showStyle","showAlign"]),it=e=>{const t=encodeURIComponent(e.replaceAll("%","%25"));return t.endsWith(X)?`${t.slice(0,-X.length)}%2Edata`:t},st=e=>e.replaceAll("%25","%"),oe=e=>{const{sourceIds:t}=e;if(t===void 0)throw new TypeError("[markdown-explorer] the configuration has no source ids; join the server's sources with withExplorerSources(config, sourceIds)");return t},at=(e,t,r)=>{const n=r.getAll(l.source);if(n.length===0)return t;const[o]=n;return n.length>1||o===void 0||o===t||!e.includes(o)?null:o},lt=(e,t)=>{const r=t.get(l.style),n=t.get(l.align);return{...r!==null&&e.documentStyles.some(o=>o.name===r)?{style:r}:{},...n!==null&&O.CONTENT_ALIGNS.includes(n)?{align:n}:{}}},ie=e=>Number.isFinite(e)&&e>=0&&e<=te&&re.test(String(e)),ct=e=>{const t=e.get(l.padding),r=t!==null&&re.test(t)?Number(t):Number.NaN,n=e.get(l.width),o=e.get(l.maxWidth);return{...e.get(l.showToc)==="false"?{showToc:!1}:{},...e.get(l.showStyle)==="false"?{showStyle:!1}:{},...e.get(l.showAlign)==="false"?{showAlign:!1}:{},...ie(r)?{padding:r}:{},...n!==null&&$.test(n)?{width:n}:{},...o!==null&&$.test(o)?{maxWidth:o}:{}}},se=(e,t)=>[...new Set(t.filter(T.isAcceptableDocumentPath))].slice(0,e.multiView.maxPanels),dt=(e,t,r)=>{for(const n of t)ae(n);if(new Set(t).size!==t.length)throw new RangeError(`[markdown-explorer] multi-view documents must each appear once; got ${String(t.length)} with repeats`);if(t.length>e.multiView.maxPanels)throw new RangeError(`[markdown-explorer] the multi view opens at most ${String(e.multiView.maxPanels)} documents; got ${String(t.length)}`);if(r!==null&&!t.includes(r))throw new RangeError(`[markdown-explorer] the maximized document must be one of the open documents; got ${JSON.stringify(r.slice(0,80))}`)},ae=e=>{if(!T.isAcceptableDocumentPath(e))throw new RangeError(`[markdown-explorer] not an acceptable document path: ${JSON.stringify(String(e).slice(0,80))}`);return e},mt=(e,t)=>{if(t.style!==void 0&&!e.documentStyles.some(r=>r.name===t.style))throw new RangeError(`[markdown-explorer] overrides.style must name a configured document style (${e.documentStyles.map(r=>JSON.stringify(r.name)).join(", ")}); got ${JSON.stringify(t.style)}`);if(t.align!==void 0&&!O.CONTENT_ALIGNS.includes(t.align))throw new RangeError(`[markdown-explorer] overrides.align must be one of ${O.CONTENT_ALIGNS.join(", ")}; got ${JSON.stringify(t.align)}`)},ft=e=>{for(const t of ne)if(e[t]!==void 0&&typeof e[t]!="boolean")throw new RangeError(`[markdown-explorer] embed.${t} must be a boolean; got ${JSON.stringify(e[t])}`);if(e.padding!==void 0&&!ie(e.padding))throw new RangeError(`[markdown-explorer] embed.padding must be 0..${String(te)} px in plain decimal digits; got ${String(e.padding)}`);for(const t of["width","maxWidth"]){const r=e[t];if(r!==void 0&&!$.test(r))throw new RangeError(`[markdown-explorer] embed.${t} must be a CSS length in px, rem, em, ch, vw or %; got ${JSON.stringify(r)}`)}},le=(e,t)=>{const r=new URLSearchParams;let n=`${e.basePath}/${e.views[t.view]}`;if(t.view==="multi"){const i=t.docs??[],s=t.maximized??null;dt(e,i,s);for(const c of i)r.append(l.doc,c);s!==null&&r.set(l.maximized,s)}else t.doc!==void 0&&t.doc!==null&&(n+=`/${it(ae(t.doc))}`);if(t.source!==void 0){const i=oe(e);if(!i.includes(t.source))throw new RangeError(`[markdown-explorer] unknown source ${JSON.stringify(t.source)}; expected one of ${i.join(", ")}`);t.source!==i[0]&&r.set(l.source,t.source)}if(t.view!=="multi"&&t.overrides!==void 0&&(mt(e,t.overrides),t.overrides.style!==void 0&&r.set(l.style,t.overrides.style),t.overrides.align!==void 0&&r.set(l.align,t.overrides.align)),t.view==="single"&&t.embed!==void 0){const{embed:i}=t;ft(i);for(const s of ne)i[s]===!1&&r.set(l[s],"false");i.padding!==void 0&&r.set(l.padding,String(i.padding)),i.width!==void 0&&r.set(l.width,i.width),i.maxWidth!==void 0&&r.set(l.maxWidth,i.maxWidth)}const o=r.toString();return o===""?n:`${n}?${o}`},ut=(e,t)=>Object.keys(e.views).find(r=>e.views[r]===t),gt=(e,t,r)=>{const n=oe(e),[o]=n;if(o===void 0)throw new RangeError("[markdown-explorer] the configuration has no source");const i=at(n,o,r),s=i===null?o:i,c=m=>({kind:"redirect",href:le(e,m),location:m}),a=()=>c({view:"tree",source:s,doc:null,overrides:{}});if(t===void 0||t==="")return a();const p=t.indexOf("/"),I=p<0?t:t.slice(0,p),N=p<0?null:t.slice(p+1),u=ut(e,I);if(u===void 0)return a();if(u==="multi"){const m=r.getAll(l.doc),h=se(e,m),A=r.getAll(l.maximized),[L]=A,k=A.length===1&&L!==void 0&&h.includes(L)?L:null;return N===null&&i!==null&&h.length===m.length&&h.every((ce,de)=>ce===m[de])&&(A.length===0||k!==null)?{kind:"location",location:{view:"multi",source:s,docs:h,maximized:k}}:c({view:"multi",source:s,docs:h,maximized:k})}const g=N===null?null:st(N);if(g!==null&&!T.isAcceptableDocumentPath(g))return a();const b=lt(e,r);if(u==="single"){if(g===null)return a();const m=ct(r);return i===null?c({view:u,source:s,doc:g,overrides:b,embed:m}):{kind:"location",location:{view:u,source:s,doc:g,overrides:b,embed:m}}}return i===null?c({view:u,source:s,doc:g,overrides:b}):{kind:"location",location:{view:u,source:s,doc:g,overrides:b}}};exports.ASSUMED_ROOT_FONT_PIXELS=ye;exports.COARSE_TARGET_PIXELS=Ne;exports.COLUMN_MIN_MEASURE=Pe;exports.CONTROL_BLOCK_PIXELS=Ie;exports.DEFAULT_TREE_SETTINGS=C;exports.DEFAULT_VIEW_SLUGS=M;exports.EXPAND_ALL_DEPTH_LIMITS=Z;exports.EXPAND_ALL_FOLDER_LIMITS=K;exports.EXPLORER_DEFAULT_PERCENT=Oe;exports.EXPLORER_MAX_PERCENT=z;exports.EXPLORER_MIN_REM=H;exports.EXPLORER_MULTI_DEFAULT_PERCENT=be;exports.EXPLORER_WIDTH_PERSIST_DELAY_MS=Me;exports.FINE_TARGET_PIXELS=Ae;exports.GOLDEN_RATIO=f;exports.MULTI_VIEW_COLUMN_LIMITS=B;exports.MULTI_VIEW_PANEL_LIMITS=q;exports.NAME_COLLATOR=P;exports.NO_TREE_SETTING_CHANGES=v;exports.PANEL_MAX_BLOCK_RATIO=Le;exports.PANEL_MIN_BLOCK_RATIO=ke;exports.PREFETCH_DWELL_MS=$e;exports.REVEAL_DOCUMENT_DEPTH_LIMITS=Y;exports.SPLIT_HANDLE_PIXELS=Te;exports.advanceTreeSetting=ge;exports.applyTreeSettingChanges=pe;exports.canonicalMultiDocuments=se;exports.columnGroups=je;exports.createEntryComparator=xe;exports.defineExplorerConfig=Q;exports.documentStyleNames=ot;exports.explorerHref=le;exports.explorerMinPixels=J;exports.explorerSheetBelowPixels=ve;exports.formatTreeSettingValue=Ee;exports.isExplorerSourceId=ee;exports.isPlainObject=R;exports.parseViewSettings=We;exports.readCookieValue=Ge;exports.readTreeSettingChanges=Se;exports.recordTreeSettingChange=he;exports.replanVisibleColumns=ze;exports.resolveExplorerLocation=gt;exports.revalidateExplorerConfig=rt;exports.serializeTreeSettingChanges=_e;exports.viewSettingsCookieString=qe;exports.visibleTreeSettingDescriptors=ue;exports.withExplorerSources=nt;
|
package/dist/sanitizeWorker.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const te=require("node:worker_threads"),_=require("parse5"),R=require("@aiquants/markdown/embeds"),S=require("isomorphic-dompurify"),F=require("./dataRoute-DYjYBiXF.cjs"),G=512,re=4096,j=1024,V=Symbol("placement"),$=2,ne=3,se=new Set(["html","head","body"]),b=0,M=1,U=2,W=3,z=4,O=5,k=6,N=7,Q=8,y=9,X=10,w=-1,oe=0,ae=1,ie=2,le=3,ce=4,ue=5,J=6,fe=7,de=t=>{switch(t){case 9:case 10:case 12:case 13:case 32:return oe;case 47:return ae;case 62:return ie;case 61:return le;case 34:return ce;case 39:return ue;default:return J}},Ee=Uint8Array.from({length:128},(t,i)=>de(i)),B=60,q=47,pe=/[\t\n\f\r />="'<]/g,Te=/["<]/g,Ae=/['<]/g,m=-1-U,he=Int8Array.from([[M,y,w,b,b,b,b],[M,y,w,m,m,m,m],[W,y,w,z,U,U,U],[W,y,w,z,m,m,m],[z,N,w,N,O,k,N],[O,O,O,O,Q,O,O],[k,k,k,k,k,Q,k],[M,N,w,N,N,N,N],[M,y,w,m,m,m,m],[M,y,w,m,m,m,m]].flat()),K=t=>t>=65&&t<=90||t>=97&&t<=122,me=(t,i)=>{let u=new Int32Array(X),f=new Int32Array(X),l=0,A=0,n=0;for(;n<t.length;){if(l===0){const E=t.indexOf("<",n);if(E<0)return!1;n=E+1,t.charCodeAt(n)===q&&(n+=1),K(t.charCodeAt(n))&&(u[b]=0,l=1<<b,n+=1);continue}if((l&-230)===0&&n>=A){const E=l===1<<O?Te:l===1<<k?Ae:pe;E.lastIndex=n;const a=E.exec(t);if(a===null)return!1;n=a.index,t.charCodeAt(n)===B&&(A=n+3)}const T=t.charCodeAt(n),g=T<128?Ee[T]:J;let h=0;for(let E=l;E!==0;E&=E-1){const a=31-Math.clz32(E&-E);let r=he[a*fe+g],s=u[a];if(r<w&&(r=-1-r,s+=1,s>i))return!0;if(r===w)continue;const p=1<<r;((h&p)===0||s>f[r])&&(f[r]=s),h|=p}K(T)&&(t.charCodeAt(n-1)===B||t.charCodeAt(n-1)===q&&t.charCodeAt(n-2)===B)&&(h&1<<b)===0&&(f[b]=0,h|=1<<b);const C=u;u=f,f=C,l=h,n+=1}return!1};class L extends Error{status;constructor(i){super(`[markdown-explorer] the nesting guard stopped the parse: ${i}`),this.name="ParseStop",this.status=i}}const ge=(t,i,u,f)=>{if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`[markdown-explorer] the nesting guard's depth limit must be a positive safe integer; got ${String(i)}`);if(!Number.isSafeInteger(u)||u<=0)throw new RangeError(`[markdown-explorer] the nesting guard's node budget must be a positive safe integer; got ${String(u)}`);if(!Number.isSafeInteger(f)||f<=0)throw new RangeError(`[markdown-explorer] the nesting guard's attribute character budget must be a positive safe integer; got ${String(f)}`);if(me(t,j))return{status:"too-many-attributes"};const l=i+$,A=t.length+ne;let n=null,T=0,g=0,h=0,C=0;const E=e=>{if(g+=e,g>u)throw new L("too-many-nodes")},a=e=>{for(const o of e)C+=o.name.length+o.value.length;if(C>f)throw new L("too-many-attribute-characters")},r=(e,o,c,d)=>{const P={node:e,above:null,levels:o,height:0,keepsChildren:c,attributes:d,first:null,next:null,previous:null},ee=e;return ee[V]=P,P},s=e=>{const c=e[V];if(c===void 0)throw new Error("[markdown-explorer] the nesting guard was handed a node it did not create");return c},p=(e,o)=>{let c=o;for(let d=e;d!==null&&c>d.height;d=d.above)d.height=c,c+=d.levels;if(n!==null&&n.height>l)throw new L("too-deep")},D=e=>{const o=e.above;o?.keepsChildren&&(e.previous===null?o.first=e.next:e.previous.next=e.next,e.next!==null&&(e.next.previous=e.previous)),e.above=null,e.next=null,e.previous=null},I=(e,o)=>{if(!_.defaultTreeAdapter.isElementNode(o))return;const c=s(o),d=s(e);D(c),c.above=d,d.keepsChildren&&(c.next=d.first,d.first!==null&&(d.first.previous=c),d.first=c),o.parentNode=e,p(d,c.height+c.levels)},H={..._.defaultTreeAdapter,createDocument:()=>{const e=_.defaultTreeAdapter.createDocument();return n=r(e,0,!1,0),e},createDocumentFragment:()=>{const e=_.defaultTreeAdapter.createDocumentFragment();return r(e,0,!1,0),e},createElement:(e,o,c)=>{if(T+=1,T>A)throw new L("too-many-elements");E(1+c.length),a(c);const d=_.defaultTreeAdapter.createElement(e,o,c);return r(d,1,!(o===_.html.NS.HTML&&se.has(e)),c.length),d},createCommentNode:e=>{if(h+=1,h>re)throw new L("too-many-comments");return E(1),_.defaultTreeAdapter.createCommentNode(e)},setTemplateContent:(e,o)=>{_.defaultTreeAdapter.setTemplateContent(e,o);const c=s(o);c.above=s(e),p(c.above,c.height)},appendChild:I,insertBefore:(e,o)=>I(e,o),detachNode:e=>{_.defaultTreeAdapter.isElementNode(e)&&(D(s(e)),e.parentNode=null)},getFirstChild:e=>{const o=s(e);if(!o.keepsChildren)throw new Error("[markdown-explorer] the nesting guard was asked for the children of a node whose children it does not keep");return o.first===null?null:o.first.node},getChildNodes:()=>{throw new Error("[markdown-explorer] the nesting guard keeps no child lists for source locations")},onItemPop:e=>{const o=s(e);o.keepsChildren=!1,o.first=null},insertText:()=>{},insertTextBefore:()=>{},adoptAttributes:(e,o)=>{E(o.length),a(o);const c=s(e);if(c.attributes+=o.length,c.attributes>j)throw new L("too-many-attributes")}};let v;try{v=_.parse(t,{scriptingEnabled:!1,treeAdapter:H})}catch(e){if(e instanceof L)return{status:e.status};throw e}return{status:"within",depth:s(v).height-$,elements:T,nodes:g}};class Y extends RangeError{constructor(i){super(`[markdown-explorer] the HTML nests deeper than ${String(i)} levels`),this.name="HtmlNestingLimitError"}}const _e=["script","style","noscript","template","form","button","textarea","select","option","object","embed","base","meta","link","frame","frameset"],Se=["srcdoc","formaction"],we=/^(?:(?:https?|mailto|tel):|[^a-z]|[a-z+.-]+(?:[^a-z+.:-]|$))/iu,be=new Set(["left","right","center","justify","start","end"]),Ne=new Set(["h1","h2","h3","h4","h5","h6"]),x=1,Oe=3,ke=7,Re=8,Z=Object.freeze({a:Object.freeze(["target","data-link-kind","data-doc-path","data-doc-exists","data-footnote-ref","data-footnote-backref"]),area:Object.freeze(["target"]),img:Object.freeze(["data-asset-src","data-asset-exists"]),section:Object.freeze(["data-footnotes"]),iframe:Object.freeze(["allow","allowfullscreen","frameborder","referrerpolicy"])}),Le=[...new Set(Object.values(Z).flatMap(t=>t.filter(i=>i.startsWith("data-"))))],Ce=new Set(["src","href","xlink:href"]),Ie=/^data:/iu,ye=Object.freeze({FORBID_TAGS:_e,FORBID_ATTR:Se,ADD_TAGS:["iframe"],ADD_ATTR:(t,i)=>Z[i]?.includes(t)===!0,ADD_URI_SAFE_ATTR:Le,ALLOWED_URI_REGEXP:we,ALLOW_DATA_ATTR:!1}),De=t=>{let i=null;for(const u of t.split(";")){const f=u.indexOf(":");if(f<0||u.slice(0,f).trim().toLowerCase()!=="text-align")continue;const l=u.slice(f+1).trim().toLowerCase();be.has(l)&&(i=l)}return i===null?null:`text-align: ${i}`},Me=t=>t.nodeType===Oe?{kind:"text",text:t.nodeValue??""}:t.nodeType===Re||t.nodeType===ke?{kind:"ignored"}:t.nodeType===x&&t.nodeName.toLowerCase()==="a"?{kind:"link",href:t.getAttribute("href")}:{kind:"element"},Ue=t=>{const i=t.getAttribute("type");return i!==null&&i.trim().toLowerCase()==="checkbox"&&t.hasAttribute("disabled")},xe=(t,i,u)=>{if(S.isSupported!==!0)throw new Error("[markdown-explorer] the HTML sanitizer cannot run in this environment");if(!Number.isSafeInteger(u)||u<=0)throw new RangeError(`[markdown-explorer] the HTML sanitizer's depth limit must be a positive integer; got ${String(u)}`);const f=Object.freeze([...t]);let l=new WeakMap,A=new WeakMap;const n=a=>{const r=a.parentNode===null?void 0:l.get(a.parentNode),s=r===void 0?0:r+1;if(l.set(a,s),a.nodeType===x&&s>u)throw new Y(u)},T=(a,r)=>{if(a.nodeType!==x)return;const s=a;(r.tagName==="input"&&!Ue(s)||r.tagName==="iframe"&&R.allowedFrameUrlOf(s.getAttribute("src")?.trim(),f)===null)&&s.parentNode?.removeChild(s)},g=(a,r)=>{const s=a.nodeName.toLowerCase();if(r.attrName==="style"){const p=De(r.attrValue);p===null?r.keepAttr=!1:r.attrValue=p}else if(r.attrName==="allow"&&s==="iframe"){const p=R.reduceFrameFeatures(r.attrValue);p===null?r.keepAttr=!1:r.attrValue=p}else if(r.attrName==="referrerpolicy"&&s==="iframe"){const p=r.attrValue.trim().toLowerCase();R.EMBED_FRAME_REFERRER_POLICIES.has(p)?r.attrValue=p:r.keepAttr=!1}else r.attrName===R.EMBED_LINK_ATTRIBUTE&&s==="p"?A.set(a,a.getAttribute(R.EMBED_LINK_ATTRIBUTE)):Ce.has(r.attrName)&&Ie.test(r.attrValue)?r.keepAttr=!1:r.attrName==="id"&&Ne.has(s)&&(r.forceKeepAttr=!0)},h=a=>{const r=a.getAttribute("data-asset-src");r!==null&&(a.getAttribute("data-asset-exists")!=="false"&&F.isAcceptableDocumentPath(r)?a.setAttribute("src",F.explorerAssetHref(i,r,null)):a.removeAttribute("src"))},C=a=>{const r=a.parentNode;if(r===null)return;const s=A.get(r);s!=null&&R.placeholderLinkOf(s,[...r.childNodes].map(Me))!==null&&r.setAttribute(R.EMBED_LINK_ATTRIBUTE,s)},E=a=>{if(a.nodeType!==x)return;const r=a,s=r.nodeName.toLowerCase();s==="img"?h(r):s==="a"&&C(r);const p=r.getAttribute("target");if(p===null||p.trim().toLowerCase()==="_self")return;const D=r.getAttribute("rel"),I=new Set(D===null?[]:D.split(/\s+/u).filter(H=>H!==""));I.add("noopener"),I.add("noreferrer"),r.setAttribute("rel",[...I].join(" "))};return a=>{l=new WeakMap,A=new WeakMap,S.addHook("beforeSanitizeElements",n),S.addHook("uponSanitizeElement",T),S.addHook("uponSanitizeAttribute",g),S.addHook("afterSanitizeAttributes",E);try{return S.sanitize(a,ye)}finally{S.removeHook("beforeSanitizeElements",n),S.removeHook("uponSanitizeElement",T),S.removeHook("uponSanitizeAttribute",g),S.removeHook("afterSanitizeAttributes",E)}}},He=t=>{if(t===null||typeof t!="object")return!1;const{id:i,input:u}=t;if(typeof i!="number"||u===null||typeof u!="object")return!1;const{html:f,iframeHosts:l,dataPath:A,maxNodes:n,maxAttributeChars:T,maxSanitizedChars:g}=u;return typeof f=="string"&&Array.isArray(l)&&l.every(h=>typeof h=="string")&&typeof A=="string"&&A!==""&&[n,T,g].every(h=>Number.isSafeInteger(h)&&h>0)},ze=()=>{const t=te.parentPort;if(t===null)throw new Error("[markdown-explorer] the sanitizer worker must run in a worker thread");const i=new Map;t.on("message",u=>{if(!He(u))throw new TypeError("[markdown-explorer] the sanitizer worker received a message that is not a job");const{id:f,input:l}=u;let A;try{if(ge(l.html,G,l.maxNodes,l.maxAttributeChars).status!=="within"){t.postMessage({id:f,output:{status:"too-large"}});return}const n=JSON.stringify([l.iframeHosts,l.dataPath]);let T=i.get(n);T===void 0&&(T=xe(l.iframeHosts,l.dataPath,G),i.set(n,T));const g=T(l.html);A=g.length>l.maxSanitizedChars?{status:"too-large"}:{status:"sanitized",html:g}}catch(n){A=n instanceof Y?{status:"too-large"}:{status:"error",message:n instanceof Error?`${n.name}: ${n.message}`:String(n)}}t.postMessage({id:f,output:A})}),t.postMessage({ready:!0})};ze();
|
|
1
|
+
"use strict";const te=require("node:worker_threads"),_=require("parse5"),R=require("@aiquants/markdown/embeds"),S=require("isomorphic-dompurify"),F=require("./dataRoute-CUXlMhUJ.cjs"),G=512,re=4096,j=1024,V=Symbol("placement"),$=2,ne=3,se=new Set(["html","head","body"]),b=0,M=1,U=2,W=3,z=4,O=5,k=6,N=7,Q=8,y=9,X=10,w=-1,oe=0,ae=1,ie=2,le=3,ce=4,ue=5,J=6,fe=7,de=t=>{switch(t){case 9:case 10:case 12:case 13:case 32:return oe;case 47:return ae;case 62:return ie;case 61:return le;case 34:return ce;case 39:return ue;default:return J}},Ee=Uint8Array.from({length:128},(t,i)=>de(i)),B=60,q=47,pe=/[\t\n\f\r />="'<]/g,Te=/["<]/g,Ae=/['<]/g,m=-1-U,he=Int8Array.from([[M,y,w,b,b,b,b],[M,y,w,m,m,m,m],[W,y,w,z,U,U,U],[W,y,w,z,m,m,m],[z,N,w,N,O,k,N],[O,O,O,O,Q,O,O],[k,k,k,k,k,Q,k],[M,N,w,N,N,N,N],[M,y,w,m,m,m,m],[M,y,w,m,m,m,m]].flat()),K=t=>t>=65&&t<=90||t>=97&&t<=122,me=(t,i)=>{let u=new Int32Array(X),f=new Int32Array(X),l=0,A=0,n=0;for(;n<t.length;){if(l===0){const E=t.indexOf("<",n);if(E<0)return!1;n=E+1,t.charCodeAt(n)===q&&(n+=1),K(t.charCodeAt(n))&&(u[b]=0,l=1<<b,n+=1);continue}if((l&-230)===0&&n>=A){const E=l===1<<O?Te:l===1<<k?Ae:pe;E.lastIndex=n;const a=E.exec(t);if(a===null)return!1;n=a.index,t.charCodeAt(n)===B&&(A=n+3)}const T=t.charCodeAt(n),g=T<128?Ee[T]:J;let h=0;for(let E=l;E!==0;E&=E-1){const a=31-Math.clz32(E&-E);let r=he[a*fe+g],s=u[a];if(r<w&&(r=-1-r,s+=1,s>i))return!0;if(r===w)continue;const p=1<<r;((h&p)===0||s>f[r])&&(f[r]=s),h|=p}K(T)&&(t.charCodeAt(n-1)===B||t.charCodeAt(n-1)===q&&t.charCodeAt(n-2)===B)&&(h&1<<b)===0&&(f[b]=0,h|=1<<b);const C=u;u=f,f=C,l=h,n+=1}return!1};class L extends Error{status;constructor(i){super(`[markdown-explorer] the nesting guard stopped the parse: ${i}`),this.name="ParseStop",this.status=i}}const ge=(t,i,u,f)=>{if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`[markdown-explorer] the nesting guard's depth limit must be a positive safe integer; got ${String(i)}`);if(!Number.isSafeInteger(u)||u<=0)throw new RangeError(`[markdown-explorer] the nesting guard's node budget must be a positive safe integer; got ${String(u)}`);if(!Number.isSafeInteger(f)||f<=0)throw new RangeError(`[markdown-explorer] the nesting guard's attribute character budget must be a positive safe integer; got ${String(f)}`);if(me(t,j))return{status:"too-many-attributes"};const l=i+$,A=t.length+ne;let n=null,T=0,g=0,h=0,C=0;const E=e=>{if(g+=e,g>u)throw new L("too-many-nodes")},a=e=>{for(const o of e)C+=o.name.length+o.value.length;if(C>f)throw new L("too-many-attribute-characters")},r=(e,o,c,d)=>{const P={node:e,above:null,levels:o,height:0,keepsChildren:c,attributes:d,first:null,next:null,previous:null},ee=e;return ee[V]=P,P},s=e=>{const c=e[V];if(c===void 0)throw new Error("[markdown-explorer] the nesting guard was handed a node it did not create");return c},p=(e,o)=>{let c=o;for(let d=e;d!==null&&c>d.height;d=d.above)d.height=c,c+=d.levels;if(n!==null&&n.height>l)throw new L("too-deep")},D=e=>{const o=e.above;o?.keepsChildren&&(e.previous===null?o.first=e.next:e.previous.next=e.next,e.next!==null&&(e.next.previous=e.previous)),e.above=null,e.next=null,e.previous=null},I=(e,o)=>{if(!_.defaultTreeAdapter.isElementNode(o))return;const c=s(o),d=s(e);D(c),c.above=d,d.keepsChildren&&(c.next=d.first,d.first!==null&&(d.first.previous=c),d.first=c),o.parentNode=e,p(d,c.height+c.levels)},H={..._.defaultTreeAdapter,createDocument:()=>{const e=_.defaultTreeAdapter.createDocument();return n=r(e,0,!1,0),e},createDocumentFragment:()=>{const e=_.defaultTreeAdapter.createDocumentFragment();return r(e,0,!1,0),e},createElement:(e,o,c)=>{if(T+=1,T>A)throw new L("too-many-elements");E(1+c.length),a(c);const d=_.defaultTreeAdapter.createElement(e,o,c);return r(d,1,!(o===_.html.NS.HTML&&se.has(e)),c.length),d},createCommentNode:e=>{if(h+=1,h>re)throw new L("too-many-comments");return E(1),_.defaultTreeAdapter.createCommentNode(e)},setTemplateContent:(e,o)=>{_.defaultTreeAdapter.setTemplateContent(e,o);const c=s(o);c.above=s(e),p(c.above,c.height)},appendChild:I,insertBefore:(e,o)=>I(e,o),detachNode:e=>{_.defaultTreeAdapter.isElementNode(e)&&(D(s(e)),e.parentNode=null)},getFirstChild:e=>{const o=s(e);if(!o.keepsChildren)throw new Error("[markdown-explorer] the nesting guard was asked for the children of a node whose children it does not keep");return o.first===null?null:o.first.node},getChildNodes:()=>{throw new Error("[markdown-explorer] the nesting guard keeps no child lists for source locations")},onItemPop:e=>{const o=s(e);o.keepsChildren=!1,o.first=null},insertText:()=>{},insertTextBefore:()=>{},adoptAttributes:(e,o)=>{E(o.length),a(o);const c=s(e);if(c.attributes+=o.length,c.attributes>j)throw new L("too-many-attributes")}};let v;try{v=_.parse(t,{scriptingEnabled:!1,treeAdapter:H})}catch(e){if(e instanceof L)return{status:e.status};throw e}return{status:"within",depth:s(v).height-$,elements:T,nodes:g}};class Y extends RangeError{constructor(i){super(`[markdown-explorer] the HTML nests deeper than ${String(i)} levels`),this.name="HtmlNestingLimitError"}}const _e=["script","style","noscript","template","form","button","textarea","select","option","object","embed","base","meta","link","frame","frameset"],Se=["srcdoc","formaction"],we=/^(?:(?:https?|mailto|tel):|[^a-z]|[a-z+.-]+(?:[^a-z+.:-]|$))/iu,be=new Set(["left","right","center","justify","start","end"]),Ne=new Set(["h1","h2","h3","h4","h5","h6"]),x=1,Oe=3,ke=7,Re=8,Z=Object.freeze({a:Object.freeze(["target","data-link-kind","data-doc-path","data-doc-exists","data-footnote-ref","data-footnote-backref"]),area:Object.freeze(["target"]),img:Object.freeze(["data-asset-src","data-asset-exists"]),section:Object.freeze(["data-footnotes"]),iframe:Object.freeze(["allow","allowfullscreen","frameborder","referrerpolicy"])}),Le=[...new Set(Object.values(Z).flatMap(t=>t.filter(i=>i.startsWith("data-"))))],Ce=new Set(["src","href","xlink:href"]),Ie=/^data:/iu,ye=Object.freeze({FORBID_TAGS:_e,FORBID_ATTR:Se,ADD_TAGS:["iframe"],ADD_ATTR:(t,i)=>Z[i]?.includes(t)===!0,ADD_URI_SAFE_ATTR:Le,ALLOWED_URI_REGEXP:we,ALLOW_DATA_ATTR:!1}),De=t=>{let i=null;for(const u of t.split(";")){const f=u.indexOf(":");if(f<0||u.slice(0,f).trim().toLowerCase()!=="text-align")continue;const l=u.slice(f+1).trim().toLowerCase();be.has(l)&&(i=l)}return i===null?null:`text-align: ${i}`},Me=t=>t.nodeType===Oe?{kind:"text",text:t.nodeValue??""}:t.nodeType===Re||t.nodeType===ke?{kind:"ignored"}:t.nodeType===x&&t.nodeName.toLowerCase()==="a"?{kind:"link",href:t.getAttribute("href")}:{kind:"element"},Ue=t=>{const i=t.getAttribute("type");return i!==null&&i.trim().toLowerCase()==="checkbox"&&t.hasAttribute("disabled")},xe=(t,i,u)=>{if(S.isSupported!==!0)throw new Error("[markdown-explorer] the HTML sanitizer cannot run in this environment");if(!Number.isSafeInteger(u)||u<=0)throw new RangeError(`[markdown-explorer] the HTML sanitizer's depth limit must be a positive integer; got ${String(u)}`);const f=Object.freeze([...t]);let l=new WeakMap,A=new WeakMap;const n=a=>{const r=a.parentNode===null?void 0:l.get(a.parentNode),s=r===void 0?0:r+1;if(l.set(a,s),a.nodeType===x&&s>u)throw new Y(u)},T=(a,r)=>{if(a.nodeType!==x)return;const s=a;(r.tagName==="input"&&!Ue(s)||r.tagName==="iframe"&&R.allowedFrameUrlOf(s.getAttribute("src")?.trim(),f)===null)&&s.parentNode?.removeChild(s)},g=(a,r)=>{const s=a.nodeName.toLowerCase();if(r.attrName==="style"){const p=De(r.attrValue);p===null?r.keepAttr=!1:r.attrValue=p}else if(r.attrName==="allow"&&s==="iframe"){const p=R.reduceFrameFeatures(r.attrValue);p===null?r.keepAttr=!1:r.attrValue=p}else if(r.attrName==="referrerpolicy"&&s==="iframe"){const p=r.attrValue.trim().toLowerCase();R.EMBED_FRAME_REFERRER_POLICIES.has(p)?r.attrValue=p:r.keepAttr=!1}else r.attrName===R.EMBED_LINK_ATTRIBUTE&&s==="p"?A.set(a,a.getAttribute(R.EMBED_LINK_ATTRIBUTE)):Ce.has(r.attrName)&&Ie.test(r.attrValue)?r.keepAttr=!1:r.attrName==="id"&&Ne.has(s)&&(r.forceKeepAttr=!0)},h=a=>{const r=a.getAttribute("data-asset-src");r!==null&&(a.getAttribute("data-asset-exists")!=="false"&&F.isAcceptableDocumentPath(r)?a.setAttribute("src",F.explorerAssetHref(i,r,null)):a.removeAttribute("src"))},C=a=>{const r=a.parentNode;if(r===null)return;const s=A.get(r);s!=null&&R.placeholderLinkOf(s,[...r.childNodes].map(Me))!==null&&r.setAttribute(R.EMBED_LINK_ATTRIBUTE,s)},E=a=>{if(a.nodeType!==x)return;const r=a,s=r.nodeName.toLowerCase();s==="img"?h(r):s==="a"&&C(r);const p=r.getAttribute("target");if(p===null||p.trim().toLowerCase()==="_self")return;const D=r.getAttribute("rel"),I=new Set(D===null?[]:D.split(/\s+/u).filter(H=>H!==""));I.add("noopener"),I.add("noreferrer"),r.setAttribute("rel",[...I].join(" "))};return a=>{l=new WeakMap,A=new WeakMap,S.addHook("beforeSanitizeElements",n),S.addHook("uponSanitizeElement",T),S.addHook("uponSanitizeAttribute",g),S.addHook("afterSanitizeAttributes",E);try{return S.sanitize(a,ye)}finally{S.removeHook("beforeSanitizeElements",n),S.removeHook("uponSanitizeElement",T),S.removeHook("uponSanitizeAttribute",g),S.removeHook("afterSanitizeAttributes",E)}}},He=t=>{if(t===null||typeof t!="object")return!1;const{id:i,input:u}=t;if(typeof i!="number"||u===null||typeof u!="object")return!1;const{html:f,iframeHosts:l,dataPath:A,maxNodes:n,maxAttributeChars:T,maxSanitizedChars:g}=u;return typeof f=="string"&&Array.isArray(l)&&l.every(h=>typeof h=="string")&&typeof A=="string"&&A!==""&&[n,T,g].every(h=>Number.isSafeInteger(h)&&h>0)},ze=()=>{const t=te.parentPort;if(t===null)throw new Error("[markdown-explorer] the sanitizer worker must run in a worker thread");const i=new Map;t.on("message",u=>{if(!He(u))throw new TypeError("[markdown-explorer] the sanitizer worker received a message that is not a job");const{id:f,input:l}=u;let A;try{if(ge(l.html,G,l.maxNodes,l.maxAttributeChars).status!=="within"){t.postMessage({id:f,output:{status:"too-large"}});return}const n=JSON.stringify([l.iframeHosts,l.dataPath]);let T=i.get(n);T===void 0&&(T=xe(l.iframeHosts,l.dataPath,G),i.set(n,T));const g=T(l.html);A=g.length>l.maxSanitizedChars?{status:"too-large"}:{status:"sanitized",html:g}}catch(n){A=n instanceof Y?{status:"too-large"}:{status:"error",message:n instanceof Error?`${n.name}: ${n.message}`:String(n)}}t.postMessage({id:f,output:A})}),t.postMessage({ready:!0})};ze();
|
package/dist/sanitizeWorker.js
CHANGED
|
@@ -2,7 +2,7 @@ import { parentPort as ee } from "node:worker_threads";
|
|
|
2
2
|
import { defaultTreeAdapter as b, parse as te, html as re } from "parse5";
|
|
3
3
|
import { allowedFrameUrlOf as ne, reduceFrameFeatures as oe, EMBED_FRAME_REFERRER_POLICIES as se, EMBED_LINK_ATTRIBUTE as H, placeholderLinkOf as ae } from "@aiquants/markdown/embeds";
|
|
4
4
|
import S from "isomorphic-dompurify";
|
|
5
|
-
import { i as ie, e as ce } from "./dataRoute-
|
|
5
|
+
import { i as ie, e as ce } from "./dataRoute-Ce6EIuu4.js";
|
|
6
6
|
const F = 512, le = 4096, G = 1024, j = /* @__PURE__ */ Symbol("placement"), V = 2, ue = 3, fe = /* @__PURE__ */ new Set(["html", "head", "body"]), w = 0, D = 1, M = 2, W = 3, z = 4, O = 5, k = 6, N = 7, Q = 8, I = 9, $ = 10, _ = -1, de = 0, pe = 1, Ee = 2, me = 3, he = 4, Te = 5, K = 6, Ae = 7, ge = (t) => {
|
|
7
7
|
switch (t) {
|
|
8
8
|
case 9:
|
package/dist/server/errors.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ExplorerFailure, ExplorerFailureReason } from "../core/contracts.cjs";
|
|
2
|
-
export type ExplorerOperation = "authenticate" | "tree" | "children" | "ancestors" | "document" | "notices" | "refresh" | "boundary" | "asset";
|
|
2
|
+
export type ExplorerOperation = "authenticate" | "tree" | "children" | "ancestors" | "reveal" | "document" | "text" | "notices" | "refresh" | "boundary" | "asset";
|
|
3
3
|
export type ExplorerLogDetail = {
|
|
4
4
|
readonly operation: ExplorerOperation;
|
|
5
5
|
readonly sourceId?: string;
|
package/dist/server/errors.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ExplorerFailure, ExplorerFailureReason } from "../core/contracts.js";
|
|
2
|
-
export type ExplorerOperation = "authenticate" | "tree" | "children" | "ancestors" | "document" | "notices" | "refresh" | "boundary" | "asset";
|
|
2
|
+
export type ExplorerOperation = "authenticate" | "tree" | "children" | "ancestors" | "reveal" | "document" | "text" | "notices" | "refresh" | "boundary" | "asset";
|
|
3
3
|
export type ExplorerLogDetail = {
|
|
4
4
|
readonly operation: ExplorerOperation;
|
|
5
5
|
readonly sourceId?: string;
|
package/dist/server/ports.d.cts
CHANGED
|
@@ -101,6 +101,7 @@ export type MarkdownExplorerServerConfig<P> = {
|
|
|
101
101
|
} | false;
|
|
102
102
|
readonly sanitizer?: HtmlSanitizerOptions;
|
|
103
103
|
readonly deferredTimeoutMs?: number;
|
|
104
|
+
readonly textMaxBytes?: number;
|
|
104
105
|
readonly logger?: ExplorerLogger;
|
|
105
106
|
readonly onTreeRefreshed?: (key: string) => void;
|
|
106
107
|
};
|
package/dist/server/ports.d.ts
CHANGED
|
@@ -101,6 +101,7 @@ export type MarkdownExplorerServerConfig<P> = {
|
|
|
101
101
|
} | false;
|
|
102
102
|
readonly sanitizer?: HtmlSanitizerOptions;
|
|
103
103
|
readonly deferredTimeoutMs?: number;
|
|
104
|
+
readonly textMaxBytes?: number;
|
|
104
105
|
readonly logger?: ExplorerLogger;
|
|
105
106
|
readonly onTreeRefreshed?: (key: string) => void;
|
|
106
107
|
};
|
package/dist/server.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("./dataRoute-DYjYBiXF.cjs"),it=require("node:crypto"),xt=require("@aiquants/markdown/server"),Te=require("react-router"),ne=require("./location-2QZADLiv.cjs"),oe=require("node:fs"),te=require("node:path"),xe=require("node:url"),Ot=require("node:worker_threads"),fe=require("node:fs/promises"),kt=require("node:stream");var Oe=typeof document<"u"?document.currentScript:null;const De=Object.freeze({kind:"anonymous"}),Rt=Object.freeze({authenticate:async()=>({status:"signed-in",principal:De}),principalKey:()=>De.kind,signedOutPage:(e,t)=>new Response(null,{status:401,headers:t})}),_t="application/octet-stream",ct="application/pdf",At=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",ct]),ut="default-src 'none'; media-src 'self'; style-src 'unsafe-inline'",Nt=`${ut}; sandbox`,Pt=`${ut}; sandbox allow-same-origin`,ze=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,It=/^[\t\n\r ]+|[\t\n\r ]+$/gu,Pe=/^[\t ]+|[\t ]+$/gu,Mt=e=>{const t=[];let r="",n=0;for(;;){for(;n<e.length&&e[n]!=='"'&&e[n]!==",";)r+=e[n],n+=1;if(n<e.length&&e[n]==='"'){const a=n;for(n+=1;n<e.length&&e[n]!=='"';)n+=e[n]==="\\"?2:1;if(n=Math.min(n+1,e.length),r+=e.slice(a,n),n<e.length)continue}if(t.push(r.replace(Pe,"")),r="",n>=e.length)return t;n+=1}},vt=e=>{const t=e.replace(It,""),r=t.indexOf("/");if(r<0)return null;const n=t.slice(0,r),a=t.indexOf(";",r+1),o=t.slice(r+1,a<0?t.length:a).replace(/[\t\n\r ]+$/u,"");return ze.test(n)&&ze.test(o)?`${n}/${o}`.toLowerCase():null},$t=e=>{let t=null;for(const r of Mt(e)){const n=vt(r);n!==null&&n!=="*/*"&&(t=n)}return t},Lt=/['()*]/gu,jt=e=>encodeURIComponent(e).replace(Lt,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Dt=Object.freeze({"Cache-Control":"private, max-age=60, stale-while-revalidate=600, no-transform",Vary:"Cookie"}),zt=(e,t)=>{const r=$t(e),n=r!==null&&At.has(r),a=n&&(r.startsWith("audio/")||r.startsWith("video/"));return{contentType:r===null?_t:r,inline:n,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`${n?"inline":"attachment"}; filename*=UTF-8''${jt(t)}`,...r===ct?{}:{"Content-Security-Policy":a?Pt:Nt},"Cross-Origin-Resource-Policy":"same-origin"}}},Ct=/^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu,he=Object.freeze({kind:"whole"}),Ce=Object.freeze({kind:"unsatisfiable"}),Ht=(e,t,r)=>{const n=e.get("Range");if(n===null)return he;const a=e.get("If-Range");if(a!==null&&a!==r)return he;const o=Ct.exec(n);if(o===null)return he;const[,i,l,E]=o;if(E!==void 0){const h=Number(E);if(h===0)return Ce;const R=Math.max(0,t-h);return{kind:"partial",range:{offset:R,length:t-R}}}const O=Number(i),f=l===""?Number.POSITIVE_INFINITY:Number(l);return f<O?he:O>=t?Ce:{kind:"partial",range:{offset:O,length:Math.min(f,t-1)-O+1}}},He="W/",Bt=e=>{const t=[];let r=0,n=!1;for(let a=0;a<e.length;a+=1)e[a]==='"'?n=!n:e[a]===","&&!n&&(t.push(e.slice(r,a).replace(Pe,"")),r=a+1);return t.push(e.slice(r).replace(Pe,"")),t},Be=e=>e.startsWith(He)?e.slice(He.length):e,Ft=(e,t)=>{if(e===null)return!1;const r=Bt(e);if(r.length===1&&r[0]==="*")return!0;const n=Be(t);return r.some(a=>Be(a)===n)},Ut=(e,t)=>{let r=t;return e.pipeThrough(new TransformStream({transform:(n,a)=>{const o=n.byteLength>r?n.subarray(0,r):n;r-=o.byteLength,a.enqueue(o),r===0&&a.terminate()},flush:n=>{r>0&&n.error(new RangeError("[markdown-explorer] the asset ended before its declared length"))}}))},ke=async(e,t,r,n,a)=>{if(n!==null&&r.set("Content-Length",String(n)),e.method.toUpperCase()==="HEAD")return new Response(null,{status:t,headers:r});const o=await a();return new Response(n===null?o:Ut(o,n),{status:t,headers:r})},Xt=(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})},Gt=async(e,t,r)=>{const n=`"${t.version}"`,a=zt(t.contentType,t.name),o=new Headers(r);for(const[E,O]of Object.entries({...a.headers,...Dt,ETag:n}))o.set(E,O);if(Ft(e.headers.get("If-None-Match"),n))return new Response(null,{status:304,headers:o});if(o.set("Content-Type",a.contentType),t.size===null)return ke(e,200,o,null,()=>t.open(null));if(t.size===0)return o.set("Content-Length","0"),new Response(null,{status:200,headers:o});o.set("Accept-Ranges","bytes");const i=Ht(e.headers,t.size,n);if(i.kind==="unsatisfiable")return Xt(r,t.size);if(i.kind==="whole")return ke(e,200,o,t.size,()=>t.open(null));const{range:l}=i;return o.set("Content-Range",`bytes ${l.offset}-${l.offset+l.length-1}/${t.size}`),ke(e,206,o,l.length,()=>t.open(l))},Re=(e,t)=>{const r=new AbortController,n=t(AbortSignal.any([e.signal,r.signal]));return new Promise(a=>{let o;const i=setTimeout(()=>{a(e.late),o=setTimeout(()=>r.abort(),e.handOverMs)},e.timeoutMs),l=()=>{clearTimeout(i),clearTimeout(o)};n.then(E=>{l(),a(E)},()=>{l(),a(e.late)})})},Jt=Object.freeze({error:(e,t)=>{console.error(e,t)}}),lt=Symbol.for("@aiquants/markdown-explorer:ExplorerError");class me extends Error{reason;code;constructor(t,r={}){if(!b.isExplorerFailureReason(t))throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${JSON.stringify(t)}`);if(r.code!==void 0&&!b.isExplorerFailureCode(r.code))throw new RangeError(`[markdown-explorer] an ExplorerError code must be 1 to 64 lowercase letters, digits or hyphens; got ${JSON.stringify(r.code)}`);super(`[markdown-explorer] ${t}`,r.cause===void 0?void 0:{cause:r.cause}),this.name="ExplorerError",this.reason=t,this.code=r.code,Object.defineProperty(this,lt,{value:!0})}}const Yt=e=>e instanceof Error&&Object.hasOwn(e,lt)&&b.isExplorerFailureReason(e.reason),Wt=e=>typeof e=="object"&&e!==null&&e.name==="AbortError",Me=(e,t,r)=>{try{e.error(t,r)}catch(n){console.error("[markdown-explorer] the logger threw while reporting a failure",{operation:r.operation,error:n})}},re=(e,t)=>Me(e,`[markdown-explorer] ${t.operation} failed`,t),Kt=(e,t)=>Me(e,`[markdown-explorer] ${t.operation} left out an entry`,t),Vt=(e,t)=>Me(e,`[markdown-explorer] ${t.operation} refused a path the deny rules match`,{...t,error:new RangeError("[markdown-explorer] the path matches a deny rule")}),Fe=(e,t)=>{e===null||typeof e!="object"&&typeof e!="function"||Promise.resolve(e).then(void 0,t)},q=(e,t,r,n)=>Yt(e)?b.failureOf(e.reason,e.code):(Wt(e)||r.aborted||re(n,{...t,error:e}),{reason:"failed"}),Ue=(e,t)=>{if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] a cache ${e} must be a positive integer; got ${String(t)}`)},dt=(e,t)=>{Ue("capacity",e),t!==void 0&&Ue("weight budget",t.max);const r=new Map;let n=0;const a=o=>{const i=r.get(o);i!==void 0&&(r.delete(o),n-=i.weight)};return{get:o=>{const i=r.get(o);if(i!==void 0)return r.delete(o),r.set(o,i),i.value},set:(o,i)=>{a(o);const l=t===void 0?0:t.of(o,i);if(!(t!==void 0&&l>t.max)){r.set(o,{value:i,weight:l}),n+=l;for(const E of r.keys()){if(r.size<=e&&(t===void 0||n<=t.max))break;a(E)}}},delete:a,size:()=>r.size,weight:()=>n}},ft=e=>Math.max(1,e-1),Qt=2147483647,Xe=Object.freeze({status:"aborted"}),ae=(e,t,r)=>{const n=(e.get(t)??0)+r;n===0?e.delete(t):e.set(t,n)},ue=(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)}`)},Zt=e=>e!==null&&typeof e=="object"&&e.ready===!0&&!("id"in e),qt=(e,t)=>e!==null&&typeof e=="object"&&e.id===t&&"output"in e,er=({url:e,size:t,deadlineMs:r,jobsPerScope:n,maxQueuedJobs:a,heapLimits:o})=>{ue("size",t,Number.MAX_SAFE_INTEGER),ue("deadline",r,Qt),ue("jobsPerScope",n,Number.MAX_SAFE_INTEGER),ue("maxQueuedJobs",a,Number.MAX_SAFE_INTEGER),ue("maxOldGenerationSizeMb",o.maxOldGenerationSizeMb,Number.MAX_SAFE_INTEGER),ue("maxYoungGenerationSizeMb",o.maxYoungGenerationSizeMb,Number.MAX_SAFE_INTEGER);const i=Object.freeze({maxOldGenerationSizeMb:o.maxOldGenerationSizeMb,maxYoungGenerationSizeMb:o.maxYoungGenerationSizeMb}),l=new Set,E=[],O=new Map,f=new Map,h=ft(t);let R=0;const A=(u,w)=>{const{job:g}=u;u.timer!==null&&clearTimeout(u.timer),u.timer=null,u.job=null,u.sent=!1,g!==null&&(ae(O,g.scope,-1),ae(f,g.scope,-1),g.settle(w))},v=u=>{const[w]=E.splice(u,1);w?.detach()},_=()=>{let u=-1,w=h,g=Number.POSITIVE_INFINITY;for(const[x,S]of E.entries()){const N=O.get(S.scope)??0,$=f.get(S.scope)??0;(N<w||N===w&&u>=0&&$<g)&&(u=x,w=N,g=$)}return u},k=(u,w)=>{l.has(u)&&(l.delete(u),A(u,w),u.worker.terminate().catch(()=>{}),H())},j=u=>{u.timer=setTimeout(()=>{k(u,{status:"timeout"})},r)},T=(u,w)=>u.sent?{status:"crashed",error:w}:{status:"unavailable",error:w},P=(u,w)=>{u.sent=!0,j(u);try{u.worker.postMessage({id:w.id,input:w.input})}catch(g){A(u,{status:"crashed",error:g}),u.worker.unref()}},C=()=>{const u={worker:new Ot.Worker(e,{resourceLimits:i}),job:null,sent:!1,timer:null,ready:!1};return u.worker.unref(),u.timer=setTimeout(()=>{k(u,{status:"unavailable",error:new Error(`[markdown-explorer] a worker did not start within ${String(r)} ms`)})},r),u.worker.on("message",w=>{if(!u.ready&&Zt(w)){u.ready=!0,u.timer!==null&&clearTimeout(u.timer),u.timer=null,u.job===null?u.worker.unref():P(u,u.job),u.job===null&&H();return}const{job:g}=u;if(g===null||!qt(w,g.id)){k(u,T(u,new Error("[markdown-explorer] a worker sent a message that answers no job")));return}A(u,{status:"done",output:w.output}),u.worker.unref(),H()}),u.worker.on("error",w=>{k(u,T(u,w))}),u.worker.on("messageerror",w=>{k(u,T(u,w))}),u.worker.on("exit",w=>{k(u,T(u,new Error(`[markdown-explorer] a worker exited with code ${String(w)}`)))}),l.add(u),u},H=()=>{for(;;){const u=_(),w=E[u];if(w===void 0)return;let g;for(const S of l)if(S.job===null){g=S;break}if(g===void 0&&l.size<t)try{g=C()}catch(S){v(u),ae(f,w.scope,-1),w.settle({status:"unavailable",error:S});continue}if(g===void 0)return;v(u),ae(O,w.scope,1);const x=g;x.job=w,x.worker.ref(),x.ready&&P(x,w)}};return{run:(u,{scope:w,signal:g})=>new Promise(x=>{if(g.aborted){x(Xe);return}if((f.get(w)??0)>=n){x({status:"refused",limit:"scope"});return}R+=1;const S={id:R,input:u,scope:w,settle:x,detach:()=>{}};E.push(S),ae(f,w,1),H();const N=E.indexOf(S);if(N<0)return;if(E.length>a){v(N),ae(f,w,-1),x({status:"refused",limit:"queue"});return}const $=()=>{const F=E.indexOf(S);F<0||(v(F),ae(f,w,-1),x(Xe))};g.addEventListener("abort",$,{once:!0}),S.detach=()=>{g.removeEventListener("abort",$)}}),workers:()=>l.size}},ve=1024*1024,tr=3e4,rr=4*ve,nr=64*ve,or=3,sr=2,ar=(e,t)=>e+ft(t)+or,ir=4,cr=32,ur=512,lr=64,dr=4096,fr=32,Ge=4096,mr=4,mt=({workerHeapMb:e,maxHtmlBytes:t})=>Math.floor(((e-lr)*ve-t*fr)/dr),pr=({maxHtmlBytes:e})=>e,hr=({maxHtmlBytes:e})=>mr*e,wr=1024,gr=2147483647,Er=64,yr=2**29,br=1024*1024,Sr=64,Je=Object.freeze({status:"rejected",reason:"too-large",cause:null}),_e=Object.freeze({status:"rejected",reason:"failed",cause:null}),ie=(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},Tr=(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:o,workerHeapMb:i,jobsPerScope:l,maxQueuedJobs:E}=e??{},O=ie("workers",r,sr,Er),f=ie("jobsPerScope",l,ar(t,O),Number.MAX_SAFE_INTEGER),h=Object.freeze({workers:O,deadlineMs:ie("deadlineMs",n,tr,gr),maxHtmlBytes:ie("maxHtmlBytes",a,rr,yr),cacheBytes:ie("cacheBytes",o,nr,Number.MAX_SAFE_INTEGER),workerHeapMb:ie("workerHeapMb",i,ur,br),jobsPerScope:f,maxQueuedJobs:ie("maxQueuedJobs",E,ir*f,Number.MAX_SAFE_INTEGER)});if(h.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(h.jobsPerScope)}`);if(h.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(h.maxQueuedJobs)}`);if(mt(h)<Ge)throw new RangeError(`[markdown-explorer] sanitizer.workerHeapMb (${String(h.workerHeapMb)} MiB) must leave room for ${String(Ge)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(h.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`);return h},xr=()=>{const e=typeof document>"u"?require("url").pathToFileURL(__filename).href:Oe&&Oe.tagName.toUpperCase()==="SCRIPT"&&Oe.src||new URL("server.cjs",document.baseURI).href,t=new URL(`./sanitizeWorker${te.extname(xe.fileURLToPath(e))}`,e);if(!oe.existsSync(xe.fileURLToPath(t)))throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${xe.fileURLToPath(t)}`);return t},Ye=new Map,Or=(e,t)=>{const r=[e.href,t.workers,t.deadlineMs,t.workerHeapMb,t.jobsPerScope,t.maxQueuedJobs].map(String).join("\0");let n=Ye.get(r);return n===void 0&&(n=er({url:e,size:t.workers,deadlineMs:t.deadlineMs,jobsPerScope:t.jobsPerScope,maxQueuedJobs:t.maxQueuedJobs,heapLimits:{maxOldGenerationSizeMb:t.workerHeapMb,maxYoungGenerationSizeMb:cr}}),Ye.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"},Rr=e=>e instanceof Error&&e.code==="ERR_WORKER_OUT_OF_MEMORY",_r=({iframeHosts:e,dataPath:t,options:r,pool:n})=>{const a=Object.freeze([...e]),o=mt(r),i=pr(r),l=hr(r),E=dt(wr,{max:r.cacheBytes,of:(_,k)=>2*_.length+(k.status==="sanitized"?2*k.html.length:Sr)}),O=new Map,f=new Map,h=_=>{O.get(_.key)===_&&O.delete(_.key);const k=f.get(_.hash);k?.delete(_),k?.size===0&&f.delete(_.hash)},R=async(_,k,j)=>{const T=await n.run({html:_,iframeHosts:a,dataPath:t,maxNodes:o,maxAttributeChars:i,maxSanitizedChars:l},{scope:k,signal:j});if(T.status==="refused"){const C=T.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(T.status==="aborted")return{outcome:_e,lasting:!1};if(T.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(T.status==="unavailable")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker could not start",{cause:T.error})},lasting:!1};if(T.status==="crashed"&&Rr(T.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:T.error})},lasting:!0};if(T.status==="crashed")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker failed",{cause:T.error})},lasting:!0};const{output:P}=T;return kr(P)?P.status==="too-large"?{outcome:Je,lasting:!0}:P.status==="error"?{outcome:{status:"rejected",reason:"failed",cause:new Error(`[markdown-explorer] the HTML sanitizer failed: ${P.message}`)},lasting:!0}:P.html.length>l?{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer's output of ${String(P.html.length)} characters exceeds its limit of ${String(l)}`)},lasting:!0}:{outcome:{status:"sanitized",html:P.html},lasting:!0}:{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker answered something that is not an outcome")},lasting:!0}},A=(_,k,j,T)=>{let P=()=>{};const C=new Promise(w=>{P=w}),H={hash:k,key:j,outcome:C,answer:P,controller:new AbortController,waiters:0};O.set(j,H);const u=f.get(k);return u===void 0?f.set(k,new Set([H])):u.add(H),R(_,T,H.controller.signal).catch(w=>({outcome:{status:"rejected",reason:"failed",cause:w instanceof Error?w:new Error(String(w))},lasting:!0})).then(({outcome:w,lasting:g})=>{if(h(H),H.answer(w),!g)return;const x=E.get(k),S=x??(w.status==="rejected"?{...w,cause:null}:w);x===void 0&&E.set(k,S);for(const N of f.get(k)??[])h(N),N.answer(S),N.controller.abort()}),H},v=(_,k)=>new Promise(j=>{_.waiters+=1;const T=()=>{_.waiters-=1,j(_e),!(_.waiters>0)&&(h(_),_.controller.abort())};k.addEventListener("abort",T,{once:!0}),_.outcome.then(P=>{k.removeEventListener("abort",T),j(P)})});return(_,{scope:k,signal:j})=>{if(_.length>r.maxHtmlBytes||Buffer.byteLength(_,"utf8")>r.maxHtmlBytes)return Promise.resolve(Je);const T=it.createHash("sha256").update(_,"utf8").digest("base64"),P=E.get(T);if(P!==void 0)return Promise.resolve(P);if(j.aborted)return Promise.resolve(_e);const C=`${T}\0${k}`,H=O.get(C);return v(H===void 0?A(_,T,C,k):H,j)}},Se=e=>({result:e,json:JSON.stringify(e)}),Ae=Object.freeze(Se(Object.freeze({status:"error",failure:Object.freeze({reason:"failed"})}))),Ar=e=>e.status==="ok"&&e.entries.length>0,Nr=({ttlMs:e,maxEntries:t,maxBytes:r,now:n})=>{const a=dt(t,{max:r,of:(f,h)=>2*h.tree.json.length}),o=new Map,i=new Map,l=(f,h)=>{const R=new AbortController,A={waiters:0,superseded:!1,started:!1,loadTree:h},v=i.get(f),_=(C,H)=>{const u=Se(C);return!(A.superseded||R.signal.aborted)&&Ar(C)&&a.set(f,{tree:u,loadedAt:H}),u},j=(async()=>{if(v!==void 0&&await v,R.signal.aborted)return Ae;const C=n();return A.started=!0,_(await A.loadTree(R.signal,C),C)})().finally(()=>{o.get(f)===T&&o.delete(f)}),T={promise:j,controller:R,state:A};o.set(f,T);const P=j.then(()=>{},()=>{});return i.set(f,P),P.then(()=>{i.get(f)===P&&i.delete(f)}),T},E=(f,h,R)=>{h.state.waiters+=1;const A=()=>{h.state.waiters-=1,!(h.state.waiters>0)&&(o.get(f)===h&&o.delete(f),h.controller.abort())};return R.addEventListener("abort",A,{once:!0}),h.promise.finally(()=>{R.removeEventListener("abort",A)})},O=f=>{a.delete(f);const h=o.get(f);h?.state.started&&(h.state.superseded=!0,o.delete(f))};return{load:(f,h,R)=>{if(h.aborted)return Promise.resolve(Ae);const A=a.get(f);if(A!==void 0){if(n()-A.loadedAt<e)return Promise.resolve(A.tree);a.delete(f)}const v=o.get(f);return E(f,v===void 0?l(f,R):v,h)},refresh:(f,h,R)=>{if(h.aborted)return Promise.resolve(Ae);O(f);const A=o.get(f);return A===void 0?E(f,l(f,R),h):(A.state.loadTree=R,E(f,A,h))},forget:O}},Pr=e=>({load:(t,r,n)=>n(r,e()).then(Se),refresh:(t,r,n)=>n(r,e()).then(Se),forget:()=>{}}),L=e=>{throw new TypeError(`[markdown-explorer] ${e}`)},Ir=e=>{if(e===null||typeof e!="object")return null;const{name:t,path:r}=e;return typeof t!="string"||typeof r!="string"?null:t===""?{path:r,reason:"an empty name"}:b.isAcceptableDocumentPath(r)?null:{path:r,reason:"a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)"}},Mr=(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 o of e){if(typeof o!="string"||!b.isAcceptableDocumentPath(o))throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");if(r.deniesPath(o))throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");if(!n(o))throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");if(o===t)throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");if(a.has(o))throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");a.add(o)}return Object.freeze([...a])},vr=(e,t,r,n,a)=>{const o=new Set,i=E=>{if(!Array.isArray(E))return L("a source returned entries that are not an array");const O=[];for(const f of E){const h=l(f);h!==null&&O.push(h)}return O},l=E=>{const O=Ir(E);if(O!==null)return n(O),null;const f=b.entryViolation(E);if(f!==null)return L(f);const h=E;if(o.has(h))return L("a source returned entries that contain themselves");const{name:R,path:A,type:v,mimeType:_,children:k,lazy:j}=h;if(t.deniesName(R)||t.deniesPath(A))return null;if(!a(A))return n({path:A,reason:"a path outside the source's boundary"}),null;const T=_===void 0?{name:R,path:A}:{name:R,path:A,mimeType:_};if(v==="file")return{...T,type:v};if(j===!0)return r?{...T,type:v,lazy:!0,children:[]}:L("a lazy directory came from a source without a children function");if(k===void 0)return{...T,type:v};o.add(h);const P=i(k);return o.delete(h),{...T,type:v,children:P}};return i(e)},$r=/^[\x21\x23-\x7E]{1,256}$/u,pt=e=>typeof e=="string"&&$r.test(e),Lr=new Set(["text","image","media","file"]),jr=e=>typeof e=="string"&&Lr.has(e),Dr=(e,t)=>{if(e!==null&&typeof e=="object"){const a=e,{kind:o}=a;if(jr(o)){if(Object.hasOwn(a,"url"))return L(`a ${o} document carries its version, not a url`);if(typeof a.name!="string")return L("a document needs a name string");if(!pt(a.version))return L(`a ${o} document needs a version of 1 to 256 visible ASCII characters other than '"'`);const i=t(a.version);switch(o){case"image":case"file":return{kind:o,name:a.name,url:i};case"media":{const{mediaType:l}=a;return b.isExplorerMediaType(l)?{kind:o,name:a.name,url:i,mediaType:l}:L(`unknown media type ${typeof l=="string"?JSON.stringify(l.slice(0,64)):typeof l}`)}case"text":return typeof a.text!="string"||typeof a.truncated!="boolean"?L("a text document needs text and truncated"):{kind:o,name:a.name,text:a.text,truncated:a.truncated,url:i}}}}const r=b.documentViolation(e);if(r!==null)return L(r);const n=e;switch(n.kind){case"failure":{const{reason:a,code:o}=n.failure;return{kind:"failure",failure:b.failureOf(a,o)}}case"markdown":return n.headings.length>b.EXPLORER_MAX_HEADINGS?{kind:"failure",failure:b.failureOf("too-large")}:{kind:"unsanitized-markdown",name:n.name,html:n.htmlContent,headings:n.headings.map(({text:a,depth:o,id:i})=>({text:a,depth:o,id:i}))}}},zr=e=>{if(e===null||typeof e!="object")return L("an asset file must be an object");const{name:t,contentType:r,size:n,version:a,open:o}=e;return typeof t!="string"||t===""?L("an asset file needs a non-empty name"):typeof r!="string"?L("an asset file needs a contentType string ('' when unknown)"):n!==null&&!(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)?L("an asset file's size must be null or a non-negative safe integer"):pt(a)?typeof o!="function"?L("an asset file needs an open function"):Object.freeze({name:t,contentType:r,size:n,version:a,open:o}):L(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`)},Cr=e=>Array.isArray(e)?e.map(t=>{if(t===null||typeof t!="object")return L("a notice must be an object");const{id:r,tone:n,title:a,body:o,action:i}=t;if(typeof r!="string"||r===""||typeof a!="string")return L("a notice needs an id and a title");if(!b.isExplorerNoticeTone(n))return L(`unknown notice tone ${typeof n=="string"?JSON.stringify(n.slice(0,64)):typeof n}`);if(o!==void 0&&typeof o!="string")return L("a notice body must be a string");const E={id:r,tone:n,title:a,...o===void 0?{}:{body:o}};if(i===void 0)return E;if(i===null||typeof i!="object")return L("a notice action must be an object");const{label:O,href:f}=i;return typeof O!="string"||!b.isAcceptableUrl(f,b.EXPLORER_LINK_PROTOCOLS)?L("a notice action needs a label and an http(s), mailto or relative href"):{...E,action:{label:O,href:f}}}):L("notices must be an array"),Hr=4e3,we=Object.freeze({ttlMs:3e5,maxEntries:64,maxBytes:64*1024*1024}),We=32,ht="private, no-store",Br=Object.freeze({"Content-Type":"application/json; charset=utf-8","Cache-Control":ht,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; frame-ancestors 'none'; sandbox","Cross-Origin-Resource-Policy":"same-origin"}),Fr=22,Ur=2147483647,Ne=Object.freeze([]),Ke=Object.freeze(["contains","confirm"]),Ve=Object.freeze({readOnly:!1}),Xr=Object.freeze({readOnly:!0}),J=(e,t,r)=>{if(!(r&&t===void 0)&&typeof t!="function")throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${typeof t}`)},be=(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},Gr=e=>{if(e===null||typeof e!="object"||!Object.isFrozen(e))throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");return ne.revalidateExplorerConfig(e)},Qe=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)")}},Ze=e=>e instanceof Response?new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`):e,Jr=e=>{if(typeof e!="string")throw new TypeError(`[markdown-explorer] scopeSecret must be a string; got ${typeof e}`);if(e.length<We)throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(We)} characters; got ${String(e.length)}`);return e},Yr=(e,t)=>{if(!ne.isPlainObject(t))throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);for(const r of Object.keys(t))if(!Ke.includes(r))throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${Ke.join(", ")}`);J(`${e}.boundary.contains`,t.contains,!1),J(`${e}.boundary.confirm`,t.confirm,!0)},Wr=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:o,label:i,boundary:l,tree:E,children:O,ancestors:f,cacheScope:h}=a;if(!ne.isExplorerSourceId(o))throw new RangeError(`[markdown-explorer] sources[${String(n)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${typeof o=="string"?JSON.stringify(o):typeof o}`);const R=`source ${JSON.stringify(o)}`;if(r.has(o))throw new RangeError(`[markdown-explorer] source ids must be unique; ${JSON.stringify(o)} repeats at sources[${String(n)}]`);if(r.add(o),typeof i!="string"&&typeof i!="function")throw new TypeError(`[markdown-explorer] ${R}.label must be a string or a function`);if(typeof i=="string"&&i.trim()==="")throw new RangeError(`[markdown-explorer] ${R}.label must not be blank`);if(Yr(R,l),J(`${R}.tree`,E,!1),J(`${R}.children`,O,!0),J(`${R}.ancestors`,f,!0),h!==void 0&&h!=="principal"&&h!=="shared")throw new RangeError(`[markdown-explorer] ${R}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(h)}`)}return t},Kr=e=>{if(e===!1)return!1;if(e===void 0)return we;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?we.ttlMs:be("treeCache.ttlMs",t,Number.MAX_SAFE_INTEGER),maxEntries:r===void 0?we.maxEntries:be("treeCache.maxEntries",r,Number.MAX_SAFE_INTEGER),maxBytes:n===void 0?we.maxBytes:be("treeCache.maxBytes",n,Number.MAX_SAFE_INTEGER)}},qe=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},et=(e,t)=>{if(!(t instanceof Response))throw new TypeError(`[markdown-explorer] ${e} must return a Response`);return t},tt=(e,t)=>{if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");return it.createHmac("sha256",e).update(t,"utf8").digest("base64url").slice(0,Fr)},Vr=e=>e.view==="multi"?e.docs:e.doc===null?[]:[e.doc],ge=(e,t)=>{const r=e.getAll(t),[n]=r;return r.length===1&&n!==void 0&&n!==""?n:null},ce=(e,t,r,n={})=>{const a=new Headers(r);for(const[o,i]of Object.entries({...Br,...n}))a.set(o,i);return new Response(t,{status:e,headers:a})},U=(e,t,r)=>ce(b.EXPLORER_FAILURE_STATUS[e.reason],JSON.stringify({failure:e}),t,r),rt=(e,t)=>{const r=t==="refresh"?["POST"]:["GET","HEAD"];return r.includes(e.method.toUpperCase())?null:ce(405,JSON.stringify({failure:{reason:"invalid"}}),void 0,{Allow:r.join(", ")})},nt=e=>{if(e.headers.get(b.EXPLORER_REFRESH_HEADER)!==b.EXPLORER_REFRESH_HEADER_VALUE)return!1;const t=e.headers.get("Sec-Fetch-Site");return t===null||t==="same-origin"},Qr=({parentHeaders:e,loaderHeaders:t,errorHeaders:r})=>{const n=new Headers,a=r===void 0?[e,t]:[e,t,r];for(const o of a)for(const[i,l]of o)i!=="set-cookie"&&n.set(i,l);return n},Zr=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the server configuration must be an object");const t=Gr(e.config),r=Jr(e.scopeSecret);J("authenticate",e.authenticate,!1),J("principalKey",e.principalKey,!1),J("document",e.document,!1),J("asset",e.asset,!1),J("signedOutPage",e.signedOutPage,!1),J("forbiddenPage",e.forbiddenPage,!0),J("notices",e.notices,!0),J("onTreeRefreshed",e.onTreeRefreshed,!0);const n=Wr(e.sources),a=ne.withExplorerSources(t,n.map(s=>s.id)),o=e.logger;if(o!==void 0&&(o===null||typeof o!="object"||typeof o.error!="function"))throw new TypeError("[markdown-explorer] logger must be an object with an error function");const i=e.logger===void 0?Jt:e.logger,l=b.resolvePathRules(e.deny),E=e.deferredTimeoutMs===void 0?Hr:be("deferredTimeoutMs",e.deferredTimeoutMs,Ur),O=Kr(e.treeCache),f=()=>Date.now(),h=O===!1?Pr(f):Nr({...O,now:f}),R=Tr(e.sanitizer,t.multiView.maxPanels),A=_r({iframeHosts:t.iframeHosts,dataPath:t.dataPath,options:R,pool:Or(xr(),R)}),v=new Map(n.map(s=>[s.id,s])),_=ne.documentStyleNames(t),{authenticate:k,principalKey:j,signedOutPage:T,forbiddenPage:P,onTreeRefreshed:C}=e,H=(s,m)=>{if(typeof s.label=="string")return s.label;const c=s.label(m);if(typeof c!="string"||c.trim()==="")throw new TypeError(`[markdown-explorer] the label of source ${JSON.stringify(s.id)} must be a non-blank string`);return c},u=(s,m)=>s.cacheScope==="shared"?s.id:`${s.id}\0${m}`,w=(s,m)=>{const c=p=>re(i,{operation:"boundary",sourceId:s.id,path:m,error:p});let d;try{d=s.boundary.contains(m)}catch(p){return c(p),!1}return typeof d=="boolean"?d:(Fe(d,c),c(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(s.id)} must return a boolean; got ${typeof d}`)),!1)},g=async(s,m,c)=>{const{confirm:d}=s.boundary;if(d===void 0)return{status:"inside",readPath:c};let p;try{p=await d(m,c)}catch(V){return{status:"error",failure:q(V,{operation:"boundary",sourceId:s.id,path:c},m.signal,i)}}const y=V=>(re(i,{operation:"boundary",sourceId:s.id,path:c,error:new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(s.id)} ${V}`)}),{status:"outside"});if(p===null||typeof p!="object")return y(`must resolve to { inside, readPath? }; got ${p===null?"null":typeof p}`);const{inside:I,readPath:z}=p;return I===!1?{status:"outside"}:I!==!0||typeof z!="string"?y("must resolve to { inside: false } or { inside: true, readPath: string }"):!b.isAcceptableDocumentPath(z)||l.deniesPath(z)?(re(i,{operation:"boundary",sourceId:s.id,path:c,error:new RangeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(s.id)} answered a readPath the explorer does not serve (unacceptable or denied)`)}),{status:"error",failure:{reason:"failed"}}):{status:"inside",readPath:z}},x=async(s,m)=>{const c=n.filter(p=>w(p,m));if(c.length===0)return{status:"error",failure:{reason:"forbidden"}};if(c.some(p=>p.boundary.confirm===void 0))return{status:"inside",readPath:m};let d=null;for(const p of c){const y=await g(p,s,m);if(y.status==="inside")return y;y.status==="error"&&d===null&&(d=y.failure)}return{status:"error",failure:d===null?{reason:"forbidden"}:d}},S=(s,m,c)=>{const d=({path:p,reason:y})=>Kt(i,{operation:c.operation,sourceId:c.sourceId,path:p,error:new TypeError(`[markdown-explorer] an entry with ${y} was left out`)});try{return{status:"ok",entries:vr(s,l,m.children!==void 0,d,p=>w(m,p))}}catch(p){return re(i,{...c,error:p}),{status:"error",failure:{reason:"failed"}}}},N=async(s,m,c)=>{let d;try{d=await s.tree(m)}catch(y){return{status:"error",failure:q(y,{operation:"tree",sourceId:s.id},m.signal,i)}}const p=S(d,s,{operation:"tree",sourceId:s.id});return p.status==="ok"?{status:"ok",entries:p.entries,loadedAt:c}:p},$=(s,m,c,d)=>(p,y)=>N(s,{principal:m,request:c,signal:p,refresh:d},y),F=(s,m,c,d,p)=>h.load(u(s,c),p,$(s,m,d,!1)),M=(s,m,c,d)=>h.refresh(u(s,c),d.signal,$(s,m,d,!0)),G=(s,m)=>{if(C===void 0)return;const c=d=>re(i,{operation:"refresh",sourceId:s.id,error:d});try{Fe(C(m),c)}catch(d){c(d)}},Y=async(s,m,c,d)=>{if(l.deniesPath(d)||!w(s,d))return{status:"error",failure:{reason:"forbidden"}};const p=await g(s,c,d);if(p.status==="outside")return{status:"error",failure:{reason:"forbidden"}};if(p.status==="error")return{status:"error",failure:p.failure};let y;try{y=await m(c,d,p.readPath)}catch(I){return{status:"error",failure:q(I,{operation:"children",sourceId:s.id,path:d},c.signal,i)}}return S(y,s,{operation:"children",sourceId:s.id,path:d})},X=async(s,m,c,d)=>{if(l.deniesPath(d))return{status:"error",failure:{reason:"forbidden"}};if(!w(s,d))return{status:"ok",ancestors:null};const p=await g(s,c,d);if(p.status==="outside")return{status:"ok",ancestors:null};if(p.status==="error")return{status:"error",failure:p.failure};let y;try{y=await m(c,d,p.readPath,{maxDepth:t.revealDocument.maxDepth})}catch(I){return{status:"error",failure:q(I,{operation:"ancestors",sourceId:s.id,path:d},c.signal,i)}}if(Array.isArray(y)&&y.length>t.revealDocument.maxDepth)return{status:"ok",ancestors:null};try{return{status:"ok",ancestors:Mr(y,d,l,I=>w(s,I))}}catch(I){return re(i,{operation:"ancestors",sourceId:s.id,path:d,error:I}),{status:"error",failure:{reason:"failed"}}}},ee=async(s,m,c)=>{if(l.deniesPath(c))return b.failureDocument("forbidden");const d=await x(s,c);if(d.status==="error")return{kind:"failure",failure:d.failure};let p;try{p=await e.document(s,c,d.readPath)}catch(z){return{kind:"failure",failure:q(z,{operation:"document",path:c},s.signal,i)}}let y;try{y=Dr(p,z=>b.explorerAssetHref(t.dataPath,c,z))}catch(z){return re(i,{operation:"document",path:c,error:z}),b.failureDocument("failed")}if(y.kind!=="unsanitized-markdown")return y;const I=await A(y.html,{scope:m,signal:s.signal});return I.status==="sanitized"?{kind:"markdown",name:y.name,htmlContent:I.html,headings:y.headings}:(I.cause!==null&&re(i,{operation:"document",path:c,error:I.cause}),b.failureDocument(I.reason))},D=async s=>{if(e.notices===void 0)return Ne;try{return Cr(await e.notices(s))}catch(m){return q(m,{operation:"notices"},s.signal,i),Ne}},W=async(s,m,c)=>{const d=ge(m,b.EXPLORER_DATA_QUERY.path);if(d===null||!b.isAcceptableDocumentPath(d))return U({reason:"invalid"},c);if(l.deniesPath(d))return Vt(i,{operation:"asset",path:d}),U({reason:"forbidden"},c);const p=await x(s,d);if(p.status==="error")return U(p.failure,c);try{const y=zr(await e.asset(s,d,p.readPath));return await Gt(s.request,y,c)}catch(y){return U(q(y,{operation:"asset",path:d},s.signal,i),c)}},Z=async({request:s,url:m,params:c})=>{const d=qe(await k(s,Ve)),p=Qe(d.headers);if(p.set("Cache-Control",ht),d.status==="signed-out")throw et("signedOutPage",T(s,p));if(d.status==="forbidden")throw P===void 0?Te.data(null,{status:403,headers:p}):et("forbiddenPage",P(s,p));const y=ne.resolveExplorerLocation(a,c["*"],m.searchParams);if(y.kind==="redirect")throw Te.redirect(y.href,{headers:p});const{location:I}=y,{principal:z}=d,V=tt(r,j(z)),le=v.get(I.source);if(le===void 0)throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(I.source)}`);const de={signal:s.signal,timeoutMs:E,late:null,handOverMs:E},se={scope:V,sources:n.map(B=>({id:B.id,label:H(B,z)})),settings:ne.parseViewSettings(ne.readCookieValue(s.headers.get("Cookie"),t.settingsCookie),_),tree:I.view==="single"?null:{sourceId:I.source,result:Re(de,B=>F(le,z,V,s,B).then(Q=>Q.result))},documents:Vr(I).map(B=>({path:B,document:Re(de,Q=>ee({principal:z,request:s,signal:Q,refresh:!1},V,B))})),notices:Re({signal:s.signal,timeoutMs:E,late:Ne,handOverMs:0},B=>D({principal:z,request:s,signal:B,refresh:!1}))};return Te.data(se,{headers:p})},K=async(s,m)=>{const c=qe(await k(s,m));return{authentication:c,headers:Qe(c.headers)}},pe=async(s,m,c)=>{let d;try{d=await K(m,Ve)}catch(Q){return U(q(Ze(Q),{operation:"authenticate"},m.signal,i))}const{authentication:p,headers:y}=d;if(p.status==="signed-out")return U({reason:"unauthorized"},y);if(p.status==="forbidden")return U({reason:"forbidden"},y);const{principal:I}=p;if(s==="asset")return W({principal:I,request:m,signal:m.signal,refresh:!1},c,y);const z=tt(r,j(I));y.set(b.EXPLORER_SCOPE_HEADER,z);const V={principal:I,request:m,signal:m.signal,refresh:!1},le=()=>U({reason:"invalid"},y);if(s==="document"){const Q=ge(c,b.EXPLORER_DATA_QUERY.path);if(Q===null||!b.isAcceptableDocumentPath(Q))return le();const je=m.headers.has(b.EXPLORER_REFRESH_HEADER);return je&&!nt(m)?U({reason:"forbidden"},y):ce(200,JSON.stringify(await ee({...V,refresh:je},z,Q)),y)}const de=ge(c,b.EXPLORER_DATA_QUERY.source),se=ge(c,b.EXPLORER_DATA_QUERY.path);if(de===null||(s==="children"||s==="ancestors")&&(se===null||!b.isAcceptableDocumentPath(se)))return le();const B=v.get(de);if(B===void 0)return U({reason:"not-found"},y);if(s==="tree")return ce(200,(await F(B,I,z,m,m.signal)).json,y);if(s==="refresh"){const Q=await M(B,I,z,m);return m.signal.aborted||G(B,u(B,z)),ce(200,Q.json,y)}return s==="ancestors"?B.ancestors===void 0||se===null?U({reason:"not-found"},y):ce(200,JSON.stringify(await X(B,B.ancestors,V,se)),y):B.children===void 0||se===null?U({reason:"not-found"},y):ce(200,JSON.stringify(await Y(B,B.children,V,se)),y)},St=async s=>{const{authentication:m,headers:c}=await K(s,Xr);if(!c.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 m.status==="signed-in"},$e=t.embeds.linkCardEndpoint===null?null:xt.createLinkCardHandler({authorize:St}),Tt=async(s,m)=>{try{return await s(m)}catch(c){return U(q(Ze(c),{operation:"authenticate"},m.signal,i))}},Le=async(s,m,c)=>{if(new URL(s.url).pathname.endsWith(".data"))return U({reason:"not-found"});if(!b.isExplorerDataOperation(c))return U({reason:"not-found"});if(c==="link-card"){if($e===null)return U({reason:"not-found"});const p=rt(s,c);return p!==null?p:Tt($e,s)}const d=rt(s,c);if(d!==null)return d;if(c==="refresh"&&!nt(s))return U({reason:"forbidden"});try{return await pe(c,s,m.searchParams)}catch(p){return U(q(p,{operation:c},s.signal,i))}};return Object.freeze({loader:Z,headers:Qr,dataLoader:({request:s,url:m,params:c})=>Le(s,m,c["*"]),dataAction:({request:s,url:m,params:c})=>Le(s,m,c["*"]),forgetTree:s=>{if(typeof s!="string")throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof s}`);h.forget(s)}})},Ee=Object.freeze({maxEntries:2e4,maxDocumentBytes:2*1024*1024,textPreviewBytes:8*1024,walkConcurrency:8}),qr=new Set(["md","markdown","mdx"]),wt=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"}]]),en=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"]),tn=new Set(["readme","license","licence","copying","notice","authors","contributors","changelog","changes","todo","makefile","dockerfile","containerfile","procfile","gemfile","rakefile","vagrantfile","jenkinsfile","brewfile","codeowners"]),gt=typeof oe.constants.O_NOFOLLOW=="number"?oe.constants.O_NOFOLLOW:0,Et=typeof oe.constants.O_NONBLOCK=="number"?oe.constants.O_NONBLOCK:0,ot=e=>`${e.size}-${e.mtimeNs}`,rn=e=>e!==""&&e!=="."&&e!==".."&&!e.includes(":")&&!e.endsWith(".")&&!e.endsWith(" "),st=e=>b.isAcceptableDocumentPath(e)&&e===e.normalize("NFC")&&e.split("/").every(rn),yt=e=>{const t=e.toLowerCase(),r=t.lastIndexOf(".");return r<0?"":t.slice(r+1)},nn=e=>{const t=yt(e);if(qr.has(t))return{kind:"markdown"};const r=wt.get(t);if(r!==void 0)return r.kind==="image"?{kind:"image"}:{kind:"media",mediaType:r.mediaType};const n=e.toLowerCase();return en.has(t)||!n.includes(".")&&tn.has(n)?{kind:"text"}:{kind:"file"}},Ie=e=>{switch(typeof e=="object"&&e!==null?e.code:void 0){case"ENOENT":case"ENOTDIR":return"not-found";case"ELOOP":case"EACCES":case"EPERM":return"forbidden";case"ENAMETOOLONG":return"invalid";case"EISDIR":return"unsupported";default:return null}},bt=e=>{const t=Ie(e);return t===null?e:new me(t)},on=e=>{const t=typeof e=="object"&&e!==null?e.code:void 0;return t==="EACCES"||t==="EPERM"||t==="ENOENT"||t==="ENOTDIR"},at=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)},sn=(e,t)=>e!==null?{start:e.offset,end:e.offset+e.length-1}:t===0n?{}:{start:0,end:Number(t)-1},an=async(e,t,r,n)=>{let a;try{a=await fe.open(e,oe.constants.O_RDONLY|gt|Et);const E=await a.stat({bigint:!0});if(!E.isFile()||E.ino!==t.ino||E.dev!==t.dev||E.size!==t.size||E.mtimeNs!==t.mtimeNs)throw new me("not-found")}catch(E){throw await a?.close(),bt(E)}const o=a.createReadStream(sn(r,t.size)),i=kt.Readable.toWeb(o),l=()=>{o.destroy(n.reason)};return n.aborted?l():n.addEventListener("abort",l,{once:!0}),i},cn=(e,t)=>{const r=ne.NAME_COLLATOR.compare(e,t);return r!==0?r:e===t?0:e<t?-1:1},un=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()}}},ln=(e,t)=>{if(e.isSymbolicLink())return"symbolic-link";if(!(e.isDirectory()||e.isFile()))return"special-file";const{name:r}=e;return r!==r.normalize("NFC")?"not-nfc":r.includes(":")?"colon":r.endsWith(".")||r.endsWith(" ")?"trailing-dot-or-space":b.isAcceptableDocumentPath(r)?b.isAcceptableDocumentPath(t)?null:"path-too-long":"control-character-or-backslash"},dn=new Set(["id","label","root","pathPrefix","parse","deny","maxEntries","maxDocumentBytes","textPreviewBytes","walkConcurrency","cacheScope","reportSkipped"]),ye=(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},fn=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] createFileSystemSource needs an options object");for(const g of Object.keys(e))if(!dn.has(g))throw new TypeError(`[markdown-explorer] createFileSystemSource does not know the option ${JSON.stringify(g)}`);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"||!te.isAbsolute(n))throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);let o;try{o=oe.statSync(n).isDirectory()}catch(g){throw new RangeError(`[markdown-explorer] root does not exist: ${n}`,{cause:g})}if(!o)throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);const i=oe.realpathSync(n),l=e.pathPrefix;if(typeof l!="string")throw new TypeError('[markdown-explorer] pathPrefix is required: "" for a source over the whole root, or relative segments ending with "/"');if(l!==""&&!(l.endsWith("/")&&st(l.slice(0,-1))))throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(l)}`);const E=b.resolvePathRules(e.deny),O=ye("maxEntries",e.maxEntries,Ee.maxEntries),f=ye("maxDocumentBytes",e.maxDocumentBytes,Ee.maxDocumentBytes),h=ye("textPreviewBytes",e.textPreviewBytes,Ee.textPreviewBytes),R=ye("walkConcurrency",e.walkConcurrency,Ee.walkConcurrency),A=e.cacheScope===void 0?"principal":e.cacheScope;if(A!=="principal"&&A!=="shared")throw new RangeError(`[markdown-explorer] cacheScope must be "principal" or "shared"; got ${JSON.stringify(A)}`);const v=e.reportSkipped;if(v!==void 0&&typeof v!="function")throw new TypeError("[markdown-explorer] reportSkipped must be a function");const _=v===void 0?g=>{console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(g.sourceId)} does not list ${JSON.stringify(g.path)}: ${g.reason}`)}:v,k=new Set,j=g=>{const x=te.resolve(i,...g.split("/")),S=te.relative(i,x);return S===""||S===".."||S.startsWith(`..${te.sep}`)||te.isAbsolute(S)?null:x},T=(g,x)=>{const S=`${x}\0${g}`;k.has(S)||k.size>=O||(k.add(S),_({sourceId:t,path:g,reason:x}))},P=async({signal:g})=>{g.throwIfAborted();const x=new AbortController,S=()=>{x.abort(g.reason)};g.addEventListener("abort",S,{once:!0});const N=un(R);let $=0;const F=async(M,G)=>{const Y=await N(async()=>{x.signal.throwIfAborted();try{return await fe.readdir(M,{withFileTypes:!0})}catch(D){if(G===""||!on(D))throw D;return null}});if(x.signal.throwIfAborted(),Y===null)return T(`${l}${G}`,"unreadable-directory"),null;const X=[];for(const D of Y){if(E.deniesName(D.name))continue;const W=G===""?D.name:`${G}/${D.name}`,Z=`${l}${W}`,K=ln(D,Z);if(K!==null){T(Z,K);continue}X.push({dirent:D,relativePath:W,path:Z})}if($+=X.length,$>O)throw new me("too-large");return X.sort((D,W)=>cn(D.dirent.name,W.dirent.name)),(await Promise.all(X.map(async({dirent:D,relativePath:W,path:Z})=>{if(!D.isDirectory())return{name:D.name,path:Z,type:"file"};const K=await F(te.join(M,D.name),W);return K===null?null:{name:D.name,path:Z,type:"directory",children:K}}))).filter(D=>D!==null)};try{const M=await F(i,"");if(M===null)throw new Error("[markdown-explorer] the source's root could not be listed");return M}catch(M){throw x.abort(),M}finally{g.removeEventListener("abort",S)}},C=async g=>{if(!g.startsWith(l))return{status:"refused",reason:"not-found"};const x=g.slice(l.length);if(!st(x))return{status:"refused",reason:"invalid"};if(E.deniesPath(x))return{status:"refused",reason:"forbidden"};const S=j(x);if(S===null)return{status:"refused",reason:"forbidden"};const N=await fe.lstat(S,{bigint:!0});if(N.isSymbolicLink())return{status:"refused",reason:"forbidden"};if(!N.isFile())return{status:"refused",reason:"unsupported"};const $=await fe.realpath(S);return $!==S||E.deniesPath(te.relative(i,$).split(te.sep).join("/"))?{status:"refused",reason:"forbidden"}:{status:"file",target:S,name:x.slice(x.lastIndexOf("/")+1),stats:N}},H=async(g,x,S)=>{let N;try{const $=await C(S);if($.status==="refused")return b.failureDocument($.reason);const{target:F,name:M,stats:G}=$,Y=nn(M),X=ot(G);if(Y.kind==="image")return{kind:"image",name:M,version:X};if(Y.kind==="media")return{kind:"media",name:M,mediaType:Y.mediaType,version:X};if(Y.kind==="file")return{kind:"file",name:M,version:X};N=await fe.open(F,oe.constants.O_RDONLY|gt|Et);const ee=await N.stat({bigint:!0});if(!ee.isFile()||ee.ino!==G.ino||ee.dev!==G.dev)return b.failureDocument("forbidden");if(Y.kind==="markdown"){if(ee.size>BigInt(f))return b.failureDocument("too-large");const K=await at(N,f+1);if(K.length>f)return b.failureDocument("too-large");const pe=await a(new TextDecoder("utf-8").decode(K),x);return{kind:"markdown",name:M,htmlContent:pe.htmlContent,headings:pe.headings}}const D=await at(N,h);if(D.includes(0))return{kind:"file",name:M,version:X};const W=ee.size>BigInt(h),Z=new TextDecoder("utf-8").decode(D,{stream:W});return{kind:"text",name:M,text:Z,truncated:W,version:X}}catch($){const F=Ie($);if(F===null)throw $;return b.failureDocument(F)}finally{await N?.close()}},u=async(g,x,S)=>{let N;try{N=await C(S)}catch(X){throw bt(X)}if(N.status==="refused")throw new me(N.reason);const{target:$,name:F,stats:M}=N,G=wt.get(yt(F)),Y=G===void 0?"":G.contentType;return{name:F,contentType:Y,size:Number(M.size),version:ot(M),open:X=>an($,M,X,g.signal)}},w=async(g,x,S)=>{let N;try{N=await C(S)}catch(M){if(Ie(M)!==null)return null;throw M}if(N.status==="refused")return null;const $=S.slice(l.length).split("/");if($.some(M=>E.deniesName(M)))return null;const F=$.slice(0,-1);return F.map((M,G)=>`${l}${F.slice(0,G+1).join("/")}`)};return Object.freeze({id:t,label:r,cacheScope:A,boundary:Object.freeze({contains:g=>g.startsWith(l)}),tree:P,ancestors:w,document:H,asset:u})};exports.DEFAULT_DENIED_PATH_SEGMENTS=b.DEFAULT_DENIED_PATH_SEGMENTS;exports.MAX_DOCUMENT_PATH_LENGTH=b.MAX_DOCUMENT_PATH_LENGTH;exports.isAcceptableDocumentPath=b.isAcceptableDocumentPath;exports.isDeniedPath=b.isDeniedPath;exports.ExplorerError=me;exports.anonymousAccess=Rt;exports.createFileSystemSource=fn;exports.createMarkdownExplorer=Zr;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("./dataRoute-CUXlMhUJ.cjs"),dt=require("node:crypto"),Pt=require("@aiquants/markdown/server"),ze=require("@aiquants/request-isolation"),Se=require("react-router"),se=require("./location-FavgY_gB.cjs"),ae=require("node:fs"),re=require("node:path"),xe=require("node:url"),It=require("node:worker_threads"),me=require("node:fs/promises"),Mt=require("node:stream");var Oe=typeof document<"u"?document.currentScript:null;const Ce=Object.freeze({kind:"anonymous"}),vt=Object.freeze({authenticate:async()=>({status:"signed-in",principal:Ce}),principalKey:()=>Ce.kind,signedOutPage:(e,t)=>new Response(null,{status:401,headers:t})}),Lt="application/octet-stream",ft="application/pdf",$t=new Set(["image/png","image/apng","image/jpeg","image/gif","image/webp","image/avif","image/bmp","image/x-icon","image/vnd.microsoft.icon","audio/mpeg","audio/mp4","audio/aac","audio/ogg","audio/opus","audio/wav","audio/wave","audio/x-wav","audio/webm","audio/flac","audio/x-flac","audio/x-m4a","video/mp4","video/webm","video/ogg","video/quicktime",ft]),mt="default-src 'none'; media-src 'self'; style-src 'unsafe-inline'",Dt=`${mt}; sandbox`,jt=`${mt}; sandbox allow-same-origin`,He=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,zt=/^[\t\n\r ]+|[\t\n\r ]+$/gu,Pe=/^[\t ]+|[\t ]+$/gu,Ct=e=>{const t=[];let r="",n=0;for(;;){for(;n<e.length&&e[n]!=='"'&&e[n]!==",";)r+=e[n],n+=1;if(n<e.length&&e[n]==='"'){const a=n;for(n+=1;n<e.length&&e[n]!=='"';)n+=e[n]==="\\"?2:1;if(n=Math.min(n+1,e.length),r+=e.slice(a,n),n<e.length)continue}if(t.push(r.replace(Pe,"")),r="",n>=e.length)return t;n+=1}},Ht=e=>{const t=e.replace(zt,""),r=t.indexOf("/");if(r<0)return null;const n=t.slice(0,r),a=t.indexOf(";",r+1),s=t.slice(r+1,a<0?t.length:a).replace(/[\t\n\r ]+$/u,"");return He.test(n)&&He.test(s)?`${n}/${s}`.toLowerCase():null},Bt=e=>{let t=null;for(const r of Ct(e)){const n=Ht(r);n!==null&&n!=="*/*"&&(t=n)}return t},Ft=/['()*]/gu,Ut=e=>encodeURIComponent(e).replace(Ft,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Xt=Object.freeze({"Cache-Control":"private, max-age=60, stale-while-revalidate=600, no-transform",Vary:"Cookie"}),Gt=(e,t)=>{const r=Bt(e),n=r!==null&&$t.has(r),a=n&&(r.startsWith("audio/")||r.startsWith("video/"));return{contentType:r===null?Lt:r,inline:n,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`${n?"inline":"attachment"}; filename*=UTF-8''${Ut(t)}`,...r===ft?{}:{"Content-Security-Policy":a?jt:Dt},"Cross-Origin-Resource-Policy":"same-origin"}}},Jt=/^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu,ge=Object.freeze({kind:"whole"}),Be=Object.freeze({kind:"unsatisfiable"}),Yt=(e,t,r)=>{const n=e.get("Range");if(n===null)return ge;const a=e.get("If-Range");if(a!==null&&a!==r)return ge;const s=Jt.exec(n);if(s===null)return ge;const[,c,f,E]=s;if(E!==void 0){const w=Number(E);if(w===0)return Be;const O=Math.max(0,t-w);return{kind:"partial",range:{offset:O,length:t-O}}}const k=Number(c),p=f===""?Number.POSITIVE_INFINITY:Number(f);return p<k?ge:k>=t?Be:{kind:"partial",range:{offset:k,length:Math.min(p,t-1)-k+1}}},Fe="W/",Wt=e=>{const t=[];let r=0,n=!1;for(let a=0;a<e.length;a+=1)e[a]==='"'?n=!n:e[a]===","&&!n&&(t.push(e.slice(r,a).replace(Pe,"")),r=a+1);return t.push(e.slice(r).replace(Pe,"")),t},Ue=e=>e.startsWith(Fe)?e.slice(Fe.length):e,Kt=(e,t)=>{if(e===null)return!1;const r=Wt(e);if(r.length===1&&r[0]==="*")return!0;const n=Ue(t);return r.some(a=>Ue(a)===n)},Vt=(e,t)=>{let r=t;return e.pipeThrough(new TransformStream({transform:(n,a)=>{const s=n.byteLength>r?n.subarray(0,r):n;r-=s.byteLength,a.enqueue(s),r===0&&a.terminate()},flush:n=>{r>0&&n.error(new RangeError("[markdown-explorer] the asset ended before its declared length"))}}))},ke=async(e,t,r,n,a)=>{if(n!==null&&r.set("Content-Length",String(n)),e.method.toUpperCase()==="HEAD")return new Response(null,{status:t,headers:r});const s=await a();return new Response(n===null?s:Vt(s,n),{status:t,headers:r})},Qt=(e,t)=>{const r=new Headers(e);for(const[n,a]of Object.entries({"Accept-Ranges":"bytes","Content-Range":`bytes */${t}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff"}))r.set(n,a);return new Response(null,{status:416,headers:r})},Zt=async(e,t,r)=>{const n=`"${t.version}"`,a=Gt(t.contentType,t.name),s=new Headers(r);for(const[E,k]of Object.entries({...a.headers,...Xt,ETag:n}))s.set(E,k);if(Kt(e.headers.get("If-None-Match"),n))return new Response(null,{status:304,headers:s});if(s.set("Content-Type",a.contentType),t.size===null)return ke(e,200,s,null,()=>t.open(null));if(t.size===0)return s.set("Content-Length","0"),new Response(null,{status:200,headers:s});s.set("Accept-Ranges","bytes");const c=Yt(e.headers,t.size,n);if(c.kind==="unsatisfiable")return Qt(r,t.size);if(c.kind==="whole")return ke(e,200,s,t.size,()=>t.open(null));const{range:f}=c;return s.set("Content-Range",`bytes ${f.offset}-${f.offset+f.length-1}/${t.size}`),ke(e,206,s,f.length,()=>t.open(f))},Re=(e,t)=>{const r=new AbortController,n=t(AbortSignal.any([e.signal,r.signal]));return new Promise(a=>{let s;const c=setTimeout(()=>{a(e.late),s=setTimeout(()=>r.abort(),e.handOverMs)},e.timeoutMs),f=()=>{clearTimeout(c),clearTimeout(s)};n.then(E=>{f(),a(E)},()=>{f(),a(e.late)})})},qt=Object.freeze({error:(e,t)=>{console.error(e,t)}}),pt=Symbol.for("@aiquants/markdown-explorer:ExplorerError");class he extends Error{reason;code;constructor(t,r={}){if(!b.isExplorerFailureReason(t))throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${JSON.stringify(t)}`);if(r.code!==void 0&&!b.isExplorerFailureCode(r.code))throw new RangeError(`[markdown-explorer] an ExplorerError code must be 1 to 64 lowercase letters, digits or hyphens; got ${JSON.stringify(r.code)}`);super(`[markdown-explorer] ${t}`,r.cause===void 0?void 0:{cause:r.cause}),this.name="ExplorerError",this.reason=t,this.code=r.code,Object.defineProperty(this,pt,{value:!0})}}const er=e=>e instanceof Error&&Object.hasOwn(e,pt)&&b.isExplorerFailureReason(e.reason),tr=e=>typeof e=="object"&&e!==null&&e.name==="AbortError",Me=(e,t,r)=>{try{e.error(t,r)}catch(n){console.error("[markdown-explorer] the logger threw while reporting a failure",{operation:r.operation,error:n})}},ne=(e,t)=>Me(e,`[markdown-explorer] ${t.operation} failed`,t),rr=(e,t)=>Me(e,`[markdown-explorer] ${t.operation} left out an entry`,t),Xe=(e,t)=>Me(e,`[markdown-explorer] ${t.operation} refused a path the deny rules match`,{...t,error:new RangeError("[markdown-explorer] the path matches a deny rule")}),Ge=(e,t)=>{e===null||typeof e!="object"&&typeof e!="function"||Promise.resolve(e).then(void 0,t)},Z=(e,t,r,n)=>er(e)?b.failureOf(e.reason,e.code):(tr(e)||r.aborted||ne(n,{...t,error:e}),{reason:"failed"}),nr=2*1024*1024,or=256*1024*1024,sr=async(e,t)=>{const r=e.getReader(),n=new Uint8Array(t);let a=0;for(;a<t;){const{done:s,value:c}=await r.read();if(s)return n.subarray(0,a);const f=c.subarray(0,t-a);n.set(f,a),a+=f.byteLength}return r.cancel().catch(()=>{}),n},ar=async(e,t)=>{if(e.size===0)return{text:"",truncated:!1};const r=e.size!==null&&e.size>t,n=e.size===null?t+1:Math.min(e.size,t),a=await sr(await e.open(r?{offset:0,length:t}:null),n);if(e.size!==null&&a.byteLength<n)throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");const s=r||a.byteLength>t,c=s?a.subarray(0,t):a;return c.includes(0)?null:{text:new TextDecoder("utf-8").decode(c,{stream:s}),truncated:s}},Je=(e,t)=>{if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] a cache ${e} must be a positive integer; got ${String(t)}`)},ht=(e,t)=>{Je("capacity",e),t!==void 0&&Je("weight budget",t.max);const r=new Map;let n=0;const a=s=>{const c=r.get(s);c!==void 0&&(r.delete(s),n-=c.weight)};return{get:s=>{const c=r.get(s);if(c!==void 0)return r.delete(s),r.set(s,c),c.value},set:(s,c)=>{a(s);const f=t===void 0?0:t.of(s,c);if(!(t!==void 0&&f>t.max)){r.set(s,{value:c,weight:f}),n+=f;for(const E of r.keys()){if(r.size<=e&&(t===void 0||n<=t.max))break;a(E)}}},delete:a,size:()=>r.size,weight:()=>n}},wt=e=>Math.max(1,e-1),ir=2147483647,Ye=Object.freeze({status:"aborted"}),ce=(e,t,r)=>{const n=(e.get(t)??0)+r;n===0?e.delete(t):e.set(t,n)},le=(e,t,r)=>{if(!Number.isSafeInteger(t)||t<=0||t>r)throw new RangeError(`[markdown-explorer] a worker pool's ${e} must be an integer in 1..${String(r)}; got ${String(t)}`)},cr=e=>e!==null&&typeof e=="object"&&e.ready===!0&&!("id"in e),ur=(e,t)=>e!==null&&typeof e=="object"&&e.id===t&&"output"in e,lr=({url:e,size:t,deadlineMs:r,jobsPerScope:n,maxQueuedJobs:a,heapLimits:s})=>{le("size",t,Number.MAX_SAFE_INTEGER),le("deadline",r,ir),le("jobsPerScope",n,Number.MAX_SAFE_INTEGER),le("maxQueuedJobs",a,Number.MAX_SAFE_INTEGER),le("maxOldGenerationSizeMb",s.maxOldGenerationSizeMb,Number.MAX_SAFE_INTEGER),le("maxYoungGenerationSizeMb",s.maxYoungGenerationSizeMb,Number.MAX_SAFE_INTEGER);const c=Object.freeze({maxOldGenerationSizeMb:s.maxOldGenerationSizeMb,maxYoungGenerationSizeMb:s.maxYoungGenerationSizeMb}),f=new Set,E=[],k=new Map,p=new Map,w=wt(t);let O=0;const A=(d,y)=>{const{job:h}=d;d.timer!==null&&clearTimeout(d.timer),d.timer=null,d.job=null,d.sent=!1,h!==null&&(ce(k,h.scope,-1),ce(p,h.scope,-1),h.settle(y))},v=d=>{const[y]=E.splice(d,1);y?.detach()},_=()=>{let d=-1,y=w,h=Number.POSITIVE_INFINITY;for(const[x,T]of E.entries()){const N=k.get(T.scope)??0,L=p.get(T.scope)??0;(N<y||N===y&&d>=0&&L<h)&&(d=x,y=N,h=L)}return d},R=(d,y)=>{f.has(d)&&(f.delete(d),A(d,y),d.worker.terminate().catch(()=>{}),j())},D=d=>{d.timer=setTimeout(()=>{R(d,{status:"timeout"})},r)},S=(d,y)=>d.sent?{status:"crashed",error:y}:{status:"unavailable",error:y},P=(d,y)=>{d.sent=!0,D(d);try{d.worker.postMessage({id:y.id,input:y.input})}catch(h){A(d,{status:"crashed",error:h}),d.worker.unref()}},B=()=>{const d={worker:new It.Worker(e,{resourceLimits:c}),job:null,sent:!1,timer:null,ready:!1};return d.worker.unref(),d.timer=setTimeout(()=>{R(d,{status:"unavailable",error:new Error(`[markdown-explorer] a worker did not start within ${String(r)} ms`)})},r),d.worker.on("message",y=>{if(!d.ready&&cr(y)){d.ready=!0,d.timer!==null&&clearTimeout(d.timer),d.timer=null,d.job===null?d.worker.unref():P(d,d.job),d.job===null&&j();return}const{job:h}=d;if(h===null||!ur(y,h.id)){R(d,S(d,new Error("[markdown-explorer] a worker sent a message that answers no job")));return}A(d,{status:"done",output:y.output}),d.worker.unref(),j()}),d.worker.on("error",y=>{R(d,S(d,y))}),d.worker.on("messageerror",y=>{R(d,S(d,y))}),d.worker.on("exit",y=>{R(d,S(d,new Error(`[markdown-explorer] a worker exited with code ${String(y)}`)))}),f.add(d),d},j=()=>{for(;;){const d=_(),y=E[d];if(y===void 0)return;let h;for(const T of f)if(T.job===null){h=T;break}if(h===void 0&&f.size<t)try{h=B()}catch(T){v(d),ce(p,y.scope,-1),y.settle({status:"unavailable",error:T});continue}if(h===void 0)return;v(d),ce(k,y.scope,1);const x=h;x.job=y,x.worker.ref(),x.ready&&P(x,y)}};return{run:(d,{scope:y,signal:h})=>new Promise(x=>{if(h.aborted){x(Ye);return}if((p.get(y)??0)>=n){x({status:"refused",limit:"scope"});return}O+=1;const T={id:O,input:d,scope:y,settle:x,detach:()=>{}};E.push(T),ce(p,y,1),j();const N=E.indexOf(T);if(N<0)return;if(E.length>a){v(N),ce(p,y,-1),x({status:"refused",limit:"queue"});return}const L=()=>{const F=E.indexOf(T);F<0||(v(F),ce(p,y,-1),x(Ye))};h.addEventListener("abort",L,{once:!0}),T.detach=()=>{h.removeEventListener("abort",L)}}),workers:()=>f.size}},ve=1024*1024,dr=3e4,fr=4*ve,mr=64*ve,pr=3,hr=2,wr=(e,t)=>e+wt(t)+pr,gr=4,Er=32,yr=512,br=64,Tr=4096,Sr=32,We=4096,xr=4,gt=({workerHeapMb:e,maxHtmlBytes:t})=>Math.floor(((e-br)*ve-t*Sr)/Tr),Or=({maxHtmlBytes:e})=>e,kr=({maxHtmlBytes:e})=>xr*e,Rr=1024,_r=2147483647,Ar=64,Nr=2**29,Pr=1024*1024,Ir=64,Ke=Object.freeze({status:"rejected",reason:"too-large",cause:null}),_e=Object.freeze({status:"rejected",reason:"failed",cause:null}),ue=(e,t,r,n)=>{if(t===void 0)return r;if(typeof t!="number")throw new TypeError(`[markdown-explorer] sanitizer.${e} must be a number; got ${typeof t}`);if(!Number.isSafeInteger(t)||t<=0||t>n)throw new RangeError(`[markdown-explorer] sanitizer.${e} must be an integer in 1..${String(n)}; got ${String(t)}`);return t},Mr=(e,t)=>{if(e!==void 0&&(e===null||typeof e!="object"))throw new TypeError("[markdown-explorer] sanitizer must be an object of { workers, deadlineMs, maxHtmlBytes, cacheBytes, workerHeapMb, jobsPerScope, maxQueuedJobs }");const{workers:r,deadlineMs:n,maxHtmlBytes:a,cacheBytes:s,workerHeapMb:c,jobsPerScope:f,maxQueuedJobs:E}=e??{},k=ue("workers",r,hr,Ar),p=ue("jobsPerScope",f,wr(t,k),Number.MAX_SAFE_INTEGER),w=Object.freeze({workers:k,deadlineMs:ue("deadlineMs",n,dr,_r),maxHtmlBytes:ue("maxHtmlBytes",a,fr,Nr),cacheBytes:ue("cacheBytes",s,mr,Number.MAX_SAFE_INTEGER),workerHeapMb:ue("workerHeapMb",c,yr,Pr),jobsPerScope:p,maxQueuedJobs:ue("maxQueuedJobs",E,gr*p,Number.MAX_SAFE_INTEGER)});if(w.jobsPerScope<t)throw new RangeError(`[markdown-explorer] sanitizer.jobsPerScope must be at least multiView.maxPanels (${String(t)}), because a page sends the document of every panel to the sanitizer at once for one reader; got ${String(w.jobsPerScope)}`);if(w.maxQueuedJobs<t)throw new RangeError(`[markdown-explorer] sanitizer.maxQueuedJobs must be at least multiView.maxPanels (${String(t)}), because a reader whose page finds every worker busy waits with the document of every panel; got ${String(w.maxQueuedJobs)}`);if(gt(w)<We)throw new RangeError(`[markdown-explorer] sanitizer.workerHeapMb (${String(w.workerHeapMb)} MiB) must leave room for ${String(We)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(w.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`);return w},vr=()=>{const e=typeof document>"u"?require("url").pathToFileURL(__filename).href:Oe&&Oe.tagName.toUpperCase()==="SCRIPT"&&Oe.src||new URL("server.cjs",document.baseURI).href,t=new URL(`./sanitizeWorker${re.extname(xe.fileURLToPath(e))}`,e);if(!ae.existsSync(xe.fileURLToPath(t)))throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${xe.fileURLToPath(t)}`);return t},Ve=new Map,Lr=(e,t)=>{const r=[e.href,t.workers,t.deadlineMs,t.workerHeapMb,t.jobsPerScope,t.maxQueuedJobs].map(String).join("\0");let n=Ve.get(r);return n===void 0&&(n=lr({url:e,size:t.workers,deadlineMs:t.deadlineMs,jobsPerScope:t.jobsPerScope,maxQueuedJobs:t.maxQueuedJobs,heapLimits:{maxOldGenerationSizeMb:t.workerHeapMb,maxYoungGenerationSizeMb:Er}}),Ve.set(r,n)),n},$r=e=>{if(e===null||typeof e!="object")return!1;const{status:t,html:r,message:n}=e;return t==="sanitized"&&typeof r=="string"||t==="too-large"||t==="error"&&typeof n=="string"},Dr=e=>e instanceof Error&&e.code==="ERR_WORKER_OUT_OF_MEMORY",jr=({iframeHosts:e,dataPath:t,options:r,pool:n})=>{const a=Object.freeze([...e]),s=gt(r),c=Or(r),f=kr(r),E=ht(Rr,{max:r.cacheBytes,of:(_,R)=>2*_.length+(R.status==="sanitized"?2*R.html.length:Ir)}),k=new Map,p=new Map,w=_=>{k.get(_.key)===_&&k.delete(_.key);const R=p.get(_.hash);R?.delete(_),R?.size===0&&p.delete(_.hash)},O=async(_,R,D)=>{const S=await n.run({html:_,iframeHosts:a,dataPath:t,maxNodes:s,maxAttributeChars:c,maxSanitizedChars:f},{scope:R,signal:D});if(S.status==="refused"){const B=S.limit==="scope"?`its reader already has ${String(r.jobsPerScope)} documents being sanitized or waiting`:`${String(r.maxQueuedJobs)} documents are already waiting`;return{outcome:{status:"rejected",reason:"failed",cause:new Error(`[markdown-explorer] the HTML sanitizer refused a document: ${B}`)},lasting:!1}}if(S.status==="aborted")return{outcome:_e,lasting:!1};if(S.status==="timeout")return{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer did not finish within ${String(r.deadlineMs)} ms`)},lasting:!0};if(S.status==="unavailable")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker could not start",{cause:S.error})},lasting:!1};if(S.status==="crashed"&&Dr(S.error))return{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer ran out of its ${String(r.workerHeapMb)} MiB worker heap`,{cause:S.error})},lasting:!0};if(S.status==="crashed")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker failed",{cause:S.error})},lasting:!0};const{output:P}=S;return $r(P)?P.status==="too-large"?{outcome:Ke,lasting:!0}:P.status==="error"?{outcome:{status:"rejected",reason:"failed",cause:new Error(`[markdown-explorer] the HTML sanitizer failed: ${P.message}`)},lasting:!0}:P.html.length>f?{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer's output of ${String(P.html.length)} characters exceeds its limit of ${String(f)}`)},lasting:!0}:{outcome:{status:"sanitized",html:P.html},lasting:!0}:{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker answered something that is not an outcome")},lasting:!0}},A=(_,R,D,S)=>{let P=()=>{};const B=new Promise(y=>{P=y}),j={hash:R,key:D,outcome:B,answer:P,controller:new AbortController,waiters:0};k.set(D,j);const d=p.get(R);return d===void 0?p.set(R,new Set([j])):d.add(j),O(_,S,j.controller.signal).catch(y=>({outcome:{status:"rejected",reason:"failed",cause:y instanceof Error?y:new Error(String(y))},lasting:!0})).then(({outcome:y,lasting:h})=>{if(w(j),j.answer(y),!h)return;const x=E.get(R),T=x??(y.status==="rejected"?{...y,cause:null}:y);x===void 0&&E.set(R,T);for(const N of p.get(R)??[])w(N),N.answer(T),N.controller.abort()}),j},v=(_,R)=>new Promise(D=>{_.waiters+=1;const S=()=>{_.waiters-=1,D(_e),!(_.waiters>0)&&(w(_),_.controller.abort())};R.addEventListener("abort",S,{once:!0}),_.outcome.then(P=>{R.removeEventListener("abort",S),D(P)})});return(_,{scope:R,signal:D})=>{if(_.length>r.maxHtmlBytes||Buffer.byteLength(_,"utf8")>r.maxHtmlBytes)return Promise.resolve(Ke);const S=dt.createHash("sha256").update(_,"utf8").digest("base64"),P=E.get(S);if(P!==void 0)return Promise.resolve(P);if(D.aborted)return Promise.resolve(_e);const B=`${S}\0${R}`,j=k.get(B);return v(j===void 0?A(_,S,B,R):j,D)}},Te=e=>({result:e,json:JSON.stringify(e)}),Ae=Object.freeze(Te(Object.freeze({status:"error",failure:Object.freeze({reason:"failed"})}))),zr=e=>e.status==="ok"&&e.entries.length>0,Cr=({ttlMs:e,maxEntries:t,maxBytes:r,now:n})=>{const a=ht(t,{max:r,of:(p,w)=>2*w.tree.json.length}),s=new Map,c=new Map,f=(p,w)=>{const O=new AbortController,A={waiters:0,superseded:!1,started:!1,loadTree:w},v=c.get(p),_=(B,j)=>{const d=Te(B);return!(A.superseded||O.signal.aborted)&&zr(B)&&a.set(p,{tree:d,loadedAt:j}),d},D=(async()=>{if(v!==void 0&&await v,O.signal.aborted)return Ae;const B=n();return A.started=!0,_(await A.loadTree(O.signal,B),B)})().finally(()=>{s.get(p)===S&&s.delete(p)}),S={promise:D,controller:O,state:A};s.set(p,S);const P=D.then(()=>{},()=>{});return c.set(p,P),P.then(()=>{c.get(p)===P&&c.delete(p)}),S},E=(p,w,O)=>{w.state.waiters+=1;const A=()=>{w.state.waiters-=1,!(w.state.waiters>0)&&(s.get(p)===w&&s.delete(p),w.controller.abort())};return O.addEventListener("abort",A,{once:!0}),w.promise.finally(()=>{O.removeEventListener("abort",A)})},k=p=>{a.delete(p);const w=s.get(p);w?.state.started&&(w.state.superseded=!0,s.delete(p))};return{load:(p,w,O)=>{if(w.aborted)return Promise.resolve(Ae);const A=a.get(p);if(A!==void 0){if(n()-A.loadedAt<e)return Promise.resolve(A.tree);a.delete(p)}const v=s.get(p);return E(p,v===void 0?f(p,O):v,w)},refresh:(p,w,O)=>{if(w.aborted)return Promise.resolve(Ae);k(p);const A=s.get(p);return A===void 0?E(p,f(p,O),w):(A.state.loadTree=O,E(p,A,w))},forget:k}},Hr=e=>({load:(t,r,n)=>n(r,e()).then(Te),refresh:(t,r,n)=>n(r,e()).then(Te),forget:()=>{}}),$=e=>{throw new TypeError(`[markdown-explorer] ${e}`)},Br=e=>{if(e===null||typeof e!="object")return null;const{name:t,path:r}=e;return typeof t!="string"||typeof r!="string"?null:t===""?{path:r,reason:"an empty name"}:b.isAcceptableDocumentPath(r)?null:{path:r,reason:"a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)"}},Fr=(e,t,r,n)=>{if(e===null)return null;if(!Array.isArray(e))throw new TypeError(`[markdown-explorer] a source's ancestors must be null or an array of folder paths; got ${typeof e}`);const a=new Set;for(const s of e){if(typeof s!="string"||!b.isAcceptableDocumentPath(s))throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");if(r.deniesPath(s))throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");if(!n(s))throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");if(s===t)throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");if(a.has(s))throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");a.add(s)}return Object.freeze([...a])},Ur=(e,t,r,n,a)=>{const s=new Set,c=E=>{if(!Array.isArray(E))return $("a source returned entries that are not an array");const k=[];for(const p of E){const w=f(p);w!==null&&k.push(w)}return k},f=E=>{const k=Br(E);if(k!==null)return n(k),null;const p=b.entryViolation(E);if(p!==null)return $(p);const w=E;if(s.has(w))return $("a source returned entries that contain themselves");const{name:O,path:A,type:v,mimeType:_,children:R,lazy:D}=w;if(t.deniesName(O)||t.deniesPath(A))return null;if(!a(A))return n({path:A,reason:"a path outside the source's boundary"}),null;const S=_===void 0?{name:O,path:A}:{name:O,path:A,mimeType:_};if(v==="file")return{...S,type:v};if(D===!0)return r?{...S,type:v,lazy:!0,children:[]}:$("a lazy directory came from a source without a children function");if(R===void 0)return{...S,type:v};s.add(w);const P=c(R);return s.delete(w),{...S,type:v,children:P}};return c(e)},Xr=/^[\x21\x23-\x7E]{1,256}$/u,Et=e=>typeof e=="string"&&Xr.test(e),Gr=new Set(["text","image","media","file"]),Jr=e=>typeof e=="string"&&Gr.has(e),Yr=(e,t)=>{if(e!==null&&typeof e=="object"){const a=e,{kind:s}=a;if(Jr(s)){if(Object.hasOwn(a,"url"))return $(`a ${s} document carries its version, not a url`);if(typeof a.name!="string")return $("a document needs a name string");if(!Et(a.version))return $(`a ${s} document needs a version of 1 to 256 visible ASCII characters other than '"'`);const c=t(a.version);switch(s){case"image":case"file":return{kind:s,name:a.name,url:c};case"media":{const{mediaType:f}=a;return b.isExplorerMediaType(f)?{kind:s,name:a.name,url:c,mediaType:f}:$(`unknown media type ${typeof f=="string"?JSON.stringify(f.slice(0,64)):typeof f}`)}case"text":return typeof a.text!="string"||typeof a.truncated!="boolean"?$("a text document needs text and truncated"):{kind:s,name:a.name,text:a.text,truncated:a.truncated,url:c}}}}const r=b.documentViolation(e);if(r!==null)return $(r);const n=e;switch(n.kind){case"failure":{const{reason:a,code:s}=n.failure;return{kind:"failure",failure:b.failureOf(a,s)}}case"markdown":return n.headings.length>b.EXPLORER_MAX_HEADINGS?{kind:"failure",failure:b.failureOf("too-large")}:{kind:"unsanitized-markdown",name:n.name,html:n.htmlContent,headings:n.headings.map(({text:a,depth:s,id:c})=>({text:a,depth:s,id:c}))}}},Qe=e=>{if(e===null||typeof e!="object")return $("an asset file must be an object");const{name:t,contentType:r,size:n,version:a,open:s}=e;return typeof t!="string"||t===""?$("an asset file needs a non-empty name"):typeof r!="string"?$("an asset file needs a contentType string ('' when unknown)"):n!==null&&!(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)?$("an asset file's size must be null or a non-negative safe integer"):Et(a)?typeof s!="function"?$("an asset file needs an open function"):Object.freeze({name:t,contentType:r,size:n,version:a,open:s}):$(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`)},Wr=e=>Array.isArray(e)?e.map(t=>{if(t===null||typeof t!="object")return $("a notice must be an object");const{id:r,tone:n,title:a,body:s,action:c}=t;if(typeof r!="string"||r===""||typeof a!="string")return $("a notice needs an id and a title");if(!b.isExplorerNoticeTone(n))return $(`unknown notice tone ${typeof n=="string"?JSON.stringify(n.slice(0,64)):typeof n}`);if(s!==void 0&&typeof s!="string")return $("a notice body must be a string");const E={id:r,tone:n,title:a,...s===void 0?{}:{body:s}};if(c===void 0)return E;if(c===null||typeof c!="object")return $("a notice action must be an object");const{label:k,href:p}=c;return typeof k!="string"||!b.isAcceptableUrl(p,b.EXPLORER_LINK_PROTOCOLS)?$("a notice action needs a label and an http(s), mailto or relative href"):{...E,action:{label:k,href:p}}}):$("notices must be an array"),Kr=4e3,Ee=Object.freeze({ttlMs:3e5,maxEntries:64,maxBytes:64*1024*1024}),Ze=32,yt="private, no-store",Vr=Object.freeze({"Content-Type":"application/json; charset=utf-8","Cache-Control":yt,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; frame-ancestors 'none'; sandbox","Cross-Origin-Resource-Policy":"same-origin"}),Qr=22,Zr=2147483647,Ne=Object.freeze([]),qr=Object.freeze({status:"ok",source:null,ancestors:null}),qe=Object.freeze(["contains","confirm"]),et=Object.freeze({readOnly:!1}),en=Object.freeze({readOnly:!0}),W=(e,t,r)=>{if(!(r&&t===void 0)&&typeof t!="function")throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${typeof t}`)},pe=(e,t,r)=>{if(typeof t!="number")throw new TypeError(`[markdown-explorer] ${e} must be a number; got ${typeof t}`);if(!Number.isSafeInteger(t)||t<=0||t>r)throw new RangeError(`[markdown-explorer] ${e} must be an integer in 1..${String(r)}; got ${String(t)}`);return t},tn=e=>{if(e===null||typeof e!="object"||!Object.isFrozen(e))throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");return se.revalidateExplorerConfig(e)},tt=e=>{try{return new Headers(e)}catch{throw new TypeError("[markdown-explorer] authenticate returned headers that are not a valid headers init (their values are not logged)")}},rt=e=>e instanceof Response?new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`):e,rn=e=>{if(typeof e!="string")throw new TypeError(`[markdown-explorer] scopeSecret must be a string; got ${typeof e}`);if(e.length<Ze)throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(Ze)} characters; got ${String(e.length)}`);return e},nn=(e,t)=>{if(!se.isPlainObject(t))throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);for(const r of Object.keys(t))if(!qe.includes(r))throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${qe.join(", ")}`);W(`${e}.boundary.contains`,t.contains,!1),W(`${e}.boundary.confirm`,t.confirm,!0)},on=e=>{if(!Array.isArray(e))throw new TypeError("[markdown-explorer] sources must be an array");const t=e;if(t.length===0)throw new RangeError("[markdown-explorer] sources must hold at least one source");const r=new Set;for(const[n,a]of t.entries()){if(a===null||typeof a!="object")throw new TypeError(`[markdown-explorer] sources[${String(n)}] must be an object`);const{id:s,label:c,boundary:f,tree:E,children:k,ancestors:p,cacheScope:w}=a;if(!se.isExplorerSourceId(s))throw new RangeError(`[markdown-explorer] sources[${String(n)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${typeof s=="string"?JSON.stringify(s):typeof s}`);const O=`source ${JSON.stringify(s)}`;if(r.has(s))throw new RangeError(`[markdown-explorer] source ids must be unique; ${JSON.stringify(s)} repeats at sources[${String(n)}]`);if(r.add(s),typeof c!="string"&&typeof c!="function")throw new TypeError(`[markdown-explorer] ${O}.label must be a string or a function`);if(typeof c=="string"&&c.trim()==="")throw new RangeError(`[markdown-explorer] ${O}.label must not be blank`);if(nn(O,f),W(`${O}.tree`,E,!1),W(`${O}.children`,k,!0),W(`${O}.ancestors`,p,!0),w!==void 0&&w!=="principal"&&w!=="shared")throw new RangeError(`[markdown-explorer] ${O}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(w)}`)}return t},sn=e=>{if(e===!1)return!1;if(e===void 0)return Ee;if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] treeCache must be { ttlMs, maxEntries, maxBytes } or false");const{ttlMs:t,maxEntries:r,maxBytes:n}=e;return{ttlMs:t===void 0?Ee.ttlMs:pe("treeCache.ttlMs",t,Number.MAX_SAFE_INTEGER),maxEntries:r===void 0?Ee.maxEntries:pe("treeCache.maxEntries",r,Number.MAX_SAFE_INTEGER),maxBytes:n===void 0?Ee.maxBytes:pe("treeCache.maxBytes",n,Number.MAX_SAFE_INTEGER)}},nt=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] authenticate must resolve to { status, ... }");const{status:t}=e;if(t!=="signed-in"&&t!=="signed-out"&&t!=="forbidden")throw new TypeError(`[markdown-explorer] authenticate resolved to an unknown status ${JSON.stringify(t)}`);return e},ot=(e,t)=>{if(!(t instanceof Response))throw new TypeError(`[markdown-explorer] ${e} must return a Response`);return t},st=(e,t)=>{if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");return dt.createHmac("sha256",e).update(t,"utf8").digest("base64url").slice(0,Qr)},an=e=>e.view==="multi"?e.docs:e.doc===null?[]:[e.doc],fe=(e,t)=>{const r=e.getAll(t),[n]=r;return r.length===1&&n!==void 0&&n!==""?n:null},oe=(e,t,r,n={})=>{const a=new Headers(r);for(const[s,c]of Object.entries({...Vr,...n}))a.set(s,c);return new Response(t,{status:e,headers:a})},U=(e,t,r)=>oe(b.EXPLORER_FAILURE_STATUS[e.reason],JSON.stringify({failure:e}),t,r),at=(e,t)=>{const r=t==="refresh"?["POST"]:["GET","HEAD"];return r.includes(e.method.toUpperCase())?null:oe(405,JSON.stringify({failure:{reason:"invalid"}}),void 0,{Allow:r.join(", ")})},it=e=>e.headers.get(b.EXPLORER_REFRESH_HEADER)===b.EXPLORER_REFRESH_HEADER_VALUE&&ze.crossOriginRefusal(e,ze.NO_CROSS_ORIGIN_NAVIGATION)===void 0,cn=({parentHeaders:e,loaderHeaders:t,errorHeaders:r})=>{const n=new Headers,a=r===void 0?[e,t]:[e,t,r];for(const s of a)for(const[c,f]of s)c!=="set-cookie"&&n.set(c,f);return n},un=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the server configuration must be an object");const t=tn(e.config),r=rn(e.scopeSecret);W("authenticate",e.authenticate,!1),W("principalKey",e.principalKey,!1),W("document",e.document,!1),W("asset",e.asset,!1),W("signedOutPage",e.signedOutPage,!1),W("forbiddenPage",e.forbiddenPage,!0),W("notices",e.notices,!0),W("onTreeRefreshed",e.onTreeRefreshed,!0);const n=on(e.sources),a=se.withExplorerSources(t,n.map(o=>o.id)),s=e.logger;if(s!==void 0&&(s===null||typeof s!="object"||typeof s.error!="function"))throw new TypeError("[markdown-explorer] logger must be an object with an error function");const c=e.logger===void 0?qt:e.logger,f=b.resolvePathRules(e.deny),E=e.deferredTimeoutMs===void 0?Kr:pe("deferredTimeoutMs",e.deferredTimeoutMs,Zr),k=e.textMaxBytes===void 0?nr:pe("textMaxBytes",e.textMaxBytes,or),p=sn(e.treeCache),w=()=>Date.now(),O=p===!1?Hr(w):Cr({...p,now:w}),A=Mr(e.sanitizer,t.multiView.maxPanels),v=jr({iframeHosts:t.iframeHosts,dataPath:t.dataPath,options:A,pool:Lr(vr(),A)}),_=new Map(n.map(o=>[o.id,o])),R=se.documentStyleNames(t),{authenticate:D,principalKey:S,signedOutPage:P,forbiddenPage:B,onTreeRefreshed:j}=e,d=(o,l)=>{if(typeof o.label=="string")return o.label;const i=o.label(l);if(typeof i!="string"||i.trim()==="")throw new TypeError(`[markdown-explorer] the label of source ${JSON.stringify(o.id)} must be a non-blank string`);return i},y=(o,l)=>o.cacheScope==="shared"?o.id:`${o.id}\0${l}`,h=(o,l)=>{const i=m=>ne(c,{operation:"boundary",sourceId:o.id,path:l,error:m});let u;try{u=o.boundary.contains(l)}catch(m){return i(m),!1}return typeof u=="boolean"?u:(Ge(u,i),i(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(o.id)} must return a boolean; got ${typeof u}`)),!1)},x=async(o,l,i)=>{const{confirm:u}=o.boundary;if(u===void 0)return{status:"inside",readPath:i};let m;try{m=await u(l,i)}catch(Y){return{status:"error",failure:Z(Y,{operation:"boundary",sourceId:o.id,path:i},l.signal,c)}}const g=Y=>(ne(c,{operation:"boundary",sourceId:o.id,path:i,error:new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} ${Y}`)}),{status:"outside"});if(m===null||typeof m!="object")return g(`must resolve to { inside, readPath? }; got ${m===null?"null":typeof m}`);const{inside:M,readPath:C}=m;return M===!1?{status:"outside"}:M!==!0||typeof C!="string"?g("must resolve to { inside: false } or { inside: true, readPath: string }"):!b.isAcceptableDocumentPath(C)||f.deniesPath(C)?(ne(c,{operation:"boundary",sourceId:o.id,path:i,error:new RangeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} answered a readPath the explorer does not serve (unacceptable or denied)`)}),{status:"error",failure:{reason:"failed"}}):{status:"inside",readPath:C}},T=async(o,l)=>{const i=n.filter(m=>h(m,l));if(i.length===0)return{status:"error",failure:{reason:"forbidden"}};if(i.some(m=>m.boundary.confirm===void 0))return{status:"inside",readPath:l};let u=null;for(const m of i){const g=await x(m,o,l);if(g.status==="inside")return g;g.status==="error"&&u===null&&(u=g.failure)}return{status:"error",failure:u===null?{reason:"forbidden"}:u}},N=(o,l,i)=>{const u=({path:m,reason:g})=>rr(c,{operation:i.operation,sourceId:i.sourceId,path:m,error:new TypeError(`[markdown-explorer] an entry with ${g} was left out`)});try{return{status:"ok",entries:Ur(o,f,l.children!==void 0,u,m=>h(l,m))}}catch(m){return ne(c,{...i,error:m}),{status:"error",failure:{reason:"failed"}}}},L=async(o,l,i)=>{let u;try{u=await o.tree(l)}catch(g){return{status:"error",failure:Z(g,{operation:"tree",sourceId:o.id},l.signal,c)}}const m=N(u,o,{operation:"tree",sourceId:o.id});return m.status==="ok"?{status:"ok",entries:m.entries,loadedAt:i}:m},F=(o,l,i,u)=>(m,g)=>L(o,{principal:l,request:i,signal:m,refresh:u},g),I=(o,l,i,u,m)=>O.load(y(o,i),m,F(o,l,u,!1)),G=(o,l,i,u)=>O.refresh(y(o,i),u.signal,F(o,l,u,!0)),K=(o,l)=>{if(j===void 0)return;const i=u=>ne(c,{operation:"refresh",sourceId:o.id,error:u});try{Ge(j(l),i)}catch(u){i(u)}},X=async(o,l,i,u)=>{if(f.deniesPath(u)||!h(o,u))return{status:"error",failure:{reason:"forbidden"}};const m=await x(o,i,u);if(m.status==="outside")return{status:"error",failure:{reason:"forbidden"}};if(m.status==="error")return{status:"error",failure:m.failure};let g;try{g=await l(i,u,m.readPath)}catch(M){return{status:"error",failure:Z(M,{operation:"children",sourceId:o.id,path:u},i.signal,c)}}return N(g,o,{operation:"children",sourceId:o.id,path:u})},te=async(o,l,i,u)=>{const m=await x(o,i,u);if(m.status==="outside")return{status:"ok",ancestors:null};if(m.status==="error")return{status:"error",failure:m.failure};let g;try{g=await l(i,u,m.readPath,{maxDepth:t.revealDocument.maxDepth})}catch(M){return{status:"error",failure:Z(M,{operation:"ancestors",sourceId:o.id,path:u},i.signal,c)}}if(Array.isArray(g)&&g.length>t.revealDocument.maxDepth)return{status:"ok",ancestors:null};try{return{status:"ok",ancestors:Fr(g,u,f,M=>h(o,M))}}catch(M){return ne(c,{operation:"ancestors",sourceId:o.id,path:u,error:M}),{status:"error",failure:{reason:"failed"}}}},z=async(o,l,i,u)=>f.deniesPath(u)?{status:"error",failure:{reason:"forbidden"}}:h(o,u)?te(o,l,i,u):{status:"ok",ancestors:null},V=async(o,l,i)=>{if(f.deniesPath(i))return{status:"error",failure:{reason:"forbidden"}};for(const u of[o,...n.filter(m=>m!==o)]){if(l.signal.aborted)break;const m=u.ancestors;if(m===void 0||!h(u,i))continue;const g=await te(u,m,l,i);if(g.status==="ok"&&g.ancestors!==null)return{status:"ok",source:u.id,ancestors:g.ancestors}}return qr},Q=async(o,l,i)=>{if(f.deniesPath(i))return b.failureDocument("forbidden");const u=await T(o,i);if(u.status==="error")return{kind:"failure",failure:u.failure};let m;try{m=await e.document(o,i,u.readPath)}catch(C){return{kind:"failure",failure:Z(C,{operation:"document",path:i},o.signal,c)}}let g;try{g=Yr(m,C=>b.explorerAssetHref(t.dataPath,i,C))}catch(C){return ne(c,{operation:"document",path:i,error:C}),b.failureDocument("failed")}if(g.kind!=="unsanitized-markdown")return g;const M=await v(g.html,{scope:l,signal:o.signal});return M.status==="sanitized"?{kind:"markdown",name:g.name,htmlContent:M.html,headings:g.headings}:(M.cause!==null&&ne(c,{operation:"document",path:i,error:M.cause}),b.failureDocument(M.reason))},q=async o=>{if(e.notices===void 0)return Ne;try{return Wr(await e.notices(o))}catch(l){return Z(l,{operation:"notices"},o.signal,c),Ne}},we=async(o,l,i)=>{const u=fe(l,b.EXPLORER_DATA_QUERY.path);if(u===null||!b.isAcceptableDocumentPath(u))return U({reason:"invalid"},i);if(f.deniesPath(u))return Xe(c,{operation:"asset",path:u}),U({reason:"forbidden"},i);const m=await T(o,u);if(m.status==="error")return U(m.failure,i);try{const g=Qe(await e.asset(o,u,m.readPath));return await Zt(o.request,g,i)}catch(g){return U(Z(g,{operation:"asset",path:u},o.signal,c),i)}},kt=async(o,l)=>{if(f.deniesPath(l))return Xe(c,{operation:"text",path:l}),b.failureDocument("forbidden");const i=await T(o,l);if(i.status==="error")return{kind:"failure",failure:i.failure};try{const u=Qe(await e.asset(o,l,i.readPath)),m=await ar(u,k);return m===null?b.failureDocument("unsupported"):{kind:"text",name:u.name,text:m.text,truncated:m.truncated,url:b.explorerAssetHref(t.dataPath,l,u.version)}}catch(u){return{kind:"failure",failure:Z(u,{operation:"text",path:l},o.signal,c)}}},Rt=async({request:o,url:l,params:i})=>{const u=nt(await D(o,et)),m=tt(u.headers);if(m.set("Cache-Control",yt),u.status==="signed-out")throw ot("signedOutPage",P(o,m));if(u.status==="forbidden")throw B===void 0?Se.data(null,{status:403,headers:m}):ot("forbiddenPage",B(o,m));const g=se.resolveExplorerLocation(a,i["*"],l.searchParams);if(g.kind==="redirect")throw Se.redirect(g.href,{headers:m});const{location:M}=g,{principal:C}=u,Y=st(r,S(C)),ie=_.get(M.source);if(ie===void 0)throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(M.source)}`);const de={signal:o.signal,timeoutMs:E,late:null,handOverMs:E},ee={scope:Y,sources:n.map(H=>({id:H.id,label:d(H,C)})),settings:se.parseViewSettings(se.readCookieValue(o.headers.get("Cookie"),t.settingsCookie),R),tree:M.view==="single"?null:{sourceId:M.source,result:Re(de,H=>I(ie,C,Y,o,H).then(J=>J.result))},documents:an(M).map(H=>({path:H,document:Re(de,J=>Q({principal:C,request:o,signal:J,refresh:!1},Y,H))})),notices:Re({signal:o.signal,timeoutMs:E,late:Ne,handOverMs:0},H=>q({principal:C,request:o,signal:H,refresh:!1}))};return Se.data(ee,{headers:m})},Le=async(o,l)=>{const i=nt(await D(o,l));return{authentication:i,headers:tt(i.headers)}},_t=async(o,l,i)=>{let u;try{u=await Le(l,et)}catch(J){return U(Z(rt(J),{operation:"authenticate"},l.signal,c))}const{authentication:m,headers:g}=u;if(m.status==="signed-out")return U({reason:"unauthorized"},g);if(m.status==="forbidden")return U({reason:"forbidden"},g);const{principal:M}=m;if(o==="asset")return we({principal:M,request:l,signal:l.signal,refresh:!1},i,g);const C=st(r,S(M));g.set(b.EXPLORER_SCOPE_HEADER,C);const Y={principal:M,request:l,signal:l.signal,refresh:!1},ie=()=>U({reason:"invalid"},g);if(o==="document"){const J=fe(i,b.EXPLORER_DATA_QUERY.path);if(J===null||!b.isAcceptableDocumentPath(J))return ie();const je=l.headers.has(b.EXPLORER_REFRESH_HEADER);return je&&!it(l)?U({reason:"forbidden"},g):oe(200,JSON.stringify(await Q({...Y,refresh:je},C,J)),g)}if(o==="text"){const J=fe(i,b.EXPLORER_DATA_QUERY.path);return J===null||!b.isAcceptableDocumentPath(J)?ie():oe(200,JSON.stringify(await kt(Y,J)),g)}const de=fe(i,b.EXPLORER_DATA_QUERY.source),ee=fe(i,b.EXPLORER_DATA_QUERY.path);if(de===null||(o==="children"||o==="ancestors"||o==="reveal")&&(ee===null||!b.isAcceptableDocumentPath(ee)))return ie();const H=_.get(de);if(H===void 0)return U({reason:"not-found"},g);if(o==="tree")return oe(200,(await I(H,M,C,l,l.signal)).json,g);if(o==="refresh"){const J=await G(H,M,C,l);return l.signal.aborted||K(H,y(H,C)),oe(200,J.json,g)}return o==="ancestors"?H.ancestors===void 0||ee===null?U({reason:"not-found"},g):oe(200,JSON.stringify(await z(H,H.ancestors,Y,ee)),g):o==="reveal"?ee===null?ie():oe(200,JSON.stringify(await V(H,Y,ee)),g):H.children===void 0||ee===null?U({reason:"not-found"},g):oe(200,JSON.stringify(await X(H,H.children,Y,ee)),g)},At=async o=>{const{authentication:l,headers:i}=await Le(o,en);if(!i.keys().next().done)throw new TypeError("[markdown-explorer] authenticate returned headers in read-only mode; a read-only authentication must only read the session (none was forwarded)");return l.status==="signed-in"},$e=t.embeds.linkCardEndpoint===null?null:Pt.createLinkCardHandler({authorize:At}),Nt=async(o,l)=>{try{return await o(l)}catch(i){return U(Z(rt(i),{operation:"authenticate"},l.signal,c))}},De=async(o,l,i)=>{if(new URL(o.url).pathname.endsWith(".data"))return U({reason:"not-found"});if(!b.isExplorerDataOperation(i))return U({reason:"not-found"});if(i==="link-card"){if($e===null)return U({reason:"not-found"});const m=at(o,i);return m!==null?m:Nt($e,o)}const u=at(o,i);if(u!==null)return u;if(i==="refresh"&&!it(o))return U({reason:"forbidden"});try{return await _t(i,o,l.searchParams)}catch(m){return U(Z(m,{operation:i},o.signal,c))}};return Object.freeze({loader:Rt,headers:cn,dataLoader:({request:o,url:l,params:i})=>De(o,l,i["*"]),dataAction:({request:o,url:l,params:i})=>De(o,l,i["*"]),forgetTree:o=>{if(typeof o!="string")throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof o}`);O.forget(o)}})},ye=Object.freeze({maxEntries:2e4,maxDocumentBytes:2*1024*1024,textPreviewBytes:8*1024,walkConcurrency:8}),ln=new Set(["md","markdown","mdx"]),bt=new Map([...[["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"],["svg","image/svg+xml"],["webp","image/webp"],["ico","image/x-icon"],["bmp","image/bmp"],["tif","image/tiff"],["tiff","image/tiff"],["avif","image/avif"]].map(([e,t])=>[e,{kind:"image",contentType:t}]),...[["mp4","video/mp4"],["m4v","video/mp4"],["webm","video/webm"],["mov","video/quicktime"],["avi","video/x-msvideo"],["mkv","video/x-matroska"],["ogv","video/ogg"]].map(([e,t])=>[e,{kind:"media",mediaType:"video",contentType:t}]),...[["mp3","audio/mpeg"],["wav","audio/wav"],["ogg","audio/ogg"],["oga","audio/ogg"],["opus","audio/ogg"],["m4a","audio/mp4"],["flac","audio/flac"],["aac","audio/aac"],["wma","audio/x-ms-wma"]].map(([e,t])=>[e,{kind:"media",mediaType:"audio",contentType:t}]),["pdf",{kind:"media",mediaType:"pdf",contentType:"application/pdf"}]]),dn=new Set(["txt","text","log","csv","tsv","json","jsonc","json5","ndjson","yaml","yml","toml","ini","cfg","conf","properties","xml","xsl","xsd","dtd","html","htm","xhtml","css","scss","sass","less","styl","js","mjs","cjs","jsx","ts","mts","cts","tsx","vue","svelte","astro","py","pyi","rb","go","rs","java","kt","kts","scala","groovy","gradle","c","h","cc","cpp","cxx","hpp","hh","hxx","cs","fs","vb","swift","m","mm","php","pl","pm","r","jl","lua","dart","ex","exs","erl","hrl","hs","ml","mli","clj","cljs","elm","nim","zig","v","sol","tf","hcl","nix","sh","bash","zsh","fish","ps1","psm1","bat","cmd","sql","graphql","gql","proto","thrift","avsc","rst","adoc","asciidoc","tex","bib","org","textile","diff","patch","srt","vtt","ics","vcf","gitignore","gitattributes","editorconfig","dockerignore","npmignore","prettierrc","eslintrc","babelrc","mailmap"]),fn=new Set(["readme","license","licence","copying","notice","authors","contributors","changelog","changes","todo","makefile","dockerfile","containerfile","procfile","gemfile","rakefile","vagrantfile","jenkinsfile","brewfile","codeowners"]),Tt=typeof ae.constants.O_NOFOLLOW=="number"?ae.constants.O_NOFOLLOW:0,St=typeof ae.constants.O_NONBLOCK=="number"?ae.constants.O_NONBLOCK:0,ct=e=>`${e.size}-${e.mtimeNs}`,mn=e=>e!==""&&e!=="."&&e!==".."&&!e.includes(":")&&!e.endsWith(".")&&!e.endsWith(" "),ut=e=>b.isAcceptableDocumentPath(e)&&e===e.normalize("NFC")&&e.split("/").every(mn),xt=e=>{const t=e.toLowerCase(),r=t.lastIndexOf(".");return r<0?"":t.slice(r+1)},pn=e=>{const t=xt(e);if(ln.has(t))return{kind:"markdown"};const r=bt.get(t);if(r!==void 0)return r.kind==="image"?{kind:"image"}:{kind:"media",mediaType:r.mediaType};const n=e.toLowerCase();return dn.has(t)||!n.includes(".")&&fn.has(n)?{kind:"text"}:{kind:"file"}},Ie=e=>{switch(typeof e=="object"&&e!==null?e.code:void 0){case"ENOENT":case"ENOTDIR":return"not-found";case"ELOOP":case"EACCES":case"EPERM":return"forbidden";case"ENAMETOOLONG":return"invalid";case"EISDIR":return"unsupported";default:return null}},Ot=e=>{const t=Ie(e);return t===null?e:new he(t)},hn=e=>{const t=typeof e=="object"&&e!==null?e.code:void 0;return t==="EACCES"||t==="EPERM"||t==="ENOENT"||t==="ENOTDIR"},lt=async(e,t)=>{const r=[];for await(const n of e.createReadStream({start:0,end:t-1,autoClose:!1}))r.push(n);return Buffer.concat(r)},wn=(e,t)=>e!==null?{start:e.offset,end:e.offset+e.length-1}:t===0n?{}:{start:0,end:Number(t)-1},gn=async(e,t,r,n)=>{let a;try{a=await me.open(e,ae.constants.O_RDONLY|Tt|St);const E=await a.stat({bigint:!0});if(!E.isFile()||E.ino!==t.ino||E.dev!==t.dev||E.size!==t.size||E.mtimeNs!==t.mtimeNs)throw new he("not-found")}catch(E){throw await a?.close(),Ot(E)}const s=a.createReadStream(wn(r,t.size)),c=Mt.Readable.toWeb(s),f=()=>{s.destroy(n.reason)};return n.aborted?f():n.addEventListener("abort",f,{once:!0}),c},En=(e,t)=>{const r=se.NAME_COLLATOR.compare(e,t);return r!==0?r:e===t?0:e<t?-1:1},yn=e=>{let t=0;const r=[];return async n=>{t<e?t+=1:await new Promise(a=>r.push(a));try{return await n()}finally{const a=r.shift();a===void 0?t-=1:a()}}},bn=(e,t)=>{if(e.isSymbolicLink())return"symbolic-link";if(!(e.isDirectory()||e.isFile()))return"special-file";const{name:r}=e;return r!==r.normalize("NFC")?"not-nfc":r.includes(":")?"colon":r.endsWith(".")||r.endsWith(" ")?"trailing-dot-or-space":b.isAcceptableDocumentPath(r)?b.isAcceptableDocumentPath(t)?null:"path-too-long":"control-character-or-backslash"},Tn=new Set(["id","label","root","pathPrefix","parse","deny","maxEntries","maxDocumentBytes","textPreviewBytes","walkConcurrency","cacheScope","reportSkipped"]),be=(e,t,r)=>{if(t===void 0)return r;if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] ${e} must be a positive integer; got ${String(t)}`);return t},Sn=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] createFileSystemSource needs an options object");for(const h of Object.keys(e))if(!Tn.has(h))throw new TypeError(`[markdown-explorer] createFileSystemSource does not know the option ${JSON.stringify(h)}`);const{id:t,label:r,root:n,parse:a}=e;if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] a file-system source needs a non-empty id");if(typeof r!="string"||r.trim()==="")throw new TypeError("[markdown-explorer] a file-system source needs a non-blank label");if(typeof a!="function")throw new TypeError("[markdown-explorer] a file-system source needs a parse function");if(typeof n!="string"||!re.isAbsolute(n))throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);let s;try{s=ae.statSync(n).isDirectory()}catch(h){throw new RangeError(`[markdown-explorer] root does not exist: ${n}`,{cause:h})}if(!s)throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);const c=ae.realpathSync(n),f=e.pathPrefix;if(typeof f!="string")throw new TypeError('[markdown-explorer] pathPrefix is required: "" for a source over the whole root, or relative segments ending with "/"');if(f!==""&&!(f.endsWith("/")&&ut(f.slice(0,-1))))throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(f)}`);const E=b.resolvePathRules(e.deny),k=be("maxEntries",e.maxEntries,ye.maxEntries),p=be("maxDocumentBytes",e.maxDocumentBytes,ye.maxDocumentBytes),w=be("textPreviewBytes",e.textPreviewBytes,ye.textPreviewBytes),O=be("walkConcurrency",e.walkConcurrency,ye.walkConcurrency),A=e.cacheScope===void 0?"principal":e.cacheScope;if(A!=="principal"&&A!=="shared")throw new RangeError(`[markdown-explorer] cacheScope must be "principal" or "shared"; got ${JSON.stringify(A)}`);const v=e.reportSkipped;if(v!==void 0&&typeof v!="function")throw new TypeError("[markdown-explorer] reportSkipped must be a function");const _=v===void 0?h=>{console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(h.sourceId)} does not list ${JSON.stringify(h.path)}: ${h.reason}`)}:v,R=new Set,D=h=>{const x=re.resolve(c,...h.split("/")),T=re.relative(c,x);return T===""||T===".."||T.startsWith(`..${re.sep}`)||re.isAbsolute(T)?null:x},S=(h,x)=>{const T=`${x}\0${h}`;R.has(T)||R.size>=k||(R.add(T),_({sourceId:t,path:h,reason:x}))},P=async({signal:h})=>{h.throwIfAborted();const x=new AbortController,T=()=>{x.abort(h.reason)};h.addEventListener("abort",T,{once:!0});const N=yn(O);let L=0;const F=async(I,G)=>{const K=await N(async()=>{x.signal.throwIfAborted();try{return await me.readdir(I,{withFileTypes:!0})}catch(z){if(G===""||!hn(z))throw z;return null}});if(x.signal.throwIfAborted(),K===null)return S(`${f}${G}`,"unreadable-directory"),null;const X=[];for(const z of K){if(E.deniesName(z.name))continue;const V=G===""?z.name:`${G}/${z.name}`,Q=`${f}${V}`,q=bn(z,Q);if(q!==null){S(Q,q);continue}X.push({dirent:z,relativePath:V,path:Q})}if(L+=X.length,L>k)throw new he("too-large");return X.sort((z,V)=>En(z.dirent.name,V.dirent.name)),(await Promise.all(X.map(async({dirent:z,relativePath:V,path:Q})=>{if(!z.isDirectory())return{name:z.name,path:Q,type:"file"};const q=await F(re.join(I,z.name),V);return q===null?null:{name:z.name,path:Q,type:"directory",children:q}}))).filter(z=>z!==null)};try{const I=await F(c,"");if(I===null)throw new Error("[markdown-explorer] the source's root could not be listed");return I}catch(I){throw x.abort(),I}finally{h.removeEventListener("abort",T)}},B=async h=>{if(!h.startsWith(f))return{status:"refused",reason:"not-found"};const x=h.slice(f.length);if(!ut(x))return{status:"refused",reason:"invalid"};if(E.deniesPath(x))return{status:"refused",reason:"forbidden"};const T=D(x);if(T===null)return{status:"refused",reason:"forbidden"};const N=await me.lstat(T,{bigint:!0});if(N.isSymbolicLink())return{status:"refused",reason:"forbidden"};if(!N.isFile())return{status:"refused",reason:"unsupported"};const L=await me.realpath(T);return L!==T||E.deniesPath(re.relative(c,L).split(re.sep).join("/"))?{status:"refused",reason:"forbidden"}:{status:"file",target:T,name:x.slice(x.lastIndexOf("/")+1),stats:N}},j=async(h,x,T)=>{let N;try{const L=await B(T);if(L.status==="refused")return b.failureDocument(L.reason);const{target:F,name:I,stats:G}=L,K=pn(I),X=ct(G);if(K.kind==="image")return{kind:"image",name:I,version:X};if(K.kind==="media")return{kind:"media",name:I,mediaType:K.mediaType,version:X};if(K.kind==="file")return{kind:"file",name:I,version:X};N=await me.open(F,ae.constants.O_RDONLY|Tt|St);const te=await N.stat({bigint:!0});if(!te.isFile()||te.ino!==G.ino||te.dev!==G.dev)return b.failureDocument("forbidden");if(K.kind==="markdown"){if(te.size>BigInt(p))return b.failureDocument("too-large");const q=await lt(N,p+1);if(q.length>p)return b.failureDocument("too-large");const we=await a(new TextDecoder("utf-8").decode(q),x);return{kind:"markdown",name:I,htmlContent:we.htmlContent,headings:we.headings}}const z=await lt(N,w);if(z.includes(0))return{kind:"file",name:I,version:X};const V=te.size>BigInt(w),Q=new TextDecoder("utf-8").decode(z,{stream:V});return{kind:"text",name:I,text:Q,truncated:V,version:X}}catch(L){const F=Ie(L);if(F===null)throw L;return b.failureDocument(F)}finally{await N?.close()}},d=async(h,x,T)=>{let N;try{N=await B(T)}catch(X){throw Ot(X)}if(N.status==="refused")throw new he(N.reason);const{target:L,name:F,stats:I}=N,G=bt.get(xt(F)),K=G===void 0?"":G.contentType;return{name:F,contentType:K,size:Number(I.size),version:ct(I),open:X=>gn(L,I,X,h.signal)}},y=async(h,x,T)=>{let N;try{N=await B(T)}catch(I){if(Ie(I)!==null)return null;throw I}if(N.status==="refused")return null;const L=T.slice(f.length).split("/");if(L.some(I=>E.deniesName(I)))return null;const F=L.slice(0,-1);return F.map((I,G)=>`${f}${F.slice(0,G+1).join("/")}`)};return Object.freeze({id:t,label:r,cacheScope:A,boundary:Object.freeze({contains:h=>h.startsWith(f)}),tree:P,ancestors:y,document:j,asset:d})};exports.DEFAULT_DENIED_PATH_SEGMENTS=b.DEFAULT_DENIED_PATH_SEGMENTS;exports.MAX_DOCUMENT_PATH_LENGTH=b.MAX_DOCUMENT_PATH_LENGTH;exports.isAcceptableDocumentPath=b.isAcceptableDocumentPath;exports.isDeniedPath=b.isDeniedPath;exports.ExplorerError=he;exports.anonymousAccess=vt;exports.createFileSystemSource=Sn;exports.createMarkdownExplorer=un;
|