@aiquants/markdown-explorer 0.32.0 → 0.34.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.
Files changed (57) hide show
  1. package/CHANGELOG.md +327 -0
  2. package/README.md +33 -19
  3. package/dist/{EditSurface-BPqqykro.cjs → EditSurface-CF82jZQg.cjs} +5 -5
  4. package/dist/{EditSurface-BmbDSrrw.js → EditSurface-CqHk2R3k.js} +73 -63
  5. package/dist/ExplorerSplit-D325YGEf.cjs +1 -0
  6. package/dist/ExplorerSplit-DGH9bckm.js +1500 -0
  7. package/dist/MultiLayout-CzR7yJ0m.cjs +1 -0
  8. package/dist/{MultiLayout-DKgZ1sBK.js → MultiLayout-kcZyVnvK.js} +176 -176
  9. package/dist/NativeScrollBar-UNed10Na.js +62 -0
  10. package/dist/NativeScrollBar-pUbA4Zq3.cjs +1 -0
  11. package/dist/TreeLayout-BnIU87HX.js +96 -0
  12. package/dist/TreeLayout-DtvIpuOe.cjs +1 -0
  13. package/dist/core/geometry.d.cts +1 -0
  14. package/dist/core/geometry.d.ts +1 -0
  15. package/dist/core/labels.d.cts +10 -0
  16. package/dist/core/labels.d.ts +10 -0
  17. package/dist/core/location.d.cts +2 -0
  18. package/dist/core/location.d.ts +2 -0
  19. package/dist/core/viewSettings.d.cts +2 -0
  20. package/dist/core/viewSettings.d.ts +2 -0
  21. package/dist/{dataRoute-DLhQfdoW.js → dataRoute-D6KiSHIc.js} +20 -20
  22. package/dist/index-BDCbvHDs.cjs +15 -0
  23. package/dist/{index-CcXMPCRS.js → index-DR31S_-4.js} +2029 -1929
  24. package/dist/index.cjs +1 -1
  25. package/dist/index.js +17 -17
  26. package/dist/{location-perTmwct.js → location-C44b9H1S.js} +291 -278
  27. package/dist/location-hGLhCCg4.cjs +1 -0
  28. package/dist/{merge-DZI4pkWI.cjs → merge-BziXxZkE.cjs} +1 -1
  29. package/dist/{merge-3xGYZqbE.js → merge-C1MWvhCS.js} +1 -1
  30. package/dist/{sanitizePolicy-By0tKOpZ.js → sanitizePolicy-CwvyPpp5.js} +1 -1
  31. package/dist/sanitizeWorker.js +1 -1
  32. package/dist/server.cjs +1 -1
  33. package/dist/server.js +4 -4
  34. package/dist/styles/markdown-explorer.css +1 -1
  35. package/dist/tapScrollCircle-D_BpaLwY.js +14 -0
  36. package/dist/tapScrollCircle-DigcJCsu.cjs +1 -0
  37. package/dist/useSplitPersistence-DCeYbJMx.js +38 -0
  38. package/dist/useSplitPersistence-QGcvyMAa.cjs +1 -0
  39. package/docs/behavior/dom-hooks.md +12 -3
  40. package/docs/behavior/layout.md +73 -23
  41. package/docs/behavior/localization.md +4 -3
  42. package/docs/behavior/security.md +2 -1
  43. package/docs/behavior/url-contract.md +11 -5
  44. package/package.json +11 -11
  45. package/dist/ExplorerSplit-CQxr6b0v.cjs +0 -1
  46. package/dist/ExplorerSplit-DPuXOBqs.js +0 -1493
  47. package/dist/MultiLayout-TXbet9k3.cjs +0 -1
  48. package/dist/NativeScrollBar-C1CtjwBm.js +0 -64
  49. package/dist/NativeScrollBar-UpjxjLlB.cjs +0 -1
  50. package/dist/TreeLayout-BpazybVQ.js +0 -72
  51. package/dist/TreeLayout-C0O1OGi4.cjs +0 -1
  52. package/dist/index-DSkK8iLE.cjs +0 -15
  53. package/dist/location-BxiJRTyw.cjs +0 -1
  54. package/dist/tapScrollCircle-Cbf17x8g.cjs +0 -1
  55. package/dist/tapScrollCircle-DacgW2F_.js +0 -12
  56. package/dist/useSplitPersistence-Du01PHNg.js +0 -42
  57. package/dist/useSplitPersistence-pPmE4GTT.cjs +0 -1
@@ -0,0 +1 @@
1
+ "use strict";const A=require("@aiquants/markdown/embeds"),T=require("@aiquants/markdown/viewer-settings"),L=require("./dataRoute-DwYtgyt6.cjs"),b=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Fe=Object.freeze(["UTF-8","IBM866","ISO-8859-2","ISO-8859-3","ISO-8859-4","ISO-8859-5","ISO-8859-6","ISO-8859-7","ISO-8859-8","ISO-8859-8-I","ISO-8859-10","ISO-8859-13","ISO-8859-14","ISO-8859-15","ISO-8859-16","KOI8-R","KOI8-U","macintosh","windows-874","windows-1250","windows-1251","windows-1252","windows-1253","windows-1254","windows-1255","windows-1256","windows-1257","windows-1258","x-mac-cyrillic","GBK","gb18030","Big5","EUC-JP","ISO-2022-JP","Shift_JIS","EUC-KR","replacement","UTF-16BE","UTF-16LE","x-user-defined"]),Ue=new Map(Fe.map(e=>[e.toLowerCase(),e])),$="UTF-8",ie=Object.freeze([Object.freeze({bytes:Object.freeze([239,187,191]),encoding:$}),Object.freeze({bytes:Object.freeze([255,254]),encoding:"UTF-16LE"}),Object.freeze({bytes:Object.freeze([254,255]),encoding:"UTF-16BE"})]),Ve=new Map([[$,"is read before any legacy encoding"],["UTF-16LE","is read only by its byte order mark"],["UTF-16BE","is read only by its byte order mark"],["ISO-2022-JP","writes only bytes below 0x80, which UTF-8 always reads first, so it would never be used"],["x-user-defined","is no text encoding (it maps bytes to private-use characters)"]]),Z=e=>{let t;try{t=new TextDecoder(e).encoding}catch(o){throw o instanceof RangeError?new RangeError(`[markdown-explorer] legacyTextEncoding ${JSON.stringify(e)} is no encoding label TextDecoder knows (for example "Shift_JIS" or "windows-1252")`):o}const n=Ge(t),r=Ve.get(n);if(r!==void 0)throw new RangeError(`[markdown-explorer] legacyTextEncoding ${JSON.stringify(e)} names ${n}, which cannot be the legacy encoding: it ${r}`);return n},Ge=e=>{const t=Ue.get(e);if(t===void 0)throw new RangeError(`[markdown-explorer] TextDecoder answered ${JSON.stringify(e)}, which is no encoding of the WHATWG Encoding Standard`);return t},z=(e,t,n)=>{const r=n===null?null:Z(n),o=ie.find(({bytes:i})=>i.every((a,c)=>e[c]===a));if(o!==void 0)return{body:e.subarray(o.bytes.length),encodings:[o.encoding]};const s=t||e.length===0?void 0:ie.find(({bytes:i})=>e.length<i.length&&e.every((a,c)=>i[c]===a));return s!==void 0?{body:e.subarray(e.length),encodings:[s.encoding]}:{body:e,encodings:r===null?[$]:[$,r]}},Xe=(e,t,n)=>z(e,t,n).encodings,Be=(e,t,n)=>{try{return new TextDecoder(e,{fatal:!0,ignoreBOM:!0}).decode(t,{stream:!n})}catch(r){if(r instanceof TypeError)return null;throw r}},We=(e,t,n)=>{const r=Q(z(e,t,n),t);return r===null?null:r.text},Q=({body:e,encodings:t},n)=>{for(const r of t){const o=Be(r,e,n);if(o!==null)return{encoding:r,text:o}}return null},He=(e,t,n)=>{const r=z(e,t,n),o=Q(r,t);return o===null?r.encodings[0]:o.encoding},Je=(e,t,n)=>{const r=z(e,t,n),o=Q(r,t);return o!==null?o.text:new TextDecoder(r.encodings[0],{ignoreBOM:!0}).decode(r.body,{stream:!t})},P=new Intl.Collator("en",{numeric:!0,sensitivity:"variant"}),Ke=/^readme(?:\.|$)/iu,se=/^readme(?:\.[^.]*)?$/iu,ae=Object.freeze(["md","markdown","mdx","txt",""]),qe=e=>Ke.test(e),B=e=>e.type==="file"&&qe(e.name),ce=e=>{const t=e.lastIndexOf("."),n=ae.indexOf(t<0?"":e.slice(t+1).toLowerCase());return n<0?ae.length:n},Ye=(e,t)=>{const n=+!se.test(e.name)-+!se.test(t.name);if(n!==0)return n;const r=ce(e.name)-ce(t.name);if(r!==0)return r;const o=P.compare(e.name,t.name);return o!==0?o:P.compare(e.path,t.path)},Ze=e=>{let t=null;for(const n of e)B(n)&&(t===null||Ye(n,t)<0)&&(t=n);return t===null?null:t.path},W=Object.freeze({sortMode:"native",folderPlacement:"mixed",readmePlacement:"mixed",selectionMode:"single",doubleClickAction:"recursive",expandIconSize:8,alwaysExpanded:!1,revealDocument:!1,removeRootIndent:!1,lines:!0,expandIcons:!0,directoryIcons:!0,fileIcons:!0}),Qe=[!0,!1],et=(e,t)=>t?e.settingOn:e.settingOff,p=(e,t)=>({key:e,labelKey:t,values:Qe,formatValue:et,requiresItemSelection:!1}),tt=Object.freeze({native:e=>e.sortNative,asc:e=>e.sortAscending,desc:e=>e.sortDescending,oldest:e=>e.sortOldest,newest:e=>e.sortNewest}),_=Object.freeze([{key:"sortMode",labelKey:"settingSortMode",values:["native","asc","desc","oldest","newest"],formatValue:(e,t)=>tt[t](e),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:"readmePlacement",labelKey:"settingReadmePlacement",values:["mixed","first","last"],formatValue:(e,t)=>t==="mixed"?e.readmePlacementMixed:t==="first"?e.readmePlacementFirst:e.readmePlacementLast,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},p("alwaysExpanded","settingAlwaysExpanded"),p("revealDocument","settingRevealDocument"),p("removeRootIndent","settingRemoveRootIndent"),p("lines","settingTreeLines"),p("expandIcons","settingExpandIcons"),p("directoryIcons","settingDirectoryIcons"),p("fileIcons","settingFileIcons")]),nt=e=>e?_:_.filter(t=>!t.requiresItemSelection),we=e=>{const t=_.find(n=>n.key===e);if(t===void 0)throw new RangeError(`[markdown-explorer] no tree setting descriptor for ${e}`);return t},rt=(e,t)=>{const n=we(t).values,r=n[(n.indexOf(e[t])+1)%n.length];return{...e,[t]:r}},ot=(e,t,n)=>we(n).formatValue(e,t[n]),he=2,H=Object.freeze({}),ee=(e,t)=>Object.freeze(Object.fromEntries(_.filter(n=>t(n,e[n.key])).map(n=>[n.key,e[n.key]]))),le="directoriesFirst",it=e=>{if(!Object.hasOwn(e,le))return e;const{[le]:t,...n}=e;return Object.hasOwn(n,"folderPlacement")||typeof t!="boolean"?n:{...n,folderPlacement:t?"first":"mixed"}},st=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return H;const t=e;return t.version!==he||t.settings===null||typeof t.settings!="object"||Array.isArray(t.settings)?H:ee(it(t.settings),(n,r)=>n.values.includes(r))},at=(e,t)=>{const n=ee(t,(r,o)=>o!==void 0&&o!==e[r.key]);return Object.keys(n).length===0?e:Object.freeze({...e,...n})},ct=(e,t,n,r)=>ee({...e,[t]:n},(o,s)=>s!==void 0&&!(o.key===t&&s===r[t])),lt=e=>JSON.stringify({version:he,settings:e}),dt=(e,t,n)=>e===void 0||t===void 0?e===t?0:e===void 0?1:-1:n*(e-t),mt=e=>{const{sortMode:t,folderPlacement:n,readmePlacement:r}=e;if(t==="native"&&n==="mixed"&&r==="mixed")return;const o=(s,i)=>{const a=P.compare(s.name,i.name);return a!==0?a:P.compare(s.path,i.path)};return(s,i)=>{if(n!=="mixed"&&s.type!==i.type)return s.type==="directory"==(n==="first")?-1:1;if(r!=="mixed"){const c=B(s);if(c!==B(i))return c===(r==="first")?-1:1}if(t==="native")return 0;if(t==="asc")return o(s,i);if(t==="desc")return-o(s,i);const a=dt(s.modifiedAt,i.modifiedAt,t==="oldest"?1:-1);return a!==0?a:o(s,i)}},w=(1+Math.sqrt(5))/2,ut=100/w**3,ft=100/w**4,te=100/w**2,Se=13,gt=16,Et=Object.freeze({gripThickness:5,gripLength:34,barThickness:2,barLength:21}),J=Object.freeze([1,2,3,5,8,13,21,34,55]),wt=Object.freeze([89,144,233,377]),ne=44,ht=ne,St=24;2*J[3]+ne+J[0];const pt=1/w,xt=1/w**3,Ot="40ch",yt=e=>{if(!Number.isFinite(e)||e<=0)throw new RangeError(`[markdown-explorer] rootFontPixels must be a finite number > 0; got ${String(e)}`)},pe=e=>(yt(e),Se*e),Tt=e=>pe(e)*w**2,bt=233,_t=50,xe=100/w**3,It=100-xe,Rt=wt[0],h=(e,t)=>{if(!Number.isFinite(t)||t<0)throw new RangeError(`[markdown-explorer] ${e} must be a finite number >= 0; got ${String(t)}`)},kt=({trackInlineSize:e,gap:t,minColumnInlineSize:n,logicalColumns:r})=>{if(h("trackInlineSize",e),h("gap",t),!Number.isFinite(n)||n<=0)throw new RangeError(`[markdown-explorer] minColumnInlineSize must be a finite number > 0; got ${String(n)}`);if(!Number.isInteger(r)||r<1)throw new RangeError(`[markdown-explorer] logicalColumns must be a positive integer; got ${String(r)}`);const o=Math.floor((e+t)/(n+t));return Math.min(r,Math.max(1,o))},Nt=(e,t)=>{const{trackInlineSize:n,gap:r,minColumnInlineSize:o,logicalColumns:s}=t;if(!([n,r,o].every(Number.isFinite)&&n>0&&r>=0&&o>0))return e;const a=kt(t);if(e===null||a===e)return a;const c=Math.min(s,Math.max(1,e));if(a>c){const l=(c+1)*o+c*r+r/w;return n>=l?a:c}return n>=c*o+(c-1)*r?c:a},At=(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},(n,r)=>[Math.floor(r*e/t),Math.floor((r+1)*e/t)])},Lt=(e,t,n)=>{if(h("surfaceInlineSize",e),h("handlePixels",n),!Number.isFinite(t)||t<=0)throw new RangeError(`[markdown-explorer] measure must be a finite number > 0; got ${String(t)}`);return e>=2*t+n?"beside":"stacked"},X=(e,t,n)=>Math.max(t,Math.min(e,n)),de=(e,t,n,r)=>{const o=(X(e,0,n)+X(t,0,n))/2;return X(o-r/2,0,n-r)},Pt=(e,t,n)=>{for(const[r,o]of Object.entries(e))if(!Number.isFinite(o))throw new RangeError(`[markdown-explorer] anchor.${r} must be a finite number; got ${String(o)}`);return h("marginBox.width",t.width),h("marginBox.height",t.height),h("viewport.width",n.width),h("viewport.height",n.height),{left:de(e.left,e.right,n.width,t.width),top:de(e.top,e.bottom,n.height,t.height)}},Ct=31536e3,Dt=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,$t=e=>{if(typeof e!="string"||!Dt.test(e))throw new RangeError(`[markdown-explorer] settingsCookie must be a cookie-name token; got ${JSON.stringify(e)}`)},me=e=>typeof e=="number"&&Number.isFinite(e)&&e>0&&e<=te,Mt=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))return{};const n=e,{treeExplorer:r,treeExplorerHidden:o,multiExplorer:s,multiExplorerHidden:i,style:a,align:c}=n;return{...me(r)?{treeExplorer:r}:{},...o===!0?{treeExplorerHidden:o}:{},...me(s)?{multiExplorer:s}:{},...i===!0?{multiExplorerHidden:i}:{},...typeof a=="string"&&t.includes(a)?{style:a}:{},...typeof c=="string"&&T.CONTENT_ALIGNS.includes(c)?{align:c}:{}}},vt=(e,t)=>{if(e!==null)for(const n of e.split(";")){const r=n.indexOf("=");if(!(r<0)&&n.slice(0,r).trim()===t)return n.slice(r+1).trim()}},zt=(e,t)=>{if(e===void 0||e==="")return{};try{return Mt(JSON.parse(decodeURIComponent(e)),t)}catch{return{}}},M=100,jt=Math.floor(te*M)/M,Ft=e=>{const t=n=>Math.min(jt,Math.max(1,Math.round(n*M))/M);return encodeURIComponent(JSON.stringify({...e.treeExplorer===void 0?{}:{treeExplorer:t(e.treeExplorer)},...e.treeExplorerHidden===!0?{treeExplorerHidden:!0}:{},...e.multiExplorer===void 0?{}:{multiExplorer:t(e.multiExplorer)},...e.multiExplorerHidden===!0?{multiExplorerHidden:!0}:{},...e.style===void 0?{}:{style:e.style},...e.align===void 0?{}:{align:e.align}}))},Ut=(e,t,n)=>`${e}=${Ft(t)}; Path=/; Max-Age=${String(Ct)}; SameSite=Lax${n?"; Secure":""}`,K=Object.freeze({tree:"tree",multi:"multi",single:"single"}),Oe=Object.freeze({default:12,min:1,max:64}),ye=Object.freeze({default:4,min:1,max:6}),Te=Object.freeze({default:500,min:1,max:1e4}),be=Object.freeze({default:16,min:1,max:64}),_e=Object.freeze({default:16,min:1,max:64}),Ie=Object.freeze({default:2*1024*1024,min:1,max:256*1024*1024}),Re=Object.freeze({default:8*1024*1024,min:1,max:256*1024*1024}),Vt=/^\/(?:[A-Za-z0-9._~-]+\/)*[A-Za-z0-9._~-]+$/u,Gt=/^[A-Za-z0-9][A-Za-z0-9_-]*$/u,Xt=/^[a-z0-9][a-z0-9-]*$/u,Bt=/^(?=.{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,ue=(e,t)=>{if(typeof t!="string")throw new TypeError(`[markdown-explorer] ${e} must be a string; got ${typeof t}`);if(!Vt.test(t)||t.split("/").some(n=>n==="."||n===".."))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)}`)},m=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"?b(e)?"a plain object":`a non-plain object (${Object.prototype.toString.call(e)})`:String(e),fe=Object.freeze(Object.keys({basePath:!0,dataPath:!0,settingsCookie:!0,views:!0,multiView:!0,expandAll:!0,revealDocument:!0,documentStyles:!0,defaultDocumentStyle:!0,iframeHosts:!0,embeds:!0,defaultTreeSettings:!0,legacyTextEncoding:!0,spreadsheets:!0})),O=(e,t,n)=>{if(t===void 0)return[];if(!b(t))throw new TypeError(`[markdown-explorer] ${e} must be a plain object; got ${m(t)}`);const r=Object.entries(t);for(const[o]of r)if(!n.includes(o))throw new RangeError(`[markdown-explorer] ${e}.${o} is not an option; expected ${n.join(", ")}`);return r.filter(([,o])=>o!==void 0)},Wt=e=>{const t={...K};for(const[n,r]of O("views",e,Object.keys(K)))t[n]=r;for(const[n,r]of Object.entries(t))if(typeof r!="string"||!Gt.test(r))throw new RangeError(`[markdown-explorer] views.${n} must start with a letter or digit and use only letters, digits, "_" and "-"; got ${JSON.stringify(r)}`);return Object.freeze(t)},x=(e,t,n)=>{if(t===void 0)return n.default;if(typeof t!="number"||!Number.isInteger(t)||t<n.min||t>n.max)throw new RangeError(`[markdown-explorer] ${e} must be an integer in ${String(n.min)}..${String(n.max)}; got ${m(t)}`);return t},Ht=(e,t)=>{const n=new Map(O("embeds",e,["providers","linkCards","linkCardSize"]));if(n.size===0)return A.NO_EMBEDS;const r=n.has("providers")?n.get("providers"):[];if(!Array.isArray(r))throw new RangeError(`[markdown-explorer] embeds.providers must be an array of provider ids; got ${m(r)}`);for(const a of r)if(!A.isEmbedProviderId(a))throw new RangeError(`[markdown-explorer] embeds.providers must hold only ${A.EMBED_PROVIDER_IDS.join(", ")}; got ${m(a)}`);const o=n.has("linkCards")?n.get("linkCards"):!1;if(typeof o!="boolean")throw new RangeError(`[markdown-explorer] embeds.linkCards must be a boolean; got ${m(o)}`);const s={providers:Object.freeze([...new Set(r)]),linkCardEndpoint:o?L.explorerLinkCardEndpoint(t):null};if(!n.has("linkCardSize"))return Object.freeze(s);const i=n.get("linkCardSize");if(!A.isLinkCardSize(i))throw new RangeError(`[markdown-explorer] embeds.linkCardSize must be one of ${A.LINK_CARD_SIZES.join(", ")}; got ${m(i)}`);if(!o)throw new RangeError(`[markdown-explorer] embeds.linkCardSize needs embeds.linkCards: true; got linkCardSize ${m(i)} with linkCards ${m(o)}`);return Object.freeze({...s,linkCardSize:i})},Jt=e=>{if(e===void 0)return null;if(typeof e!="string")throw new TypeError(`[markdown-explorer] legacyTextEncoding must be a string; got ${m(e)}`);return Z(e)},Kt=e=>{const t=new Map(O("defaultTreeSettings",e,_.map(r=>r.key)));if(t.size===0)return W;const n={...W};for(const r of _){if(!t.has(r.key))continue;const o=t.get(r.key),s=r.values;if(!s.includes(o))throw new RangeError(`[markdown-explorer] defaultTreeSettings.${r.key} must be one of ${s.map(m).join(", ")}; got ${m(o)}`);n[r.key]=o}return Object.freeze(n)},ke=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the explorer configuration must be an object");for(const l of Object.keys(e))if(!fe.includes(l))throw new RangeError(`[markdown-explorer] ${l} is not an option of the explorer configuration; expected ${fe.join(", ")}`);ue("basePath",e.basePath),ue("dataPath",e.dataPath);const t=Wt(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 l=e.dataPath.slice(e.basePath.length+1).split("/")[0];if(l===t.tree||l===t.multi||l===t.single)throw new RangeError(`[markdown-explorer] dataPath must not start with a view slug under basePath; got ${JSON.stringify(e.dataPath)}`)}$t(e.settingsCookie);const n=e.iframeHosts??[];if(!Array.isArray(n)||n.some(l=>typeof l!="string"||!Bt.test(l)))throw new RangeError(`[markdown-explorer] iframeHosts must be lowercase host names without scheme, port or path; got ${JSON.stringify(n)}`);const r=Object.fromEntries(O("multiView",e.multiView,["maxPanels","columns"])),o=Object.fromEntries(O("expandAll",e.expandAll,["maxFolders","maxDepth"])),s=Object.fromEntries(O("revealDocument",e.revealDocument,["maxDepth"])),i=Object.fromEntries(O("spreadsheets",e.spreadsheets,["maxBytes","maxWorkbookBytes"])),a=e.documentStyles??T.DEFAULT_MARKDOWN_STYLES;if(!Array.isArray(a)||a.length===0)throw new RangeError("[markdown-explorer] documentStyles must be a non-empty array");const c=new Set;for(const l of a){if(l===null||typeof l!="object"||typeof l.name!="string"||l.name.trim()===""||typeof l.className!="string")throw new RangeError("[markdown-explorer] each document style needs a non-blank name and a className string");if(c.has(l.name))throw new RangeError(`[markdown-explorer] document style names must be unique; ${JSON.stringify(l.name)} repeats`);c.add(l.name)}const u=e.defaultDocumentStyle===void 0?T.DEFAULT_MARKDOWN_STYLE:e.defaultDocumentStyle;if(typeof u!="string")throw new TypeError(`[markdown-explorer] defaultDocumentStyle must be a string; got ${m(u)}`);if(!c.has(u)){const l=e.defaultDocumentStyle===void 0?" (the default, DEFAULT_MARKDOWN_STYLE; name one of documentStyles)":"";throw new RangeError(`[markdown-explorer] defaultDocumentStyle must name a configured document style (${[...c].map(I=>JSON.stringify(I)).join(", ")}); got ${JSON.stringify(u)}${l}`)}return Object.freeze({basePath:e.basePath,dataPath:e.dataPath,settingsCookie:e.settingsCookie,views:t,multiView:Object.freeze({maxPanels:x("multiView.maxPanels",r.maxPanels,Oe),columns:x("multiView.columns",r.columns,ye)}),expandAll:Object.freeze({maxFolders:x("expandAll.maxFolders",o.maxFolders,Te),maxDepth:x("expandAll.maxDepth",o.maxDepth,be)}),revealDocument:Object.freeze({maxDepth:x("revealDocument.maxDepth",s.maxDepth,_e)}),documentStyles:Object.freeze(a.map(l=>Object.freeze({name:l.name,className:l.className}))),defaultDocumentStyle:u,iframeHosts:Object.freeze([...new Set(n)]),embeds:Ht(e.embeds,e.dataPath),defaultTreeSettings:Kt(e.defaultTreeSettings),legacyTextEncoding:Jt(e.legacyTextEncoding),spreadsheets:Object.freeze({maxBytes:x("spreadsheets.maxBytes",i.maxBytes,Ie),maxWorkbookBytes:x("spreadsheets.maxWorkbookBytes",i.maxWorkbookBytes,Re)})})},qt=e=>{const t=e.embeds;if(!b(t))throw new TypeError(`[markdown-explorer] config.embeds must be the embeds defineExplorerConfig resolved; got ${m(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 ${m(t.linkCards)})`);const n=e.legacyTextEncoding;if(n!==null&&typeof n!="string")throw new TypeError(`[markdown-explorer] config.legacyTextEncoding must be the encoding defineExplorerConfig resolved, or null; got ${m(n)}`);const{linkCardEndpoint:r,...o}=t,s=ke({...e,embeds:{...o,linkCards:r!==null},legacyTextEncoding:n===null?void 0:n});if(s.embeds.linkCardEndpoint!==r)throw new RangeError(`[markdown-explorer] config.embeds.linkCardEndpoint must be ${m(s.embeds.linkCardEndpoint)} (the data route's link-card path) or null; got ${m(r)}`);if(s.legacyTextEncoding!==n)throw new RangeError(`[markdown-explorer] config.legacyTextEncoding must be ${m(s.legacyTextEncoding)} (the written name of the encoding it names); got ${m(n)}`);const i=e;for(const[a,c]of Object.entries(s)){const u=q(i[a],c,a);if(u!==null)throw u.kind==="extra"?new RangeError(`[markdown-explorer] config.${u.path} is not a key of what defineExplorerConfig resolves; got ${m(u.given)} there`):new RangeError(`[markdown-explorer] config.${u.path} must be what defineExplorerConfig resolves; got ${m(u.given)} where it resolves ${m(u.resolved)}`)}return s},q=(e,t,n)=>{if(Object.is(e,t))return null;if(Array.isArray(t)){if(!Array.isArray(e))return{kind:"value",path:n,given:e,resolved:t};if(e.length!==t.length)return{kind:"value",path:`${n}.length`,given:e.length,resolved:t.length};for(const[o,s]of t.entries()){const i=q(e[o],s,`${n}[${String(o)}]`);if(i!==null)return i}return null}if(!(b(t)&&b(e)))return{kind:"value",path:n,given:e,resolved:t};for(const o of Object.keys(t)){const s=q(Object.hasOwn(e,o)?e[o]:void 0,t[o],`${n}.${o}`);if(s!==null)return s}const r=Object.keys(e).find(o=>!Object.hasOwn(t,o));return r===void 0?null:{kind:"extra",path:`${n}.${r}`,given:e[r]}},Ne=e=>typeof e=="string"&&Xt.test(e),Yt=(e,t)=>{if(e===null||typeof e!="object")throw new TypeError(`[markdown-explorer] withExplorerSources needs the configuration of defineExplorerConfig; got ${m(e)}`);if(!Array.isArray(t)||t.length===0)throw new RangeError(`[markdown-explorer] sourceIds must be a non-empty array; got ${m(t)}`);for(const n of t)if(!Ne(n))throw new RangeError(`[markdown-explorer] each source id must use lowercase letters, digits and "-" and start with a letter or digit; got ${m(n)}`);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])})},Zt=e=>e.documentStyles.map(t=>t.name),d=Object.freeze({source:"source",doc:"doc",maximized:"maximized",style:"style",align:"align",showToc:"showToc",showStyle:"showStyle",showAlign:"showAlign",padding:"padding",width:"width",maxWidth:"maxWidth",markup:"markup"}),Ae="true",Le="true",v="/",ge=".data",Pe=256,Ce=/^\d+(?:\.\d+)?$/u,Y=/^\d+(?:\.\d+)?(?:px|rem|em|ch|vw|%)$/u,De=Object.freeze(["showToc","showStyle","showAlign"]),Ee=e=>{const t=encodeURIComponent(e.replaceAll("%","%25"));return t.endsWith(ge)?`${t.slice(0,-ge.length)}%2Edata`:t},Qt=e=>e.replaceAll("%25","%"),$e=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},en=(e,t,n)=>{const r=n.getAll(d.source);if(r.length===0)return t;const[o]=r;return r.length>1||o===void 0||o===t||!e.includes(o)?null:o},tn=(e,t)=>{const n=t.get(d.style),r=t.get(d.align);return{...n!==null&&e.documentStyles.some(o=>o.name===n)?{style:n}:{},...r!==null&&T.CONTENT_ALIGNS.includes(r)?{align:r}:{}}},Me=e=>Number.isFinite(e)&&e>=0&&e<=Pe&&Ce.test(String(e)),nn=e=>{const t=e.get(d.padding),n=t!==null&&Ce.test(t)?Number(t):Number.NaN,r=e.get(d.width),o=e.get(d.maxWidth);return{...e.get(d.showToc)==="false"?{showToc:!1}:{},...e.get(d.showStyle)==="false"?{showStyle:!1}:{},...e.get(d.showAlign)==="false"?{showAlign:!1}:{},...Me(n)?{padding:n}:{},...r!==null&&Y.test(r)?{width:r}:{},...o!==null&&Y.test(o)?{maxWidth:o}:{}}},ve=(e,t)=>[...new Set(t.filter(L.isAcceptableDocumentPath))].slice(0,e.multiView.maxPanels),rn=(e,t,n,r)=>{for(const s of t)re(s);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(n!==null&&!t.includes(n))throw new RangeError(`[markdown-explorer] the maximized document must be one of the open documents; got ${JSON.stringify(n.slice(0,80))}`);if(new Set(r).size!==r.length)throw new RangeError(`[markdown-explorer] the documents shown as written must each appear once; got ${String(r.length)} with repeats`);const o=r.find(s=>!t.includes(s));if(o!==void 0)throw new RangeError(`[markdown-explorer] a document shown as written must be one of the open documents; got ${JSON.stringify(o.slice(0,80))}`)},re=e=>{if(!L.isAcceptableDocumentPath(e))throw new RangeError(`[markdown-explorer] not an acceptable document path: ${JSON.stringify(String(e).slice(0,80))}`);return e},on=e=>{if(re(e).endsWith(v))throw new RangeError(`[markdown-explorer] a document path ending in a slash has no URL (its segment would name a folder): ${JSON.stringify(e.slice(0,80))}`);return e},sn=(e,t)=>{if(t.style!==void 0&&!e.documentStyles.some(n=>n.name===t.style))throw new RangeError(`[markdown-explorer] overrides.style must name a configured document style (${e.documentStyles.map(n=>JSON.stringify(n.name)).join(", ")}); got ${JSON.stringify(t.style)}`);if(t.align!==void 0&&!T.CONTENT_ALIGNS.includes(t.align))throw new RangeError(`[markdown-explorer] overrides.align must be one of ${T.CONTENT_ALIGNS.join(", ")}; got ${JSON.stringify(t.align)}`)},an=e=>{for(const t of De)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&&!Me(e.padding))throw new RangeError(`[markdown-explorer] embed.padding must be 0..${String(Pe)} px in plain decimal digits; got ${String(e.padding)}`);for(const t of["width","maxWidth"]){const n=e[t];if(n!==void 0&&!Y.test(n))throw new RangeError(`[markdown-explorer] embed.${t} must be a CSS length in px, rem, em, ch, vw or %; got ${JSON.stringify(n)}`)}},ze=(e,t)=>{const n=new URLSearchParams;let r=`${e.basePath}/${e.views[t.view]}`;if(t.view==="multi"){const i=t.docs??[],a=t.maximized??null,c=t.markup??[];rn(e,i,a,c);for(const u of i)n.append(d.doc,u);a!==null&&n.set(d.maximized,a);for(const u of i)c.includes(u)&&n.append(d.markup,u)}else{const i=t.doc??null,a=t.view==="tree"?t.folder??null:null;if(i!==null&&a!==null)throw new RangeError("[markdown-explorer] a tree view shows a document or a folder, not both");i!==null&&(r+=`/${Ee(on(i))}`),a!==null&&(r+=`/${Ee(`${re(a)}${v}`)}`)}if(t.source!==void 0){const i=$e(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]&&n.set(d.source,t.source)}t.view!=="multi"&&t.overrides!==void 0&&(sn(e,t.overrides),t.overrides.style!==void 0&&n.set(d.style,t.overrides.style),t.overrides.align!==void 0&&n.set(d.align,t.overrides.align));const o=t.view!=="multi"&&(t.doc!==void 0&&t.doc!==null||t.view==="tree"&&t.folder!==void 0&&t.folder!==null);if(t.view==="tree"&&t.maximized===!0){if(!o)throw new RangeError("[markdown-explorer] a tree view without a document or a folder has nothing to maximize");n.set(d.maximized,Le)}if(t.view!=="multi"&&t.markup===!0){if(!o)throw new RangeError("[markdown-explorer] a tree view without a document or a folder has nothing to show as written");n.set(d.markup,Ae)}if(t.view==="single"&&t.embed!==void 0){const{embed:i}=t;an(i);for(const a of De)i[a]===!1&&n.set(d[a],"false");i.padding!==void 0&&n.set(d.padding,String(i.padding)),i.width!==void 0&&n.set(d.width,i.width),i.maxWidth!==void 0&&n.set(d.maxWidth,i.maxWidth)}const s=n.toString();return s===""?r:`${r}?${s}`},cn=(e,t)=>Object.keys(e.views).find(n=>e.views[n]===t),ln=(e,t,n)=>{const r=$e(e),[o]=r;if(o===void 0)throw new RangeError("[markdown-explorer] the configuration has no source");const s=en(r,o,n),i=s===null?o:s,a=E=>({kind:"redirect",href:ze(e,E),location:E}),c=()=>a({view:"tree",source:i,doc:null,folder:null,overrides:{},markup:!1,maximized:!1});if(t===void 0||t==="")return c();const u=t.indexOf("/"),l=u<0?t:t.slice(0,u),I=u<0?null:t.slice(u+1),S=cn(e,l);if(S===void 0)return c();if(S==="multi"){const E=n.getAll(d.doc),y=ve(e,E),j=n.getAll(d.maximized),[F]=j,U=j.length===1&&F!==void 0&&y.includes(F)?F:null,V=n.getAll(d.markup),D=y.filter(N=>V.includes(N)),je=D.length===V.length&&D.every((N,G)=>N===V[G]);return I===null&&s!==null&&y.length===E.length&&y.every((N,G)=>N===E[G])&&(j.length===0||U!==null)&&je?{kind:"location",location:{view:"multi",source:i,docs:y,maximized:U,markup:D}}:a({view:"multi",source:i,docs:y,maximized:U,markup:D})}const C=I===null?null:Qt(I),f=C?.endsWith(v)===!0?C.slice(0,-v.length):null,g=C!==null&&f===null?C:null;if(g!==null&&!L.isAcceptableDocumentPath(g)||f!==null&&!L.isAcceptableDocumentPath(f))return c();const R=tn(e,n),k=(g!==null||f!==null)&&n.get(d.markup)===Ae;if(S==="single"){if(f!==null)return a({view:"tree",source:i,doc:null,folder:f,overrides:R,markup:k,maximized:!1});if(g===null)return c();const E=nn(n);return s===null?a({view:S,source:i,doc:g,overrides:R,embed:E,markup:k}):{kind:"location",location:{view:S,source:i,doc:g,overrides:R,embed:E,markup:k}}}const oe=(g!==null||f!==null)&&n.get(d.maximized)===Le;return s===null?a({view:S,source:i,doc:g,folder:f,overrides:R,markup:k,maximized:oe}):{kind:"location",location:{view:S,source:i,doc:g,folder:f,overrides:R,markup:k,maximized:oe}}};exports.ASSUMED_ROOT_FONT_PIXELS=gt;exports.COARSE_TARGET_PIXELS=ht;exports.COLUMN_MIN_MEASURE=Ot;exports.CONTROL_BLOCK_PIXELS=ne;exports.DEFAULT_TREE_SETTINGS=W;exports.DEFAULT_VIEW_SLUGS=K;exports.EDIT_SPLIT_DEFAULT_PERCENT=_t;exports.EDIT_SPLIT_MAX_PERCENT=It;exports.EDIT_SPLIT_MIN_PERCENT=xe;exports.EXPAND_ALL_DEPTH_LIMITS=be;exports.EXPAND_ALL_FOLDER_LIMITS=Te;exports.EXPLORER_DEFAULT_PERCENT=ut;exports.EXPLORER_MAX_PERCENT=te;exports.EXPLORER_MIN_REM=Se;exports.EXPLORER_MULTI_DEFAULT_PERCENT=ft;exports.FIBONACCI_SPACING_PIXELS=J;exports.FINE_TARGET_PIXELS=St;exports.GOLDEN_RATIO=w;exports.MULTI_VIEW_COLUMN_LIMITS=ye;exports.MULTI_VIEW_PANEL_LIMITS=Oe;exports.NAME_COLLATOR=P;exports.NO_TREE_SETTING_CHANGES=H;exports.PANEL_MAX_BLOCK_RATIO=pt;exports.PANEL_MIN_BLOCK_RATIO=xt;exports.PREFETCH_DWELL_MS=Rt;exports.REVEAL_DOCUMENT_DEPTH_LIMITS=_e;exports.SPLIT_HANDLE_PIXELS=Et;exports.SPLIT_PERSIST_DELAY_MS=bt;exports.SPREADSHEET_BYTE_LIMITS=Ie;exports.WORKBOOK_BYTE_LIMITS=Re;exports.advanceTreeSetting=rt;exports.applyTreeSettingChanges=at;exports.canonicalMultiDocuments=ve;exports.centeredDialogPosition=Pt;exports.columnGroups=At;exports.createEntryComparator=mt;exports.decodeText=We;exports.decodeTextLeniently=Je;exports.defineExplorerConfig=ke;exports.documentStyleNames=Zt;exports.editSplitOrientation=Lt;exports.explorerHref=ze;exports.explorerMinPixels=pe;exports.explorerSheetBelowPixels=Tt;exports.folderReadmeOf=Ze;exports.formatTreeSettingValue=ot;exports.isExplorerSourceId=Ne;exports.isPlainObject=b;exports.legacyTextEncodingOf=Z;exports.parseViewSettings=zt;exports.readCookieValue=vt;exports.readTreeSettingChanges=st;exports.recordTreeSettingChange=ct;exports.replanVisibleColumns=Nt;exports.resolveExplorerLocation=ln;exports.revalidateExplorerConfig=qt;exports.serializeTreeSettingChanges=lt;exports.textEncodingOf=He;exports.textEncodingsOf=Xe;exports.viewSettingsCookieString=Ut;exports.visibleTreeSettingDescriptors=nt;exports.withExplorerSources=Yt;
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("node-diff3"),r=require("./index-DSkK8iLE.cjs"),R=(n,t,i,l)=>{if(t===n||t===i)return{kind:"clean",text:i};if(i===n)return{kind:"clean",text:t};const d=g.diff3Merge(t.split(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("node-diff3"),r=require("./index-BDCbvHDs.cjs"),R=(n,t,i,l)=>{if(t===n||t===i)return{kind:"clean",text:i};if(i===n)return{kind:"clean",text:t};const d=g.diff3Merge(t.split(`
2
2
  `),n.split(`
3
3
  `),i.split(`
4
4
  `),{excludeFalseConflicts:!0}),o=[];let c=0;const u=s(l.ours),a=s(l.theirs);for(const e of d)e.ok!==void 0?o.push(...e.ok):e.conflict!==void 0&&(c+=1,o.push(`${r.CONFLICT_OURS_MARKER} ${u}`,...e.conflict.a,r.CONFLICT_SEPARATOR,...e.conflict.b,`${r.CONFLICT_THEIRS_MARKER} ${a}`));const f=o.join(`
@@ -1,5 +1,5 @@
1
1
  import { diff3Merge as d } from "node-diff3";
2
- import { C, a as R, b as u } from "./index-CcXMPCRS.js";
2
+ import { C, a as R, b as u } from "./index-DR31S_-4.js";
3
3
  const g = (n, o, e, l) => {
4
4
  if (o === n || o === e) return { kind: "clean", text: e };
5
5
  if (e === n) return { kind: "clean", text: o };
@@ -1,7 +1,7 @@
1
1
  import { CODE_META_ATTRIBUTE as w } from "@aiquants/markdown/code-blocks";
2
2
  import { allowedFrameUrlOf as O, reduceFrameFeatures as L, EMBED_FRAME_REFERRER_POLICIES as D, EMBED_LINK_ATTRIBUTE as T, placeholderLinkOf as I } from "@aiquants/markdown/embeds";
3
3
  import { SOURCE_LINES_ATTRIBUTE as E, parseSourceLines as z } from "@aiquants/markdown/source-lines";
4
- import { i as M, e as x } from "./dataRoute-DLhQfdoW.js";
4
+ import { i as M, e as x } from "./dataRoute-D6KiSHIc.js";
5
5
  const ee = 512;
6
6
  class H extends RangeError {
7
7
  constructor(o) {
@@ -1,6 +1,6 @@
1
1
  import { parentPort as W } from "node:worker_threads";
2
2
  import q from "isomorphic-dompurify";
3
- import { M as D, c as K, H as Y } from "./sanitizePolicy-By0tKOpZ.js";
3
+ import { M as D, c as K, H as Y } from "./sanitizePolicy-CwvyPpp5.js";
4
4
  import { defaultTreeAdapter as w, parse as Z, html as ee } from "parse5";
5
5
  const te = 4096, P = 1024, B = /* @__PURE__ */ Symbol("placement"), G = 2, re = 3, ne = /* @__PURE__ */ new Set(["html", "head", "body"]), A = 0, L = 1, M = 2, z = 3, U = 4, C = 5, N = 6, _ = 7, F = 8, b = 9, Q = 10, T = -1, oe = 0, se = 1, ae = 2, ie = 3, ce = 4, le = 5, j = 6, ue = 7, fe = (t) => {
6
6
  switch (t) {
package/dist/server.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("./dataRoute-DwYtgyt6.cjs"),J=require("./location-BxiJRTyw.cjs"),St=require("node:crypto"),nr=require("@aiquants/markdown/server"),Ae=require("@aiquants/request-isolation"),Pe=require("react-router"),ue=require("node:fs"),ie=require("node:path"),Ie=require("node:url"),or=require("node:worker_threads"),we=require("node:fs/promises"),sr=require("node:stream");var Le=typeof document<"u"?document.currentScript:null;const Ke=Object.freeze({kind:"anonymous"}),ir=Object.freeze({authenticate:async()=>({status:"signed-in",principal:Ke}),principalKey:()=>Ke.kind,signedOutPage:(e,t)=>new Response(null,{status:401,headers:t})}),Ot="application/octet-stream",Rt="application/pdf",ar=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",Rt]),_t="default-src 'none'; media-src 'self'; style-src 'unsafe-inline'",At=`${_t}; sandbox`,cr=`${_t}; sandbox allow-same-origin`,Qe=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,ur=/^[\t\n\r ]+|[\t\n\r ]+$/gu,Ce=/^[\t ]+|[\t ]+$/gu,dr=e=>{const t=[];let r="",n=0;for(;;){for(;n<e.length&&e[n]!=='"'&&e[n]!==",";)r+=e[n],n+=1;if(n<e.length&&e[n]==='"'){const i=n;for(n+=1;n<e.length&&e[n]!=='"';)n+=e[n]==="\\"?2:1;if(n=Math.min(n+1,e.length),r+=e.slice(i,n),n<e.length)continue}if(t.push(r.replace(Ce,"")),r="",n>=e.length)return t;n+=1}},lr=e=>{const t=e.replace(ur,""),r=t.indexOf("/");if(r<0)return null;const n=t.slice(0,r),i=t.indexOf(";",r+1),o=t.slice(r+1,i<0?t.length:i).replace(/[\t\n\r ]+$/u,"");return Qe.test(n)&&Qe.test(o)?`${n}/${o}`.toLowerCase():null},fr=e=>{let t=null;for(const r of dr(e)){const n=lr(r);n!==null&&n!=="*/*"&&(t=n)}return t},mr=/['()*]/gu,vt=e=>encodeURIComponent(e).replace(mr,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Fe=Object.freeze({"Cache-Control":"private, max-age=60, stale-while-revalidate=600, no-transform",Vary:"Cookie"}),Nt=(e,t)=>{const r=fr(e),n=r!==null&&ar.has(r),i=n&&(r.startsWith("audio/")||r.startsWith("video/"));return{contentType:r===null?Ot:r,inline:n,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`${n?"inline":"attachment"}; filename*=UTF-8''${vt(t)}`,...r===Rt?{}:{"Content-Security-Policy":i?cr:At},"Cross-Origin-Resource-Policy":"same-origin"}}},_e=64*1024,ke=e=>`text/plain; charset=${e}`,pr=e=>({"X-Content-Type-Options":"nosniff","Content-Disposition":`inline; filename*=UTF-8''${vt(e)}`,"Content-Security-Policy":At,"Cross-Origin-Resource-Policy":"same-origin"}),hr=(e,t)=>`${t===null?"":t};${e}`,wr=/^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu,xe=Object.freeze({kind:"whole"}),Ze=Object.freeze({kind:"unsatisfiable"}),Pt=(e,t,r)=>{const n=e.get("Range");if(n===null)return xe;const i=e.get("If-Range");if(i!==null&&i!==r)return xe;const o=wr.exec(n);if(o===null)return xe;const[,c,l,f]=o;if(f!==void 0){const g=Number(f);if(g===0)return Ze;const b=Math.max(0,t-g);return{kind:"partial",range:{offset:b,length:t-b}}}const x=Number(c),w=l===""?Number.POSITIVE_INFINITY:Number(l);return w<x?xe:x>=t?Ze:{kind:"partial",range:{offset:x,length:Math.min(w,t-1)-x+1}}},qe="W/",yr=e=>{const t=[];let r=0,n=!1;for(let i=0;i<e.length;i+=1)e[i]==='"'?n=!n:e[i]===","&&!n&&(t.push(e.slice(r,i).replace(Ce,"")),r=i+1);return t.push(e.slice(r).replace(Ce,"")),t},et=e=>e.startsWith(qe)?e.slice(qe.length):e,Ue=(e,t)=>{if(e===null)return!1;const r=yr(e);if(r.length===1&&r[0]==="*")return!0;const n=et(t);return r.some(i=>et(i)===n)},gr=(e,t)=>{let r=t;return e.pipeThrough(new TransformStream({transform:(n,i)=>{const o=n.byteLength>r?n.subarray(0,r):n;r-=o.byteLength,i.enqueue(o),r===0&&i.terminate()},flush:n=>{r>0&&n.error(new RangeError("[markdown-explorer] the asset ended before its declared length"))}}))},pe=async(e,t,r,n,i)=>{if(n!==null&&r.set("Content-Length",String(n)),e.method.toUpperCase()==="HEAD")return new Response(null,{status:t,headers:r});const o=await i();return new Response(n===null?o:gr(o,n),{status:t,headers:r})},It=(e,t)=>{const r=new Headers(e);for(const[n,i]of Object.entries({"Accept-Ranges":"bytes","Content-Range":`bytes */${t}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff"}))r.set(n,i);return new Response(null,{status:416,headers:r})},Er=async(e,t,r)=>{const n=`"${t.version}"`,i=Nt(t.contentType,t.name),o=new Headers(r);for(const[f,x]of Object.entries({...i.headers,...Fe,ETag:n}))o.set(f,x);if(Ue(e.headers.get("If-None-Match"),n))return new Response(null,{status:304,headers:o});if(o.set("Content-Type",i.contentType),t.size===null)return pe(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 c=Pt(e.headers,t.size,n);if(c.kind==="unsatisfiable")return It(r,t.size);if(c.kind==="whole")return pe(e,200,o,t.size,()=>t.open(null));const{range:l}=c;return o.set("Content-Range",`bytes ${l.offset}-${l.offset+l.length-1}/${t.size}`),pe(e,206,o,l.length,()=>t.open(l))},br=(e,t)=>{const r=new Uint8Array(t);let n=0;for(const i of e){if(n===t)break;const o=i.subarray(0,t-n);r.set(o,n),n+=o.byteLength}return r},Tr=(e,t,r)=>new ReadableStream({start:n=>{for(const i of e)n.enqueue(i);t&&n.close()},pull:async n=>{const{done:i,value:o}=await r.read();i?n.close():n.enqueue(o)},cancel:n=>r.cancel(n)},{highWaterMark:0}),Lt=async(e,t,r)=>{const n=e.getReader(),i=t===null?_e:Math.min(t,_e),o=t===null?i+1:i,c=[];let l=0,f=!1;try{for(;l<o;){const{done:g,value:b}=await n.read();if(g){f=!0;break}c.push(b),l+=b.byteLength}if(f&&t!==null&&l<i)throw new RangeError("[markdown-explorer] the asset ended before its declared length");const x=t===null?f:t<=_e;return{encoding:J.textEncodingOf(br(c,Math.min(l,i)),x,r),body:Tr(c,f,n)}}catch(x){throw n.cancel(x).catch(()=>{}),x}},tt=async(e,t)=>{const r=await Lt(await e.open(e.size===null?null:{offset:0,length:Math.min(e.size,_e)}),e.size,t);return r.body.cancel().catch(()=>{}),r.encoding},kr=async(e,t,r,n)=>{const i=`"${hr(t.version,n)}"`,o=new Headers(r);for(const[l,f]of Object.entries({...pr(t.name),...Fe,ETag:i}))o.set(l,f);if(Ue(e.headers.get("If-None-Match"),i))return new Response(null,{status:304,headers:o});if(t.size===0)return o.set("Content-Type",ke(J.textEncodingOf(new Uint8Array(0),!0,n))),o.set("Content-Length","0"),new Response(null,{status:200,headers:o});if(t.size!==null){o.set("Accept-Ranges","bytes");const l=Pt(e.headers,t.size,i);if(l.kind==="unsatisfiable")return It(r,t.size);if(l.kind==="partial"){const{range:f}=l;return o.set("Content-Type",ke(await tt(t,n))),o.set("Content-Range",`bytes ${f.offset}-${f.offset+f.length-1}/${t.size}`),pe(e,206,o,f.length,()=>t.open(f))}}if(e.method.toUpperCase()==="HEAD")return o.set("Content-Type",ke(await tt(t,n))),pe(e,200,o,t.size,()=>t.open(null));const c=await Lt(await t.open(null),t.size,n);return o.set("Content-Type",ke(c.encoding)),pe(e,200,o,t.size,async()=>c.body)},xr=e=>`workbook;${e}`,Sr=async(e,t,r)=>{const n=`"${xr(t.version)}"`,i=Nt(Ot,t.name),o=new Headers(r);for(const[c,l]of Object.entries({...i.headers,...Fe,ETag:n}))o.set(c,l);return Ue(e.headers.get("If-None-Match"),n)?new Response(null,{status:304,headers:o}):(o.set("Content-Type",i.contentType),pe(e,200,o,t.size,()=>t.open(null)))},Or=Object.freeze({"Cache-Control":"private, no-store","Referrer-Policy":"no-referrer"}),Rr=(e,t)=>{const r=new Headers(t);for(const[n,i]of Object.entries(Or))r.set(n,i);return r.set("Location",e),new Response(null,{status:302,headers:r})},Me=(e,t)=>{const r=new AbortController,n=t(AbortSignal.any([e.signal,r.signal]));return new Promise(i=>{let o;const c=setTimeout(()=>{i(e.late),o=setTimeout(()=>r.abort(),e.handOverMs)},e.timeoutMs),l=()=>{clearTimeout(c),clearTimeout(o)};n.then(f=>{l(),i(f)},()=>{l(),i(e.late)})})},_r=Object.freeze({error:(e,t)=>{console.error(e,t)}}),Mt=Symbol.for("@aiquants/markdown-explorer:ExplorerError");class be extends Error{reason;code;constructor(t,r={}){if(!y.isExplorerFailureReason(t))throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${JSON.stringify(t)}`);if(r.code!==void 0&&!y.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,Mt,{value:!0})}}const Ar=e=>e instanceof Error&&Object.hasOwn(e,Mt)&&y.isExplorerFailureReason(e.reason),vr=e=>typeof e=="object"&&e!==null&&e.name==="AbortError",Xe=(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})}},ae=(e,t)=>Xe(e,`[markdown-explorer] ${t.operation} failed`,t),Nr=(e,t)=>Xe(e,`[markdown-explorer] ${t.operation} left out an entry`,t),$e=(e,t)=>Xe(e,`[markdown-explorer] ${t.operation} refused a path the deny rules match`,{...t,error:new RangeError("[markdown-explorer] the path matches a deny rule")}),rt=(e,t)=>{e===null||typeof e!="object"&&typeof e!="function"||Promise.resolve(e).then(void 0,t)},V=(e,t,r,n)=>Ar(e)?y.failureOf(e.reason,e.code):(vr(e)||r.aborted||ae(n,{...t,error:e}),{reason:"failed"}),nt=2*1024*1024,ot=256*1024*1024,Pr=async(e,t)=>{const r=e.getReader(),n=new Uint8Array(t);let i=0;for(;i<t;){const{done:o,value:c}=await r.read();if(o)return n.subarray(0,i);const l=c.subarray(0,t-i);n.set(l,i),i+=l.byteLength}return r.cancel().catch(()=>{}),n},Ir=async(e,t,r)=>{if(e.size===0)return{text:"",truncated:!1};const n=e.size!==null&&e.size>t,i=e.size===null?t+1:Math.min(e.size,t),o=await Pr(await e.open(n?{offset:0,length:t}:null),i);if(e.size!==null&&o.byteLength<i)throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");const c=n||o.byteLength>t,l=c?o.subarray(0,t):o,f=J.decodeTextLeniently(l,!c,r);return f.includes("\0")?null:{text:f,truncated:c}},st=(e,t)=>{if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] a cache ${e} must be a positive integer; got ${String(t)}`)},$t=(e,t)=>{st("capacity",e),t!==void 0&&st("weight budget",t.max);const r=new Map;let n=0;const i=o=>{const c=r.get(o);c!==void 0&&(r.delete(o),n-=c.weight)};return{get:o=>{const c=r.get(o);if(c!==void 0)return r.delete(o),r.set(o,c),c.value},set:(o,c)=>{i(o);const l=t===void 0?0:t.of(o,c);if(!(t!==void 0&&l>t.max)){r.set(o,{value:c,weight:l}),n+=l;for(const f of r.keys()){if(r.size<=e&&(t===void 0||n<=t.max))break;i(f)}}},delete:i,size:()=>r.size,weight:()=>n}},Dt=e=>Math.max(1,e-1),Lr=2147483647,it=Object.freeze({status:"aborted"}),fe=(e,t,r)=>{const n=(e.get(t)??0)+r;n===0?e.delete(t):e.set(t,n)},he=(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)}`)},Mr=e=>e!==null&&typeof e=="object"&&e.ready===!0&&!("id"in e),$r=(e,t)=>e!==null&&typeof e=="object"&&e.id===t&&"output"in e,Dr=({url:e,size:t,deadlineMs:r,jobsPerScope:n,maxQueuedJobs:i,heapLimits:o})=>{he("size",t,Number.MAX_SAFE_INTEGER),he("deadline",r,Lr),he("jobsPerScope",n,Number.MAX_SAFE_INTEGER),he("maxQueuedJobs",i,Number.MAX_SAFE_INTEGER),he("maxOldGenerationSizeMb",o.maxOldGenerationSizeMb,Number.MAX_SAFE_INTEGER),he("maxYoungGenerationSizeMb",o.maxYoungGenerationSizeMb,Number.MAX_SAFE_INTEGER);const c=Object.freeze({maxOldGenerationSizeMb:o.maxOldGenerationSizeMb,maxYoungGenerationSizeMb:o.maxYoungGenerationSizeMb}),l=new Set,f=[],x=new Map,w=new Map,g=Dt(t);let b=0;const v=(h,E)=>{const{job:M}=h;h.timer!==null&&clearTimeout(h.timer),h.timer=null,h.job=null,h.sent=!1,M!==null&&(fe(x,M.scope,-1),fe(w,M.scope,-1),M.settle(E))},j=h=>{const[E]=f.splice(h,1);E?.detach()},O=()=>{let h=-1,E=g,M=Number.POSITIVE_INFINITY;for(const[U,T]of f.entries()){const N=x.get(T.scope)??0,P=w.get(T.scope)??0;(N<E||N===E&&h>=0&&P<M)&&(h=U,E=N,M=P)}return h},R=(h,E)=>{l.has(h)&&(l.delete(h),v(h,E),h.worker.terminate().catch(()=>{}),F())},z=h=>{h.timer=setTimeout(()=>{R(h,{status:"timeout"})},r)},_=(h,E)=>h.sent?{status:"crashed",error:E}:{status:"unavailable",error:E},I=(h,E)=>{h.sent=!0,z(h);try{h.worker.postMessage({id:E.id,input:E.input})}catch(M){v(h,{status:"crashed",error:M}),h.worker.unref()}},C=()=>{const h={worker:new or.Worker(e,{resourceLimits:c}),job:null,sent:!1,timer:null,ready:!1};return h.worker.unref(),h.timer=setTimeout(()=>{R(h,{status:"unavailable",error:new Error(`[markdown-explorer] a worker did not start within ${String(r)} ms`)})},r),h.worker.on("message",E=>{if(!h.ready&&Mr(E)){h.ready=!0,h.timer!==null&&clearTimeout(h.timer),h.timer=null,h.job===null?h.worker.unref():I(h,h.job),h.job===null&&F();return}const{job:M}=h;if(M===null||!$r(E,M.id)){R(h,_(h,new Error("[markdown-explorer] a worker sent a message that answers no job")));return}v(h,{status:"done",output:E.output}),h.worker.unref(),F()}),h.worker.on("error",E=>{R(h,_(h,E))}),h.worker.on("messageerror",E=>{R(h,_(h,E))}),h.worker.on("exit",E=>{R(h,_(h,new Error(`[markdown-explorer] a worker exited with code ${String(E)}`)))}),l.add(h),h},F=()=>{for(;;){const h=O(),E=f[h];if(E===void 0)return;let M;for(const T of l)if(T.job===null){M=T;break}if(M===void 0&&l.size<t)try{M=C()}catch(T){j(h),fe(w,E.scope,-1),E.settle({status:"unavailable",error:T});continue}if(M===void 0)return;j(h),fe(x,E.scope,1);const U=M;U.job=E,U.worker.ref(),U.ready&&I(U,E)}};return{run:(h,{scope:E,signal:M})=>new Promise(U=>{if(M.aborted){U(it);return}if((w.get(E)??0)>=n){U({status:"refused",limit:"scope"});return}b+=1;const T={id:b,input:h,scope:E,settle:U,detach:()=>{}};f.push(T),fe(w,E,1),F();const N=f.indexOf(T);if(N<0)return;if(f.length>i){j(N),fe(w,E,-1),U({status:"refused",limit:"queue"});return}const P=()=>{const D=f.indexOf(T);D<0||(j(D),fe(w,E,-1),U(it))};M.addEventListener("abort",P,{once:!0}),T.detach=()=>{M.removeEventListener("abort",P)}}),workers:()=>l.size}},Ge=1024*1024,jr=3e4,zr=4*Ge,Cr=64*Ge,Hr=3,Br=2,Fr=(e,t)=>e+Dt(t)+Hr,Ur=4,Xr=32,Gr=512,Jr=64,Yr=4096,Wr=32,at=4096,Vr=4,jt=({workerHeapMb:e,maxHtmlBytes:t})=>Math.floor(((e-Jr)*Ge-t*Wr)/Yr),Kr=({maxHtmlBytes:e})=>e,Qr=({maxHtmlBytes:e})=>Vr*e,Zr=1024,qr=2147483647,en=64,tn=2**29,rn=1024*1024,nn=64,ct=Object.freeze({status:"rejected",reason:"too-large",cause:null}),De=Object.freeze({status:"rejected",reason:"failed",cause:null}),me=(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},on=(e,t)=>{if(e!==void 0&&(e===null||typeof e!="object"))throw new TypeError("[markdown-explorer] sanitizer must be an object of { workers, deadlineMs, maxHtmlBytes, cacheBytes, workerHeapMb, jobsPerScope, maxQueuedJobs }");const{workers:r,deadlineMs:n,maxHtmlBytes:i,cacheBytes:o,workerHeapMb:c,jobsPerScope:l,maxQueuedJobs:f}=e??{},x=me("workers",r,Br,en),w=me("jobsPerScope",l,Fr(t,x),Number.MAX_SAFE_INTEGER),g=Object.freeze({workers:x,deadlineMs:me("deadlineMs",n,jr,qr),maxHtmlBytes:me("maxHtmlBytes",i,zr,tn),cacheBytes:me("cacheBytes",o,Cr,Number.MAX_SAFE_INTEGER),workerHeapMb:me("workerHeapMb",c,Gr,rn),jobsPerScope:w,maxQueuedJobs:me("maxQueuedJobs",f,Ur*w,Number.MAX_SAFE_INTEGER)});if(g.jobsPerScope<t)throw new RangeError(`[markdown-explorer] sanitizer.jobsPerScope must be at least multiView.maxPanels (${String(t)}), because a page sends the document of every panel to the sanitizer at once for one reader; got ${String(g.jobsPerScope)}`);if(g.maxQueuedJobs<t)throw new RangeError(`[markdown-explorer] sanitizer.maxQueuedJobs must be at least multiView.maxPanels (${String(t)}), because a reader whose page finds every worker busy waits with the document of every panel; got ${String(g.maxQueuedJobs)}`);if(jt(g)<at)throw new RangeError(`[markdown-explorer] sanitizer.workerHeapMb (${String(g.workerHeapMb)} MiB) must leave room for ${String(at)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(g.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`);return g},sn=()=>{const e=typeof document>"u"?require("url").pathToFileURL(__filename).href:Le&&Le.tagName.toUpperCase()==="SCRIPT"&&Le.src||new URL("server.cjs",document.baseURI).href,t=new URL(`./sanitizeWorker${ie.extname(Ie.fileURLToPath(e))}`,e);if(!ue.existsSync(Ie.fileURLToPath(t)))throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${Ie.fileURLToPath(t)}`);return t},ut=new Map,an=(e,t)=>{const r=[e.href,t.workers,t.deadlineMs,t.workerHeapMb,t.jobsPerScope,t.maxQueuedJobs].map(String).join("\0");let n=ut.get(r);return n===void 0&&(n=Dr({url:e,size:t.workers,deadlineMs:t.deadlineMs,jobsPerScope:t.jobsPerScope,maxQueuedJobs:t.maxQueuedJobs,heapLimits:{maxOldGenerationSizeMb:t.workerHeapMb,maxYoungGenerationSizeMb:Xr}}),ut.set(r,n)),n},cn=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"},un=e=>e instanceof Error&&e.code==="ERR_WORKER_OUT_OF_MEMORY",dn=({iframeHosts:e,dataPath:t,options:r,pool:n})=>{const i=Object.freeze([...e]),o=jt(r),c=Kr(r),l=Qr(r),f=$t(Zr,{max:r.cacheBytes,of:(O,R)=>2*O.length+(R.status==="sanitized"?2*R.html.length:nn)}),x=new Map,w=new Map,g=O=>{x.get(O.key)===O&&x.delete(O.key);const R=w.get(O.hash);R?.delete(O),R?.size===0&&w.delete(O.hash)},b=async(O,R,z)=>{const _=await n.run({html:O,iframeHosts:i,dataPath:t,maxNodes:o,maxAttributeChars:c,maxSanitizedChars:l},{scope:R,signal:z});if(_.status==="refused"){const C=_.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(_.status==="aborted")return{outcome:De,lasting:!1};if(_.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(_.status==="unavailable")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker could not start",{cause:_.error})},lasting:!1};if(_.status==="crashed"&&un(_.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:_.error})},lasting:!0};if(_.status==="crashed")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker failed",{cause:_.error})},lasting:!0};const{output:I}=_;return cn(I)?I.status==="too-large"?{outcome:ct,lasting:!0}:I.status==="error"?{outcome:{status:"rejected",reason:"failed",cause:new Error(`[markdown-explorer] the HTML sanitizer failed: ${I.message}`)},lasting:!0}:I.html.length>l?{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer's output of ${String(I.html.length)} characters exceeds its limit of ${String(l)}`)},lasting:!0}:{outcome:{status:"sanitized",html:I.html},lasting:!0}:{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker answered something that is not an outcome")},lasting:!0}},v=(O,R,z,_)=>{let I=()=>{};const C=new Promise(E=>{I=E}),F={hash:R,key:z,outcome:C,answer:I,controller:new AbortController,waiters:0};x.set(z,F);const h=w.get(R);return h===void 0?w.set(R,new Set([F])):h.add(F),b(O,_,F.controller.signal).catch(E=>({outcome:{status:"rejected",reason:"failed",cause:E instanceof Error?E:new Error(String(E))},lasting:!0})).then(({outcome:E,lasting:M})=>{if(g(F),F.answer(E),!M)return;const U=f.get(R),T=U??(E.status==="rejected"?{...E,cause:null}:E);U===void 0&&f.set(R,T);for(const N of w.get(R)??[])g(N),N.answer(T),N.controller.abort()}),F},j=(O,R)=>new Promise(z=>{O.waiters+=1;const _=()=>{O.waiters-=1,z(De),!(O.waiters>0)&&(g(O),O.controller.abort())};R.addEventListener("abort",_,{once:!0}),O.outcome.then(I=>{R.removeEventListener("abort",_),z(I)})});return(O,{scope:R,signal:z})=>{if(O.length>r.maxHtmlBytes||Buffer.byteLength(O,"utf8")>r.maxHtmlBytes)return Promise.resolve(ct);const _=St.createHash("sha256").update(O,"utf8").digest("base64"),I=f.get(_);if(I!==void 0)return Promise.resolve(I);if(z.aborted)return Promise.resolve(De);const C=`${_}\0${R}`,F=x.get(C);return j(F===void 0?v(O,_,C,R):F,z)}},ve=e=>({result:e,json:JSON.stringify(e)}),je=Object.freeze(ve(Object.freeze({status:"error",failure:Object.freeze({reason:"failed"})}))),ln=e=>e.status==="ok"&&e.entries.length>0,fn=({ttlMs:e,maxEntries:t,maxBytes:r,now:n})=>{const i=$t(t,{max:r,of:(w,g)=>2*g.tree.json.length}),o=new Map,c=new Map,l=(w,g)=>{const b=new AbortController,v={waiters:0,superseded:!1,started:!1,loadTree:g},j=c.get(w),O=(C,F)=>{const h=ve(C);return!(v.superseded||b.signal.aborted)&&ln(C)&&i.set(w,{tree:h,loadedAt:F}),h},z=(async()=>{if(j!==void 0&&await j,b.signal.aborted)return je;const C=n();return v.started=!0,O(await v.loadTree(b.signal,C),C)})().finally(()=>{o.get(w)===_&&o.delete(w)}),_={promise:z,controller:b,state:v};o.set(w,_);const I=z.then(()=>{},()=>{});return c.set(w,I),I.then(()=>{c.get(w)===I&&c.delete(w)}),_},f=(w,g,b)=>{g.state.waiters+=1;const v=()=>{g.state.waiters-=1,!(g.state.waiters>0)&&(o.get(w)===g&&o.delete(w),g.controller.abort())};return b.addEventListener("abort",v,{once:!0}),g.promise.finally(()=>{b.removeEventListener("abort",v)})},x=w=>{i.delete(w);const g=o.get(w);g?.state.started&&(g.state.superseded=!0,o.delete(w))};return{load:(w,g,b)=>{if(g.aborted)return Promise.resolve(je);const v=i.get(w);if(v!==void 0){if(n()-v.loadedAt<e)return Promise.resolve(v.tree);i.delete(w)}const j=o.get(w);return f(w,j===void 0?l(w,b):j,g)},refresh:(w,g,b)=>{if(g.aborted)return Promise.resolve(je);x(w);const v=o.get(w);return v===void 0?f(w,l(w,b),g):(v.state.loadTree=b,f(w,v,g))},forget:x}},mn=e=>({load:(t,r,n)=>n(r,e()).then(ve),refresh:(t,r,n)=>n(r,e()).then(ve),forget:()=>{}}),S=e=>{throw new TypeError(`[markdown-explorer] ${e}`)},pn=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"}:y.isAcceptableDocumentPath(r)?null:{path:r,reason:"a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)"}},hn=(e,t,r,n)=>{if(e===null)return null;if(!Array.isArray(e))throw new TypeError(`[markdown-explorer] a source's ancestors must be null or an array of folder paths; got ${typeof e}`);const i=new Set;for(const o of e){if(typeof o!="string"||!y.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(i.has(o))throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");i.add(o)}return Object.freeze([...i])},wn=(e,t,r,n,i)=>{const o=new Set,c=f=>{if(!Array.isArray(f))return S("a source returned entries that are not an array");const x=[];for(const w of f){const g=l(w);g!==null&&x.push(g)}return x},l=f=>{const x=pn(f);if(x!==null)return n(x),null;const w=y.entryViolation(f);if(w!==null)return S(w);const g=f;if(o.has(g))return S("a source returned entries that contain themselves");const{name:b,path:v,type:j,mimeType:O,modifiedAt:R,children:z,lazy:_}=g;if(t.deniesName(b)||t.deniesPath(v))return null;if(!i(v))return n({path:v,reason:"a path outside the source's boundary"}),null;const I={name:b,path:v,...O===void 0?{}:{mimeType:O},...R===void 0?{}:{modifiedAt:R}};if(j==="file")return{...I,type:j};if(_===!0)return r?{...I,type:j,lazy:!0,children:[]}:S("a lazy directory came from a source without a children function");if(z===void 0)return{...I,type:j};o.add(g);const C=c(z);return o.delete(g),{...I,type:j,children:C}};return c(e)},yn=/^[\x21\x23-\x7E]{1,256}$/u,zt=e=>typeof e=="string"&&yn.test(e),gn=new Set(["text","image","media","spreadsheet","file"]),En=e=>typeof e=="string"&&gn.has(e),bn=(e,t,r)=>{if(e!==null&&typeof e=="object"){const o=e,{kind:c}=o;if(En(c)){if(Object.hasOwn(o,"url"))return S(`a ${c} document carries its version, not a url`);if(typeof o.name!="string")return S("a document needs a name string");if(!zt(o.version))return S(`a ${c} document needs a version of 1 to 256 visible ASCII characters other than '"'`);const l=t(o.version);switch(c){case"image":{const{imageType:f}=o;return y.isExplorerImageType(f)?{kind:c,name:o.name,url:l,imageType:f}:S(`unknown image type ${typeof f=="string"?JSON.stringify(f.slice(0,64)):typeof f}`)}case"file":return{kind:c,name:o.name,url:l};case"media":{const{mediaType:f}=o;return y.isExplorerMediaType(f)?{kind:c,name:o.name,url:l,mediaType:f}:S(`unknown media type ${typeof f=="string"?JSON.stringify(f.slice(0,64)):typeof f}`)}case"text":return typeof o.text!="string"||typeof o.truncated!="boolean"?S("a text document needs text and truncated"):{kind:c,name:o.name,text:o.text,truncated:o.truncated,url:l};case"spreadsheet":{const f=y.spreadsheetFieldsViolation(o);if(f!==null)return S(f);const{format:x,firstSheetText:w,edit:g}=o;return{kind:c,name:o.name,url:l,format:x,firstSheetText:w,edit:kn(g)}}}}}const n=y.documentViolation(e);if(n!==null)return S(n);const i=e;switch(i.kind){case"failure":{const{reason:o,code:c}=i.failure;return{kind:"failure",failure:y.failureOf(o,c)}}case"markdown":return i.headings.length>y.EXPLORER_MAX_HEADINGS?{kind:"failure",failure:y.failureOf("too-large")}:(i.edit?.kind==="inline"||i.edit?.kind==="draft")&&!r?S(`a markdown document offers ${i.edit.kind} editing, but the server has no edit ports`):{kind:"unsanitized-markdown",name:i.name,html:i.htmlContent,headings:i.headings.map(({text:o,depth:c,id:l})=>({text:o,depth:c,id:l})),edit:Tn(i.edit)}}},Tn=e=>{if(e===null)return null;switch(e.kind){case"inline":return{kind:"inline"};case"draft":return{kind:"draft"};case"external":return{kind:"external",href:e.href}}},kn=e=>e===null?null:{kind:"external",href:e.href},Ne=(e,t,r)=>typeof e!="string"?S(`${r} needs a text string`):e.includes("\0")?S(`${r} holds NUL, which no text editor can keep`):new TextEncoder().encode(e).byteLength>t?S(`${r} is over editMaxBytes (${t} bytes); refuse a longer source with ExplorerError "too-large"`):e,Ct=e=>y.isRootRelativeUrl(e.href)?{kind:"grant",href:e.href}:S("a grant needs a root-relative href"),xn=(e,t)=>{if(e===null||typeof e!="object")return S("an edit source must be an object");const r=e;return r.kind==="grant"?Ct(r):r.kind==="draft"?{kind:"draft",text:Ne(r.text,t,"a draft source")}:r.kind!=="edit"?S(`an edit source's kind must be "edit", "draft" or "grant"`):y.isExplorerEditToken(r.version)?typeof r.history!="boolean"?S("an edit source needs history"):{kind:"edit",text:Ne(r.text,t,"an edit source"),version:r.version,history:r.history}:S("an edit source needs a version of 1 to 1024 characters")},Sn=(e,t)=>{if(e===null||typeof e!="object")return S("a save result must be an object");const r=e;switch(r.kind){case"grant":return Ct(r);case"saved":return y.isExplorerEditToken(r.version)?{kind:"saved",version:r.version}:S("a saved result needs a version of 1 to 1024 characters");case"conflict":return y.isExplorerEditToken(r.version)?{kind:"conflict",version:r.version,text:Ne(r.text,t,"a conflict's current text")}:S("a conflict needs the current version of 1 to 1024 characters");default:return S(`a save result's kind must be "saved", "conflict" or "grant"`)}},On=e=>{if(e===null||typeof e!="object")return S("a preview must be an object");const{htmlContent:t,headings:r}=e;if(typeof t!="string"||!Array.isArray(r))return S("a preview needs htmlContent and headings");if(r.length>y.EXPLORER_MAX_HEADINGS)return{kind:"failure",failure:y.failureOf("too-large")};for(const n of r){const i=y.headingViolation(n);if(i!==null)return S(i)}return{html:t,headings:r.map(({text:n,depth:i,id:o})=>({text:n,depth:i,id:o}))}},Rn=e=>{if(!Array.isArray(e))return S("revisions must be an array");const t=new Set;return e.map(r=>{const n=y.revisionViolation(r);if(n!==null)return S(n);const{id:i,modifiedAt:o,size:c,author:l,kept:f,current:x}=r;return t.has(i)?S(`two revisions share the id ${JSON.stringify(i.slice(0,64))}`):(t.add(i),{id:i,modifiedAt:o,size:c,author:l,kept:f,current:x})})},_n=(e,t)=>Ne(e,t,"a revision"),He=e=>{if(e===null||typeof e!="object")return S("an asset file must be an object");const{name:t,contentType:r,size:n,version:i,open:o,kind:c}=e;return c!==void 0?S(c==="redirect"?"an asset redirect answers only a request for the stored file (options.delivery file), never one that reads the bytes":'an asset file has no kind (the only kind is "redirect")'):typeof t!="string"||t===""?S("an asset file needs a non-empty name"):typeof r!="string"?S("an asset file needs a contentType string ('' when unknown)"):n!==null&&!(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)?S("an asset file's size must be null or a non-negative safe integer"):zt(i)?typeof o!="function"?S("an asset file needs an open function"):Object.freeze({name:t,contentType:r,size:n,version:i,open:o}):S(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`)},An=e=>{if(e===null||typeof e!="object"||e.kind!=="redirect")return He(e);const{url:t}=e;if(typeof t!="string"||!URL.canParse(t))return S("an asset redirect needs an absolute https URL");const r=new URL(t);return r.protocol!=="https:"||r.username!==""||r.password!==""?S("an asset redirect's URL must be https and carry no credentials"):Object.freeze({kind:"redirect",url:r.href})},vn=e=>Array.isArray(e)?e.map(t=>{if(t===null||typeof t!="object")return S("a notice must be an object");const{id:r,tone:n,title:i,body:o,action:c}=t;if(typeof r!="string"||r===""||typeof i!="string")return S("a notice needs an id and a title");if(!y.isExplorerNoticeTone(n))return S(`unknown notice tone ${typeof n=="string"?JSON.stringify(n.slice(0,64)):typeof n}`);if(o!==void 0&&typeof o!="string")return S("a notice body must be a string");const f={id:r,tone:n,title:i,...o===void 0?{}:{body:o}};if(c===void 0)return f;if(c===null||typeof c!="object")return S("a notice action must be an object");const{label:x,href:w}=c;return typeof x!="string"||!y.isAcceptableUrl(w,y.EXPLORER_LINK_PROTOCOLS)?S("a notice action needs a label and an http(s), mailto or relative href"):{...f,action:{label:x,href:w}}}):S("notices must be an array"),Nn=4e3,Se=Object.freeze({ttlMs:3e5,maxEntries:64,maxBytes:64*1024*1024}),dt=32,Ht="private, no-store",Pn=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"}),In=22,Ln=2147483647,ze=Object.freeze([]),Mn=Object.freeze({status:"ok",source:null,ancestors:null}),lt=Object.freeze(["contains","confirm"]),ft=Object.freeze({readOnly:!1}),$n=Object.freeze({readOnly:!0}),ee=(e,t,r)=>{if(!(r&&t===void 0)&&typeof t!="function")throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${typeof t}`)},ye=(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},Dn=e=>{if(e===null||typeof e!="object"||!Object.isFrozen(e))throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");return J.revalidateExplorerConfig(e)},mt=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)")}},pt=e=>e instanceof Response?new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`):e,jn=e=>{if(typeof e!="string")throw new TypeError(`[markdown-explorer] scopeSecret must be a string; got ${typeof e}`);if(e.length<dt)throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(dt)} characters; got ${String(e.length)}`);return e},zn=(e,t)=>{if(!J.isPlainObject(t))throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);for(const r of Object.keys(t))if(!lt.includes(r))throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${lt.join(", ")}`);ee(`${e}.boundary.contains`,t.contains,!1),ee(`${e}.boundary.confirm`,t.confirm,!0)},Cn=e=>{if(!Array.isArray(e))throw new TypeError("[markdown-explorer] sources must be an array");const t=e;if(t.length===0)throw new RangeError("[markdown-explorer] sources must hold at least one source");const r=new Set;for(const[n,i]of t.entries()){if(i===null||typeof i!="object")throw new TypeError(`[markdown-explorer] sources[${String(n)}] must be an object`);const{id:o,label:c,boundary:l,tree:f,children:x,ancestors:w,cacheScope:g}=i;if(!J.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 b=`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 c!="string"&&typeof c!="function")throw new TypeError(`[markdown-explorer] ${b}.label must be a string or a function`);if(typeof c=="string"&&c.trim()==="")throw new RangeError(`[markdown-explorer] ${b}.label must not be blank`);if(zn(b,l),ee(`${b}.tree`,f,!1),ee(`${b}.children`,x,!0),ee(`${b}.ancestors`,w,!0),g!==void 0&&g!=="principal"&&g!=="shared")throw new RangeError(`[markdown-explorer] ${b}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(g)}`)}return t},Hn=e=>{if(e===!1)return!1;if(e===void 0)return Se;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?Se.ttlMs:ye("treeCache.ttlMs",t,Number.MAX_SAFE_INTEGER),maxEntries:r===void 0?Se.maxEntries:ye("treeCache.maxEntries",r,Number.MAX_SAFE_INTEGER),maxBytes:n===void 0?Se.maxBytes:ye("treeCache.maxBytes",n,Number.MAX_SAFE_INTEGER)}},ht=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},wt=(e,t)=>{if(!(t instanceof Response))throw new TypeError(`[markdown-explorer] ${e} must return a Response`);return t},yt=(e,t)=>{if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");return St.createHmac("sha256",e).update(t,"utf8").digest("base64url").slice(0,In)},Bn=e=>e.view==="multi"?e.docs:e.doc===null?[]:[e.doc],de=(e,t)=>{const r=e.getAll(t),[n]=r;return r.length===1&&n!==void 0&&n!==""?n:null},q=(e,t,r,n={})=>{const i=new Headers(r);for(const[o,c]of Object.entries({...Pn,...n}))i.set(o,c);return new Response(t,{status:e,headers:i})},$=(e,t,r)=>q(y.EXPLORER_FAILURE_STATUS[e.reason],JSON.stringify({failure:e}),t,r),Fn=new Set(["refresh","save","preview"]),Un=new Set(["edit","save","preview","revisions","revision"]),gt=(e,t)=>{const r=Fn.has(t)?["POST"]:["GET","HEAD"];return r.includes(e.method.toUpperCase())?null:q(405,JSON.stringify({failure:{reason:"invalid"}}),void 0,{Allow:r.join(", ")})},Et=e=>e.headers.get(y.EXPLORER_PROOF_HEADER)===y.EXPLORER_REFRESH_PROOF&&Ae.crossOriginRefusal(e,Ae.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Xn=e=>e.headers.get(y.EXPLORER_PROOF_HEADER)===y.EXPLORER_EDIT_PROOF&&Ae.crossOriginRefusal(e,Ae.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Gn=async(e,t)=>{const[r,...n]=(e.headers.get("Content-Type")??"").split(";").map(b=>b.trim().toLowerCase()),i=n.find(b=>b.startsWith("charset="));if(r!==y.EXPLORER_DRAFT_MEDIA_TYPE||i!==void 0&&i!=="charset=utf-8")return{status:"error",failure:{reason:"invalid"}};const o=Number(e.headers.get("Content-Length")??"0");if(Number.isFinite(o)&&o>t)return{status:"error",failure:{reason:"too-large"}};if(e.body===null)return{status:"ok",text:""};const c=e.body.getReader(),l=[];let f=0;for(;;){const{done:b,value:v}=await c.read();if(b)break;if(f+=v.byteLength,f>t)return await c.cancel(),{status:"error",failure:{reason:"too-large"}};l.push(v)}const x=new Uint8Array(f);let w=0;for(const b of l)x.set(b,w),w+=b.byteLength;let g;try{g=new TextDecoder("utf-8",{fatal:!0}).decode(x)}catch{return{status:"error",failure:{reason:"invalid"}}}return g.includes("\0")?{status:"error",failure:{reason:"invalid"}}:{status:"ok",text:g}},Jn=e=>{if(e===void 0)return;if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] edit must be an object of the editor's ports");const t=e;for(const r of["source","save","preview","revisions","revision"])ee(`edit.${r}`,t[r],!1);return e},Yn=({parentHeaders:e,loaderHeaders:t,errorHeaders:r})=>{const n=new Headers,i=r===void 0?[e,t]:[e,t,r];for(const o of i)for(const[c,l]of o)c!=="set-cookie"&&n.set(c,l);return n},Wn=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the server configuration must be an object");const t=Dn(e.config),r=jn(e.scopeSecret);ee("authenticate",e.authenticate,!1),ee("principalKey",e.principalKey,!1),ee("document",e.document,!1),ee("asset",e.asset,!1),ee("signedOutPage",e.signedOutPage,!1),ee("forbiddenPage",e.forbiddenPage,!0),ee("notices",e.notices,!0),ee("onTreeRefreshed",e.onTreeRefreshed,!0);const n=Cn(e.sources),i=J.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 c=e.logger===void 0?_r:e.logger,l=y.resolvePathRules(e.deny),f=e.deferredTimeoutMs===void 0?Nn:ye("deferredTimeoutMs",e.deferredTimeoutMs,Ln),x=e.textMaxBytes===void 0?nt:ye("textMaxBytes",e.textMaxBytes,ot),w=Jn(e.edit);if(w===void 0&&e.editMaxBytes!==void 0)throw new TypeError("[markdown-explorer] editMaxBytes needs the edit ports");const g=e.editMaxBytes===void 0?nt:ye("editMaxBytes",e.editMaxBytes,ot),b=Hn(e.treeCache),v=()=>Date.now(),j=b===!1?mn(v):fn({...b,now:v}),O=on(e.sanitizer,t.multiView.maxPanels),R=dn({iframeHosts:t.iframeHosts,dataPath:t.dataPath,options:O,pool:an(sn(),O)}),z=new Map(n.map(s=>[s.id,s])),_=J.documentStyleNames(t),{authenticate:I,principalKey:C,signedOutPage:F,forbiddenPage:h,onTreeRefreshed:E}=e,M=(s,u)=>{if(typeof s.label=="string")return s.label;const a=s.label(u);if(typeof a!="string"||a.trim()==="")throw new TypeError(`[markdown-explorer] the label of source ${JSON.stringify(s.id)} must be a non-blank string`);return a},U=(s,u)=>s.cacheScope==="shared"?s.id:`${s.id}\0${u}`,T=(s,u)=>{const a=m=>ae(c,{operation:"boundary",sourceId:s.id,path:u,error:m});let d;try{d=s.boundary.contains(u)}catch(m){return a(m),!1}return typeof d=="boolean"?d:(rt(d,a),a(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(s.id)} must return a boolean; got ${typeof d}`)),!1)},N=async(s,u,a)=>{const{confirm:d}=s.boundary;if(d===void 0)return{status:"inside",readPath:a};let m;try{m=await d(u,a)}catch(X){return{status:"error",failure:V(X,{operation:"boundary",sourceId:s.id,path:a},u.signal,c)}}const p=X=>(ae(c,{operation:"boundary",sourceId:s.id,path:a,error:new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(s.id)} ${X}`)}),{status:"outside"});if(m===null||typeof m!="object")return p(`must resolve to { inside, readPath? }; got ${m===null?"null":typeof m}`);const{inside:k,readPath:A}=m;return k===!1?{status:"outside"}:k!==!0||typeof A!="string"?p("must resolve to { inside: false } or { inside: true, readPath: string }"):!y.isAcceptableDocumentPath(A)||l.deniesPath(A)?(ae(c,{operation:"boundary",sourceId:s.id,path:a,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:A}},P=async(s,u)=>{const a=n.filter(m=>T(m,u));if(a.length===0)return{status:"error",failure:{reason:"forbidden"}};if(a.some(m=>m.boundary.confirm===void 0))return{status:"inside",readPath:u};let d=null;for(const m of a){const p=await N(m,s,u);if(p.status==="inside")return p;p.status==="error"&&d===null&&(d=p.failure)}return{status:"error",failure:d===null?{reason:"forbidden"}:d}},D=(s,u,a)=>{const d=({path:m,reason:p})=>Nr(c,{operation:a.operation,sourceId:a.sourceId,path:m,error:new TypeError(`[markdown-explorer] an entry with ${p} was left out`)});try{return{status:"ok",entries:wn(s,l,u.children!==void 0,d,m=>T(u,m))}}catch(m){return ae(c,{...a,error:m}),{status:"error",failure:{reason:"failed"}}}},G=async(s,u,a)=>{let d;try{d=await s.tree(u)}catch(p){return{status:"error",failure:V(p,{operation:"tree",sourceId:s.id},u.signal,c)}}const m=D(d,s,{operation:"tree",sourceId:s.id});return m.status==="ok"?{status:"ok",entries:m.entries,loadedAt:a}:m},W=(s,u,a,d)=>(m,p)=>G(s,{principal:u,request:a,signal:m,refresh:d},p),L=(s,u,a,d,m)=>j.load(U(s,a),m,W(s,u,d,!1)),K=(s,u,a,d)=>j.refresh(U(s,a),d.signal,W(s,u,d,!0)),Q=(s,u)=>{if(E===void 0)return;const a=d=>ae(c,{operation:"refresh",sourceId:s.id,error:d});try{rt(E(u),a)}catch(d){a(d)}},Y=async(s,u,a,d)=>{if(l.deniesPath(d)||!T(s,d))return{status:"error",failure:{reason:"forbidden"}};const m=await N(s,a,d);if(m.status==="outside")return{status:"error",failure:{reason:"forbidden"}};if(m.status==="error")return{status:"error",failure:m.failure};let p;try{p=await u(a,d,m.readPath)}catch(k){return{status:"error",failure:V(k,{operation:"children",sourceId:s.id,path:d},a.signal,c)}}return D(p,s,{operation:"children",sourceId:s.id,path:d})},ce=async(s,u,a,d)=>{const m=await N(s,a,d);if(m.status==="outside")return{status:"ok",ancestors:null};if(m.status==="error")return{status:"error",failure:m.failure};let p;try{p=await u(a,d,m.readPath,{maxDepth:t.revealDocument.maxDepth})}catch(k){return{status:"error",failure:V(k,{operation:"ancestors",sourceId:s.id,path:d},a.signal,c)}}if(Array.isArray(p)&&p.length>t.revealDocument.maxDepth)return{status:"ok",ancestors:null};try{return{status:"ok",ancestors:hn(p,d,l,k=>T(s,k))}}catch(k){return ae(c,{operation:"ancestors",sourceId:s.id,path:d,error:k}),{status:"error",failure:{reason:"failed"}}}},H=async(s,u,a,d)=>l.deniesPath(d)?{status:"error",failure:{reason:"forbidden"}}:T(s,d)?ce(s,u,a,d):{status:"ok",ancestors:null},re=async(s,u,a)=>{if(l.deniesPath(a))return{status:"error",failure:{reason:"forbidden"}};for(const d of[s,...n.filter(m=>m!==s)]){if(u.signal.aborted)break;const m=d.ancestors;if(m===void 0||!T(d,a))continue;const p=await ce(d,m,u,a);if(p.status==="ok"&&p.ancestors!==null)return{status:"ok",source:d.id,ancestors:p.ancestors}}return Mn},te=async(s,u,a)=>{if(l.deniesPath(a))return y.failureDocument("forbidden");const d=await P(s,a);if(d.status==="error")return{kind:"failure",failure:d.failure};let m;try{m=await e.document(s,a,d.readPath)}catch(A){return{kind:"failure",failure:V(A,{operation:"document",path:a},s.signal,c)}}let p;try{p=bn(m,A=>y.explorerAssetHref(t.dataPath,a,A),w!==void 0)}catch(A){return ae(c,{operation:"document",path:a,error:A}),y.failureDocument("failed")}if(p.kind!=="unsanitized-markdown")return p;const k=await R(p.html,{scope:u,signal:s.signal});return k.status==="sanitized"?{kind:"markdown",name:p.name,htmlContent:k.html,headings:p.headings,edit:p.edit}:(k.cause!==null&&ae(c,{operation:"document",path:a,error:k.cause}),y.failureDocument(k.reason))},ne=async s=>{if(e.notices===void 0)return ze;try{return vn(await e.notices(s))}catch(u){return V(u,{operation:"notices"},s.signal,c),ze}},le=async(s,u,a)=>{const d=de(u,y.EXPLORER_DATA_QUERY.path);if(d===null||!y.isAcceptableDocumentPath(d))return $({reason:"invalid"},a);const m=y.readExplorerAssetDisplay(u);if(m===null)return $({reason:"invalid"},a);if(l.deniesPath(d))return $e(c,{operation:"asset",path:d}),$({reason:"forbidden"},a);const p=await P(s,d);if(p.status==="error")return $(p.failure,a);try{const k=await e.asset(s,d,p.readPath,{delivery:m}),A=m==="file"?An(k):He(k);return"kind"in A?Rr(A.url,a):m==="text"?await kr(s.request,A,a,t.legacyTextEncoding):m==="workbook"?await Sr(s.request,A,a):await Er(s.request,A,a)}catch(k){return $(V(k,{operation:"asset",path:d},s.signal,c),a)}},Te=async(s,u)=>{if(l.deniesPath(u))return $e(c,{operation:"text",path:u}),y.failureDocument("forbidden");const a=await P(s,u);if(a.status==="error")return{kind:"failure",failure:a.failure};try{const d=He(await e.asset(s,u,a.readPath,{delivery:"text"})),m=await Ir(d,x,t.legacyTextEncoding);return m===null?y.failureDocument("unsupported"):{kind:"text",name:d.name,text:m.text,truncated:m.truncated,url:y.explorerAssetHref(t.dataPath,u,d.version)}}catch(d){return{kind:"failure",failure:V(d,{operation:"text",path:u},s.signal,c)}}},ge=async(s,u,a)=>l.deniesPath(a)?($e(c,{operation:u,path:a}),{status:"error",failure:{reason:"forbidden"}}):P(s,a),Yt=async(s,u,a)=>{const d=await ge(u,"edit",a);if(d.status==="error")return{kind:"failure",failure:d.failure};try{return xn(await s.source(u,a,d.readPath),g)}catch(m){return{kind:"failure",failure:V(m,{operation:"edit",path:a},u.signal,c)}}},Wt=async(s,u,a,d,m)=>{const p=await ge(u,"save",a);if(p.status==="error")return{kind:"failure",failure:p.failure};try{return Sn(await s.save(u,a,p.readPath,{text:m,baseVersion:d}),g)}catch(k){return{kind:"failure",failure:V(k,{operation:"save",path:a},u.signal,c)}}},Vt=async(s,u,a,d,m)=>{const p=await ge(u,"preview",d);if(p.status==="error")return{kind:"failure",failure:p.failure};let k;try{k=On(await s.preview(u,d,p.readPath,m))}catch(X){return{kind:"failure",failure:V(X,{operation:"preview",path:d},u.signal,c)}}if("kind"in k)return k.kind==="failure"?k:y.failureDocument("failed");const A=await R(k.html,{scope:a,signal:u.signal});return A.status==="sanitized"?{kind:"preview",htmlContent:A.html,headings:k.headings}:(A.cause!==null&&ae(c,{operation:"preview",path:d,error:A.cause}),y.failureDocument(A.reason))},Kt=async(s,u,a)=>{const d=await ge(u,"revisions",a);if(d.status==="error")return{kind:"failure",failure:d.failure};try{return{kind:"revisions",revisions:Rn(await s.revisions(u,a,d.readPath))}}catch(m){return{kind:"failure",failure:V(m,{operation:"revisions",path:a},u.signal,c)}}},Qt=async(s,u,a,d)=>{const m=await ge(u,"revision",a);if(m.status==="error")return{kind:"failure",failure:m.failure};try{return{kind:"revision",id:d,text:_n(await s.revision(u,a,m.readPath,d),g)}}catch(p){return{kind:"failure",failure:V(p,{operation:"revision",path:a},u.signal,c)}}},Zt=async(s,u,a,d,m,p)=>{const k=de(m,y.EXPLORER_DATA_QUERY.path);if(k===null||!y.isAcceptableDocumentPath(k))return $({reason:"invalid"},p);if(u==="edit")return q(200,JSON.stringify(await Yt(s,a,k)),p);if(u==="revisions")return q(200,JSON.stringify(await Kt(s,a,k)),p);if(u==="revision"){const oe=de(m,y.EXPLORER_DATA_QUERY.revision);return y.isExplorerEditToken(oe)?q(200,JSON.stringify(await Qt(s,a,k,oe)),p):$({reason:"invalid"},p)}const A=de(m,y.EXPLORER_DATA_QUERY.base);if(u==="save"&&!y.isExplorerEditToken(A))return $({reason:"invalid"},p);const X=await Gn(a.request,g);return X.status==="error"?$(X.failure,p):u==="preview"?q(200,JSON.stringify(await Vt(s,a,d,k,X.text)),p):q(200,JSON.stringify(await Wt(s,a,k,A,X.text)),p)},qt=async({request:s,url:u,params:a})=>{const d=ht(await I(s,ft)),m=mt(d.headers);if(m.set("Cache-Control",Ht),d.status==="signed-out")throw wt("signedOutPage",F(s,m));if(d.status==="forbidden")throw h===void 0?Pe.data(null,{status:403,headers:m}):wt("forbiddenPage",h(s,m));const p=J.resolveExplorerLocation(i,a["*"],u.searchParams);if(p.kind==="redirect")throw Pe.redirect(p.href,{headers:m});const{location:k}=p,{principal:A}=d,X=yt(r,C(A)),oe=z.get(k.source);if(oe===void 0)throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(k.source)}`);const Ee={signal:s.signal,timeoutMs:f,late:null,handOverMs:f},se={scope:X,sources:n.map(B=>({id:B.id,label:M(B,A)})),settings:J.parseViewSettings(J.readCookieValue(s.headers.get("Cookie"),t.settingsCookie),_),tree:k.view==="single"?null:{sourceId:k.source,result:Me(Ee,B=>L(oe,A,X,s,B).then(Z=>Z.result))},documents:Bn(k).map(B=>({path:B,document:Me(Ee,Z=>te({principal:A,request:s,signal:Z,refresh:!1},X,B))})),notices:Me({signal:s.signal,timeoutMs:f,late:ze,handOverMs:0},B=>ne({principal:A,request:s,signal:B,refresh:!1}))};return Pe.data(se,{headers:m})},Je=async(s,u)=>{const a=ht(await I(s,u));return{authentication:a,headers:mt(a.headers)}},er=async(s,u,a)=>{let d;try{d=await Je(u,ft)}catch(Z){return $(V(pt(Z),{operation:"authenticate"},u.signal,c))}const{authentication:m,headers:p}=d;if(m.status==="signed-out")return $({reason:"unauthorized"},p);if(m.status==="forbidden")return $({reason:"forbidden"},p);const{principal:k}=m;if(s==="asset")return le({principal:k,request:u,signal:u.signal,refresh:!1},a,p);const A=yt(r,C(k));p.set(y.EXPLORER_SCOPE_HEADER,A);const X={principal:k,request:u,signal:u.signal,refresh:!1},oe=()=>$({reason:"invalid"},p);if(s==="document"){const Z=de(a,y.EXPLORER_DATA_QUERY.path);if(Z===null||!y.isAcceptableDocumentPath(Z))return oe();const Ve=u.headers.has(y.EXPLORER_PROOF_HEADER);return Ve&&!Et(u)?$({reason:"forbidden"},p):q(200,JSON.stringify(await te({...X,refresh:Ve},A,Z)),p)}if(s==="text"){const Z=de(a,y.EXPLORER_DATA_QUERY.path);return Z===null||!y.isAcceptableDocumentPath(Z)?oe():q(200,JSON.stringify(await Te(X,Z)),p)}if(s==="edit"||s==="save"||s==="preview"||s==="revisions"||s==="revision")return w===void 0?$({reason:"not-found"},p):Zt(w,s,X,A,a,p);const Ee=de(a,y.EXPLORER_DATA_QUERY.source),se=de(a,y.EXPLORER_DATA_QUERY.path);if(Ee===null||(s==="children"||s==="ancestors"||s==="reveal")&&(se===null||!y.isAcceptableDocumentPath(se)))return oe();const B=z.get(Ee);if(B===void 0)return $({reason:"not-found"},p);if(s==="tree")return q(200,(await L(B,k,A,u,u.signal)).json,p);if(s==="refresh"){const Z=await K(B,k,A,u);return u.signal.aborted||Q(B,U(B,A)),q(200,Z.json,p)}return s==="ancestors"?B.ancestors===void 0||se===null?$({reason:"not-found"},p):q(200,JSON.stringify(await H(B,B.ancestors,X,se)),p):s==="reveal"?se===null?oe():q(200,JSON.stringify(await re(B,X,se)),p):B.children===void 0||se===null?$({reason:"not-found"},p):q(200,JSON.stringify(await Y(B,B.children,X,se)),p)},tr=async s=>{const{authentication:u,headers:a}=await Je(s,$n);if(!a.keys().next().done)throw new TypeError("[markdown-explorer] authenticate returned headers in read-only mode; a read-only authentication must only read the session (none was forwarded)");return u.status==="signed-in"},Ye=t.embeds.linkCardEndpoint===null?null:nr.createLinkCardHandler({authorize:tr}),rr=async(s,u)=>{try{return await s(u)}catch(a){return $(V(pt(a),{operation:"authenticate"},u.signal,c))}},We=async(s,u,a)=>{if(new URL(s.url).pathname.endsWith(".data"))return $({reason:"not-found"});if(!y.isExplorerDataOperation(a))return $({reason:"not-found"});if(a==="link-card"){if(Ye===null)return $({reason:"not-found"});const m=gt(s,a);return m!==null?m:rr(Ye,s)}if(Un.has(a)&&w===void 0)return $({reason:"not-found"});const d=gt(s,a);if(d!==null)return d;if(a==="refresh"&&!Et(s))return $({reason:"forbidden"});if((a==="save"||a==="preview")&&!Xn(s))return $({reason:"forbidden"});try{return await er(a,s,u.searchParams)}catch(m){return $(V(m,{operation:a},s.signal,c))}};return Object.freeze({loader:qt,headers:Yn,dataLoader:({request:s,url:u,params:a})=>We(s,u,a["*"]),dataAction:({request:s,url:u,params:a})=>We(s,u,a["*"]),forgetTree:s=>{if(typeof s!="string")throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof s}`);j.forget(s)}})},Oe=Object.freeze({maxEntries:2e4,maxDocumentBytes:2*1024*1024,textPreviewBytes:8*1024,walkConcurrency:8}),Vn=new Set(["md","markdown","mdx"]),bt="image/svg+xml",Bt=new Map([...[["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"],["svg",bt],["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",imageType:t===bt?"svg":"raster",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"}]]),Kn=new Map([["csv","csv"],["tsv","tsv"],["tab","tsv"],["xlsx","workbook"],["xlsm","workbook"],["ods","workbook"]]),Qn=new Set(["txt","text","log","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"]),Zn=new Set(["readme","license","licence","copying","notice","authors","contributors","changelog","changes","todo","makefile","dockerfile","containerfile","procfile","gemfile","rakefile","vagrantfile","jenkinsfile","brewfile","codeowners"]),Ft=typeof ue.constants.O_NOFOLLOW=="number"?ue.constants.O_NOFOLLOW:0,Ut=typeof ue.constants.O_NONBLOCK=="number"?ue.constants.O_NONBLOCK:0,Tt=e=>`${e.size}-${e.mtimeNs}`,qn=e=>e!==""&&e!=="."&&e!==".."&&!e.includes(":")&&!e.endsWith(".")&&!e.endsWith(" "),kt=e=>y.isAcceptableDocumentPath(e)&&e===e.normalize("NFC")&&e.split("/").every(qn),Xt=e=>{const t=e.toLowerCase(),r=t.lastIndexOf(".");return r<0?"":t.slice(r+1)},eo=e=>{const t=Xt(e);if(Vn.has(t))return{kind:"markdown"};const r=Bt.get(t);if(r!==void 0)return r.kind==="image"?{kind:"image",imageType:r.imageType}:{kind:"media",mediaType:r.mediaType};const n=Kn.get(t);if(n!==void 0)return{kind:"spreadsheet",format:n};const i=e.toLowerCase();return Qn.has(t)||!i.includes(".")&&Zn.has(i)?{kind:"text"}:{kind:"file"}},Be=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}},Gt=e=>{const t=Be(e);return t===null?e:new be(t)},Jt=e=>{const t=typeof e=="object"&&e!==null?e.code:void 0;return t==="EACCES"||t==="EPERM"||t==="ENOENT"||t==="ENOTDIR"},to=async e=>{try{return Math.trunc((await we.lstat(e)).mtimeMs)}catch(t){if(Jt(t))return;throw t}},xt=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)},ro=(e,t)=>e!==null?{start:e.offset,end:e.offset+e.length-1}:t===0n?{}:{start:0,end:Number(t)-1},no=async(e,t,r,n)=>{let i;try{i=await we.open(e,ue.constants.O_RDONLY|Ft|Ut);const f=await i.stat({bigint:!0});if(!f.isFile()||f.ino!==t.ino||f.dev!==t.dev||f.size!==t.size||f.mtimeNs!==t.mtimeNs)throw new be("not-found")}catch(f){throw await i?.close(),Gt(f)}const o=i.createReadStream(ro(r,t.size)),c=sr.Readable.toWeb(o),l=()=>{o.destroy(n.reason)};return n.aborted?l():n.addEventListener("abort",l,{once:!0}),c},oo=(e,t)=>{const r=J.NAME_COLLATOR.compare(e,t);return r!==0?r:e===t?0:e<t?-1:1},so=e=>{let t=0;const r=[];return async n=>{t<e?t+=1:await new Promise(i=>r.push(i));try{return await n()}finally{const i=r.shift();i===void 0?t-=1:i()}}},io=(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":y.isAcceptableDocumentPath(r)?y.isAcceptableDocumentPath(t)?null:"path-too-long":"control-character-or-backslash"},ao=new Set(["id","label","root","pathPrefix","parse","deny","maxEntries","maxDocumentBytes","textPreviewBytes","legacyTextEncoding","walkConcurrency","cacheScope","reportSkipped"]),Re=(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},co=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] createFileSystemSource needs an options object");for(const T of Object.keys(e))if(!ao.has(T))throw new TypeError(`[markdown-explorer] createFileSystemSource does not know the option ${JSON.stringify(T)}`);const{id:t,label:r,root:n,parse:i}=e;if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] a file-system source needs a non-empty id");if(typeof r!="string"||r.trim()==="")throw new TypeError("[markdown-explorer] a file-system source needs a non-blank label");if(typeof i!="function")throw new TypeError("[markdown-explorer] a file-system source needs a parse function");if(typeof n!="string"||!ie.isAbsolute(n))throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);let o;try{o=ue.statSync(n).isDirectory()}catch(T){throw new RangeError(`[markdown-explorer] root does not exist: ${n}`,{cause:T})}if(!o)throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);const c=ue.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("/")&&kt(l.slice(0,-1))))throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(l)}`);const f=y.resolvePathRules(e.deny),x=Re("maxEntries",e.maxEntries,Oe.maxEntries),w=Re("maxDocumentBytes",e.maxDocumentBytes,Oe.maxDocumentBytes),g=Re("textPreviewBytes",e.textPreviewBytes,Oe.textPreviewBytes),b=e.legacyTextEncoding;if(b!=null&&typeof b!="string")throw new TypeError("[markdown-explorer] legacyTextEncoding must be a string or null");const v=typeof b=="string"?J.legacyTextEncodingOf(b):null,j=Re("walkConcurrency",e.walkConcurrency,Oe.walkConcurrency),O=e.cacheScope===void 0?"principal":e.cacheScope;if(O!=="principal"&&O!=="shared")throw new RangeError(`[markdown-explorer] cacheScope must be "principal" or "shared"; got ${JSON.stringify(O)}`);const R=e.reportSkipped;if(R!==void 0&&typeof R!="function")throw new TypeError("[markdown-explorer] reportSkipped must be a function");const z=R===void 0?T=>{console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(T.sourceId)} does not list ${JSON.stringify(T.path)}: ${T.reason}`)}:R,_=new Set,I=T=>{const N=ie.resolve(c,...T.split("/")),P=ie.relative(c,N);return P===""||P===".."||P.startsWith(`..${ie.sep}`)||ie.isAbsolute(P)?null:N},C=(T,N)=>{const P=`${N}\0${T}`;_.has(P)||_.size>=x||(_.add(P),z({sourceId:t,path:T,reason:N}))},F=async({signal:T})=>{T.throwIfAborted();const N=new AbortController,P=()=>{N.abort(T.reason)};T.addEventListener("abort",P,{once:!0});const D=so(j);let G=0;const W=async(L,K)=>{const Q=await D(async()=>{N.signal.throwIfAborted();try{return await we.readdir(L,{withFileTypes:!0})}catch(H){if(K===""||!Jt(H))throw H;return null}});if(N.signal.throwIfAborted(),Q===null)return C(`${l}${K}`,"unreadable-directory"),null;const Y=[];for(const H of Q){if(f.deniesName(H.name))continue;const re=K===""?H.name:`${K}/${H.name}`,te=`${l}${re}`,ne=io(H,te);if(ne!==null){C(te,ne);continue}Y.push({dirent:H,relativePath:re,path:te})}if(G+=Y.length,G>x)throw new be("too-large");return Y.sort((H,re)=>oo(H.dirent.name,re.dirent.name)),(await Promise.all(Y.map(async({dirent:H,relativePath:re,path:te})=>{const ne=await to(ie.join(L,H.name)),le=ne===void 0?{}:{modifiedAt:ne};if(!H.isDirectory())return{name:H.name,path:te,type:"file",...le};const Te=await W(ie.join(L,H.name),re);return Te===null?null:{name:H.name,path:te,type:"directory",...le,children:Te}}))).filter(H=>H!==null)};try{const L=await W(c,"");if(L===null)throw new Error("[markdown-explorer] the source's root could not be listed");return L}catch(L){throw N.abort(),L}finally{T.removeEventListener("abort",P)}},h=async T=>{if(!T.startsWith(l))return{status:"refused",reason:"not-found"};const N=T.slice(l.length);if(!kt(N))return{status:"refused",reason:"invalid"};if(f.deniesPath(N))return{status:"refused",reason:"forbidden"};const P=I(N);if(P===null)return{status:"refused",reason:"forbidden"};const D=await we.lstat(P,{bigint:!0});if(D.isSymbolicLink())return{status:"refused",reason:"forbidden"};if(!D.isFile())return{status:"refused",reason:"unsupported"};const G=await we.realpath(P);return G!==P||f.deniesPath(ie.relative(c,G).split(ie.sep).join("/"))?{status:"refused",reason:"forbidden"}:{status:"file",target:P,name:N.slice(N.lastIndexOf("/")+1),stats:D}},E=async(T,N,P)=>{let D;try{const G=await h(P);if(G.status==="refused")return y.failureDocument(G.reason);const{target:W,name:L,stats:K}=G,Q=eo(L),Y=Tt(K);if(Q.kind==="image")return{kind:"image",name:L,imageType:Q.imageType,version:Y};if(Q.kind==="media")return{kind:"media",name:L,mediaType:Q.mediaType,version:Y};if(Q.kind==="spreadsheet")return{kind:"spreadsheet",name:L,format:Q.format,firstSheetText:null,edit:null,version:Y};if(Q.kind==="file")return{kind:"file",name:L,version:Y};D=await we.open(W,ue.constants.O_RDONLY|Ft|Ut);const ce=await D.stat({bigint:!0});if(!ce.isFile()||ce.ino!==K.ino||ce.dev!==K.dev)return y.failureDocument("forbidden");if(Q.kind==="markdown"){if(ce.size>BigInt(w))return y.failureDocument("too-large");const ne=await xt(D,w+1);if(ne.length>w)return y.failureDocument("too-large");const le=await i(J.decodeTextLeniently(ne,!0,v),N);return{kind:"markdown",name:L,htmlContent:le.htmlContent,headings:le.headings,edit:null}}const H=await xt(D,g),re=ce.size>BigInt(g),te=J.decodeTextLeniently(H,!re,v);return te.includes("\0")?{kind:"file",name:L,version:Y}:{kind:"text",name:L,text:te,truncated:re,version:Y}}catch(G){const W=Be(G);if(W===null)throw G;return y.failureDocument(W)}finally{await D?.close()}},M=async(T,N,P)=>{let D;try{D=await h(P)}catch(Y){throw Gt(Y)}if(D.status==="refused")throw new be(D.reason);const{target:G,name:W,stats:L}=D,K=Bt.get(Xt(W)),Q=K===void 0?"":K.contentType;return{name:W,contentType:Q,size:Number(L.size),version:Tt(L),open:Y=>no(G,L,Y,T.signal)}},U=async(T,N,P)=>{let D;try{D=await h(P)}catch(L){if(Be(L)!==null)return null;throw L}if(D.status==="refused")return null;const G=P.slice(l.length).split("/");if(G.some(L=>f.deniesName(L)))return null;const W=G.slice(0,-1);return W.map((L,K)=>`${l}${W.slice(0,K+1).join("/")}`)};return Object.freeze({id:t,label:r,cacheScope:O,boundary:Object.freeze({contains:T=>T.startsWith(l)}),tree:F,ancestors:U,document:E,asset:M})};exports.DEFAULT_DENIED_PATH_SEGMENTS=y.DEFAULT_DENIED_PATH_SEGMENTS;exports.MAX_DOCUMENT_PATH_LENGTH=y.MAX_DOCUMENT_PATH_LENGTH;exports.isAcceptableDocumentPath=y.isAcceptableDocumentPath;exports.isDeniedPath=y.isDeniedPath;exports.decodeText=J.decodeText;exports.decodeTextLeniently=J.decodeTextLeniently;exports.legacyTextEncodingOf=J.legacyTextEncodingOf;exports.ExplorerError=be;exports.anonymousAccess=ir;exports.createFileSystemSource=co;exports.createMarkdownExplorer=Wn;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("./dataRoute-DwYtgyt6.cjs"),J=require("./location-hGLhCCg4.cjs"),St=require("node:crypto"),nr=require("@aiquants/markdown/server"),Ae=require("@aiquants/request-isolation"),Pe=require("react-router"),ue=require("node:fs"),ie=require("node:path"),Ie=require("node:url"),or=require("node:worker_threads"),we=require("node:fs/promises"),sr=require("node:stream");var Le=typeof document<"u"?document.currentScript:null;const Ke=Object.freeze({kind:"anonymous"}),ir=Object.freeze({authenticate:async()=>({status:"signed-in",principal:Ke}),principalKey:()=>Ke.kind,signedOutPage:(e,t)=>new Response(null,{status:401,headers:t})}),Ot="application/octet-stream",Rt="application/pdf",ar=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",Rt]),_t="default-src 'none'; media-src 'self'; style-src 'unsafe-inline'",At=`${_t}; sandbox`,cr=`${_t}; sandbox allow-same-origin`,Qe=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,ur=/^[\t\n\r ]+|[\t\n\r ]+$/gu,Ce=/^[\t ]+|[\t ]+$/gu,dr=e=>{const t=[];let r="",n=0;for(;;){for(;n<e.length&&e[n]!=='"'&&e[n]!==",";)r+=e[n],n+=1;if(n<e.length&&e[n]==='"'){const i=n;for(n+=1;n<e.length&&e[n]!=='"';)n+=e[n]==="\\"?2:1;if(n=Math.min(n+1,e.length),r+=e.slice(i,n),n<e.length)continue}if(t.push(r.replace(Ce,"")),r="",n>=e.length)return t;n+=1}},lr=e=>{const t=e.replace(ur,""),r=t.indexOf("/");if(r<0)return null;const n=t.slice(0,r),i=t.indexOf(";",r+1),o=t.slice(r+1,i<0?t.length:i).replace(/[\t\n\r ]+$/u,"");return Qe.test(n)&&Qe.test(o)?`${n}/${o}`.toLowerCase():null},fr=e=>{let t=null;for(const r of dr(e)){const n=lr(r);n!==null&&n!=="*/*"&&(t=n)}return t},mr=/['()*]/gu,vt=e=>encodeURIComponent(e).replace(mr,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Fe=Object.freeze({"Cache-Control":"private, max-age=60, stale-while-revalidate=600, no-transform",Vary:"Cookie"}),Nt=(e,t)=>{const r=fr(e),n=r!==null&&ar.has(r),i=n&&(r.startsWith("audio/")||r.startsWith("video/"));return{contentType:r===null?Ot:r,inline:n,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`${n?"inline":"attachment"}; filename*=UTF-8''${vt(t)}`,...r===Rt?{}:{"Content-Security-Policy":i?cr:At},"Cross-Origin-Resource-Policy":"same-origin"}}},_e=64*1024,ke=e=>`text/plain; charset=${e}`,pr=e=>({"X-Content-Type-Options":"nosniff","Content-Disposition":`inline; filename*=UTF-8''${vt(e)}`,"Content-Security-Policy":At,"Cross-Origin-Resource-Policy":"same-origin"}),hr=(e,t)=>`${t===null?"":t};${e}`,wr=/^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu,xe=Object.freeze({kind:"whole"}),Ze=Object.freeze({kind:"unsatisfiable"}),Pt=(e,t,r)=>{const n=e.get("Range");if(n===null)return xe;const i=e.get("If-Range");if(i!==null&&i!==r)return xe;const o=wr.exec(n);if(o===null)return xe;const[,c,l,f]=o;if(f!==void 0){const g=Number(f);if(g===0)return Ze;const b=Math.max(0,t-g);return{kind:"partial",range:{offset:b,length:t-b}}}const x=Number(c),w=l===""?Number.POSITIVE_INFINITY:Number(l);return w<x?xe:x>=t?Ze:{kind:"partial",range:{offset:x,length:Math.min(w,t-1)-x+1}}},qe="W/",yr=e=>{const t=[];let r=0,n=!1;for(let i=0;i<e.length;i+=1)e[i]==='"'?n=!n:e[i]===","&&!n&&(t.push(e.slice(r,i).replace(Ce,"")),r=i+1);return t.push(e.slice(r).replace(Ce,"")),t},et=e=>e.startsWith(qe)?e.slice(qe.length):e,Ue=(e,t)=>{if(e===null)return!1;const r=yr(e);if(r.length===1&&r[0]==="*")return!0;const n=et(t);return r.some(i=>et(i)===n)},gr=(e,t)=>{let r=t;return e.pipeThrough(new TransformStream({transform:(n,i)=>{const o=n.byteLength>r?n.subarray(0,r):n;r-=o.byteLength,i.enqueue(o),r===0&&i.terminate()},flush:n=>{r>0&&n.error(new RangeError("[markdown-explorer] the asset ended before its declared length"))}}))},pe=async(e,t,r,n,i)=>{if(n!==null&&r.set("Content-Length",String(n)),e.method.toUpperCase()==="HEAD")return new Response(null,{status:t,headers:r});const o=await i();return new Response(n===null?o:gr(o,n),{status:t,headers:r})},It=(e,t)=>{const r=new Headers(e);for(const[n,i]of Object.entries({"Accept-Ranges":"bytes","Content-Range":`bytes */${t}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff"}))r.set(n,i);return new Response(null,{status:416,headers:r})},Er=async(e,t,r)=>{const n=`"${t.version}"`,i=Nt(t.contentType,t.name),o=new Headers(r);for(const[f,x]of Object.entries({...i.headers,...Fe,ETag:n}))o.set(f,x);if(Ue(e.headers.get("If-None-Match"),n))return new Response(null,{status:304,headers:o});if(o.set("Content-Type",i.contentType),t.size===null)return pe(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 c=Pt(e.headers,t.size,n);if(c.kind==="unsatisfiable")return It(r,t.size);if(c.kind==="whole")return pe(e,200,o,t.size,()=>t.open(null));const{range:l}=c;return o.set("Content-Range",`bytes ${l.offset}-${l.offset+l.length-1}/${t.size}`),pe(e,206,o,l.length,()=>t.open(l))},br=(e,t)=>{const r=new Uint8Array(t);let n=0;for(const i of e){if(n===t)break;const o=i.subarray(0,t-n);r.set(o,n),n+=o.byteLength}return r},Tr=(e,t,r)=>new ReadableStream({start:n=>{for(const i of e)n.enqueue(i);t&&n.close()},pull:async n=>{const{done:i,value:o}=await r.read();i?n.close():n.enqueue(o)},cancel:n=>r.cancel(n)},{highWaterMark:0}),Lt=async(e,t,r)=>{const n=e.getReader(),i=t===null?_e:Math.min(t,_e),o=t===null?i+1:i,c=[];let l=0,f=!1;try{for(;l<o;){const{done:g,value:b}=await n.read();if(g){f=!0;break}c.push(b),l+=b.byteLength}if(f&&t!==null&&l<i)throw new RangeError("[markdown-explorer] the asset ended before its declared length");const x=t===null?f:t<=_e;return{encoding:J.textEncodingOf(br(c,Math.min(l,i)),x,r),body:Tr(c,f,n)}}catch(x){throw n.cancel(x).catch(()=>{}),x}},tt=async(e,t)=>{const r=await Lt(await e.open(e.size===null?null:{offset:0,length:Math.min(e.size,_e)}),e.size,t);return r.body.cancel().catch(()=>{}),r.encoding},kr=async(e,t,r,n)=>{const i=`"${hr(t.version,n)}"`,o=new Headers(r);for(const[l,f]of Object.entries({...pr(t.name),...Fe,ETag:i}))o.set(l,f);if(Ue(e.headers.get("If-None-Match"),i))return new Response(null,{status:304,headers:o});if(t.size===0)return o.set("Content-Type",ke(J.textEncodingOf(new Uint8Array(0),!0,n))),o.set("Content-Length","0"),new Response(null,{status:200,headers:o});if(t.size!==null){o.set("Accept-Ranges","bytes");const l=Pt(e.headers,t.size,i);if(l.kind==="unsatisfiable")return It(r,t.size);if(l.kind==="partial"){const{range:f}=l;return o.set("Content-Type",ke(await tt(t,n))),o.set("Content-Range",`bytes ${f.offset}-${f.offset+f.length-1}/${t.size}`),pe(e,206,o,f.length,()=>t.open(f))}}if(e.method.toUpperCase()==="HEAD")return o.set("Content-Type",ke(await tt(t,n))),pe(e,200,o,t.size,()=>t.open(null));const c=await Lt(await t.open(null),t.size,n);return o.set("Content-Type",ke(c.encoding)),pe(e,200,o,t.size,async()=>c.body)},xr=e=>`workbook;${e}`,Sr=async(e,t,r)=>{const n=`"${xr(t.version)}"`,i=Nt(Ot,t.name),o=new Headers(r);for(const[c,l]of Object.entries({...i.headers,...Fe,ETag:n}))o.set(c,l);return Ue(e.headers.get("If-None-Match"),n)?new Response(null,{status:304,headers:o}):(o.set("Content-Type",i.contentType),pe(e,200,o,t.size,()=>t.open(null)))},Or=Object.freeze({"Cache-Control":"private, no-store","Referrer-Policy":"no-referrer"}),Rr=(e,t)=>{const r=new Headers(t);for(const[n,i]of Object.entries(Or))r.set(n,i);return r.set("Location",e),new Response(null,{status:302,headers:r})},Me=(e,t)=>{const r=new AbortController,n=t(AbortSignal.any([e.signal,r.signal]));return new Promise(i=>{let o;const c=setTimeout(()=>{i(e.late),o=setTimeout(()=>r.abort(),e.handOverMs)},e.timeoutMs),l=()=>{clearTimeout(c),clearTimeout(o)};n.then(f=>{l(),i(f)},()=>{l(),i(e.late)})})},_r=Object.freeze({error:(e,t)=>{console.error(e,t)}}),Mt=Symbol.for("@aiquants/markdown-explorer:ExplorerError");class be extends Error{reason;code;constructor(t,r={}){if(!y.isExplorerFailureReason(t))throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${JSON.stringify(t)}`);if(r.code!==void 0&&!y.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,Mt,{value:!0})}}const Ar=e=>e instanceof Error&&Object.hasOwn(e,Mt)&&y.isExplorerFailureReason(e.reason),vr=e=>typeof e=="object"&&e!==null&&e.name==="AbortError",Xe=(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})}},ae=(e,t)=>Xe(e,`[markdown-explorer] ${t.operation} failed`,t),Nr=(e,t)=>Xe(e,`[markdown-explorer] ${t.operation} left out an entry`,t),$e=(e,t)=>Xe(e,`[markdown-explorer] ${t.operation} refused a path the deny rules match`,{...t,error:new RangeError("[markdown-explorer] the path matches a deny rule")}),rt=(e,t)=>{e===null||typeof e!="object"&&typeof e!="function"||Promise.resolve(e).then(void 0,t)},V=(e,t,r,n)=>Ar(e)?y.failureOf(e.reason,e.code):(vr(e)||r.aborted||ae(n,{...t,error:e}),{reason:"failed"}),nt=2*1024*1024,ot=256*1024*1024,Pr=async(e,t)=>{const r=e.getReader(),n=new Uint8Array(t);let i=0;for(;i<t;){const{done:o,value:c}=await r.read();if(o)return n.subarray(0,i);const l=c.subarray(0,t-i);n.set(l,i),i+=l.byteLength}return r.cancel().catch(()=>{}),n},Ir=async(e,t,r)=>{if(e.size===0)return{text:"",truncated:!1};const n=e.size!==null&&e.size>t,i=e.size===null?t+1:Math.min(e.size,t),o=await Pr(await e.open(n?{offset:0,length:t}:null),i);if(e.size!==null&&o.byteLength<i)throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");const c=n||o.byteLength>t,l=c?o.subarray(0,t):o,f=J.decodeTextLeniently(l,!c,r);return f.includes("\0")?null:{text:f,truncated:c}},st=(e,t)=>{if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] a cache ${e} must be a positive integer; got ${String(t)}`)},$t=(e,t)=>{st("capacity",e),t!==void 0&&st("weight budget",t.max);const r=new Map;let n=0;const i=o=>{const c=r.get(o);c!==void 0&&(r.delete(o),n-=c.weight)};return{get:o=>{const c=r.get(o);if(c!==void 0)return r.delete(o),r.set(o,c),c.value},set:(o,c)=>{i(o);const l=t===void 0?0:t.of(o,c);if(!(t!==void 0&&l>t.max)){r.set(o,{value:c,weight:l}),n+=l;for(const f of r.keys()){if(r.size<=e&&(t===void 0||n<=t.max))break;i(f)}}},delete:i,size:()=>r.size,weight:()=>n}},Dt=e=>Math.max(1,e-1),Lr=2147483647,it=Object.freeze({status:"aborted"}),fe=(e,t,r)=>{const n=(e.get(t)??0)+r;n===0?e.delete(t):e.set(t,n)},he=(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)}`)},Mr=e=>e!==null&&typeof e=="object"&&e.ready===!0&&!("id"in e),$r=(e,t)=>e!==null&&typeof e=="object"&&e.id===t&&"output"in e,Dr=({url:e,size:t,deadlineMs:r,jobsPerScope:n,maxQueuedJobs:i,heapLimits:o})=>{he("size",t,Number.MAX_SAFE_INTEGER),he("deadline",r,Lr),he("jobsPerScope",n,Number.MAX_SAFE_INTEGER),he("maxQueuedJobs",i,Number.MAX_SAFE_INTEGER),he("maxOldGenerationSizeMb",o.maxOldGenerationSizeMb,Number.MAX_SAFE_INTEGER),he("maxYoungGenerationSizeMb",o.maxYoungGenerationSizeMb,Number.MAX_SAFE_INTEGER);const c=Object.freeze({maxOldGenerationSizeMb:o.maxOldGenerationSizeMb,maxYoungGenerationSizeMb:o.maxYoungGenerationSizeMb}),l=new Set,f=[],x=new Map,w=new Map,g=Dt(t);let b=0;const v=(h,E)=>{const{job:M}=h;h.timer!==null&&clearTimeout(h.timer),h.timer=null,h.job=null,h.sent=!1,M!==null&&(fe(x,M.scope,-1),fe(w,M.scope,-1),M.settle(E))},j=h=>{const[E]=f.splice(h,1);E?.detach()},O=()=>{let h=-1,E=g,M=Number.POSITIVE_INFINITY;for(const[U,T]of f.entries()){const N=x.get(T.scope)??0,P=w.get(T.scope)??0;(N<E||N===E&&h>=0&&P<M)&&(h=U,E=N,M=P)}return h},R=(h,E)=>{l.has(h)&&(l.delete(h),v(h,E),h.worker.terminate().catch(()=>{}),F())},z=h=>{h.timer=setTimeout(()=>{R(h,{status:"timeout"})},r)},_=(h,E)=>h.sent?{status:"crashed",error:E}:{status:"unavailable",error:E},I=(h,E)=>{h.sent=!0,z(h);try{h.worker.postMessage({id:E.id,input:E.input})}catch(M){v(h,{status:"crashed",error:M}),h.worker.unref()}},C=()=>{const h={worker:new or.Worker(e,{resourceLimits:c}),job:null,sent:!1,timer:null,ready:!1};return h.worker.unref(),h.timer=setTimeout(()=>{R(h,{status:"unavailable",error:new Error(`[markdown-explorer] a worker did not start within ${String(r)} ms`)})},r),h.worker.on("message",E=>{if(!h.ready&&Mr(E)){h.ready=!0,h.timer!==null&&clearTimeout(h.timer),h.timer=null,h.job===null?h.worker.unref():I(h,h.job),h.job===null&&F();return}const{job:M}=h;if(M===null||!$r(E,M.id)){R(h,_(h,new Error("[markdown-explorer] a worker sent a message that answers no job")));return}v(h,{status:"done",output:E.output}),h.worker.unref(),F()}),h.worker.on("error",E=>{R(h,_(h,E))}),h.worker.on("messageerror",E=>{R(h,_(h,E))}),h.worker.on("exit",E=>{R(h,_(h,new Error(`[markdown-explorer] a worker exited with code ${String(E)}`)))}),l.add(h),h},F=()=>{for(;;){const h=O(),E=f[h];if(E===void 0)return;let M;for(const T of l)if(T.job===null){M=T;break}if(M===void 0&&l.size<t)try{M=C()}catch(T){j(h),fe(w,E.scope,-1),E.settle({status:"unavailable",error:T});continue}if(M===void 0)return;j(h),fe(x,E.scope,1);const U=M;U.job=E,U.worker.ref(),U.ready&&I(U,E)}};return{run:(h,{scope:E,signal:M})=>new Promise(U=>{if(M.aborted){U(it);return}if((w.get(E)??0)>=n){U({status:"refused",limit:"scope"});return}b+=1;const T={id:b,input:h,scope:E,settle:U,detach:()=>{}};f.push(T),fe(w,E,1),F();const N=f.indexOf(T);if(N<0)return;if(f.length>i){j(N),fe(w,E,-1),U({status:"refused",limit:"queue"});return}const P=()=>{const D=f.indexOf(T);D<0||(j(D),fe(w,E,-1),U(it))};M.addEventListener("abort",P,{once:!0}),T.detach=()=>{M.removeEventListener("abort",P)}}),workers:()=>l.size}},Ge=1024*1024,jr=3e4,zr=4*Ge,Cr=64*Ge,Hr=3,Br=2,Fr=(e,t)=>e+Dt(t)+Hr,Ur=4,Xr=32,Gr=512,Jr=64,Yr=4096,Wr=32,at=4096,Vr=4,jt=({workerHeapMb:e,maxHtmlBytes:t})=>Math.floor(((e-Jr)*Ge-t*Wr)/Yr),Kr=({maxHtmlBytes:e})=>e,Qr=({maxHtmlBytes:e})=>Vr*e,Zr=1024,qr=2147483647,en=64,tn=2**29,rn=1024*1024,nn=64,ct=Object.freeze({status:"rejected",reason:"too-large",cause:null}),De=Object.freeze({status:"rejected",reason:"failed",cause:null}),me=(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},on=(e,t)=>{if(e!==void 0&&(e===null||typeof e!="object"))throw new TypeError("[markdown-explorer] sanitizer must be an object of { workers, deadlineMs, maxHtmlBytes, cacheBytes, workerHeapMb, jobsPerScope, maxQueuedJobs }");const{workers:r,deadlineMs:n,maxHtmlBytes:i,cacheBytes:o,workerHeapMb:c,jobsPerScope:l,maxQueuedJobs:f}=e??{},x=me("workers",r,Br,en),w=me("jobsPerScope",l,Fr(t,x),Number.MAX_SAFE_INTEGER),g=Object.freeze({workers:x,deadlineMs:me("deadlineMs",n,jr,qr),maxHtmlBytes:me("maxHtmlBytes",i,zr,tn),cacheBytes:me("cacheBytes",o,Cr,Number.MAX_SAFE_INTEGER),workerHeapMb:me("workerHeapMb",c,Gr,rn),jobsPerScope:w,maxQueuedJobs:me("maxQueuedJobs",f,Ur*w,Number.MAX_SAFE_INTEGER)});if(g.jobsPerScope<t)throw new RangeError(`[markdown-explorer] sanitizer.jobsPerScope must be at least multiView.maxPanels (${String(t)}), because a page sends the document of every panel to the sanitizer at once for one reader; got ${String(g.jobsPerScope)}`);if(g.maxQueuedJobs<t)throw new RangeError(`[markdown-explorer] sanitizer.maxQueuedJobs must be at least multiView.maxPanels (${String(t)}), because a reader whose page finds every worker busy waits with the document of every panel; got ${String(g.maxQueuedJobs)}`);if(jt(g)<at)throw new RangeError(`[markdown-explorer] sanitizer.workerHeapMb (${String(g.workerHeapMb)} MiB) must leave room for ${String(at)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(g.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`);return g},sn=()=>{const e=typeof document>"u"?require("url").pathToFileURL(__filename).href:Le&&Le.tagName.toUpperCase()==="SCRIPT"&&Le.src||new URL("server.cjs",document.baseURI).href,t=new URL(`./sanitizeWorker${ie.extname(Ie.fileURLToPath(e))}`,e);if(!ue.existsSync(Ie.fileURLToPath(t)))throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${Ie.fileURLToPath(t)}`);return t},ut=new Map,an=(e,t)=>{const r=[e.href,t.workers,t.deadlineMs,t.workerHeapMb,t.jobsPerScope,t.maxQueuedJobs].map(String).join("\0");let n=ut.get(r);return n===void 0&&(n=Dr({url:e,size:t.workers,deadlineMs:t.deadlineMs,jobsPerScope:t.jobsPerScope,maxQueuedJobs:t.maxQueuedJobs,heapLimits:{maxOldGenerationSizeMb:t.workerHeapMb,maxYoungGenerationSizeMb:Xr}}),ut.set(r,n)),n},cn=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"},un=e=>e instanceof Error&&e.code==="ERR_WORKER_OUT_OF_MEMORY",dn=({iframeHosts:e,dataPath:t,options:r,pool:n})=>{const i=Object.freeze([...e]),o=jt(r),c=Kr(r),l=Qr(r),f=$t(Zr,{max:r.cacheBytes,of:(O,R)=>2*O.length+(R.status==="sanitized"?2*R.html.length:nn)}),x=new Map,w=new Map,g=O=>{x.get(O.key)===O&&x.delete(O.key);const R=w.get(O.hash);R?.delete(O),R?.size===0&&w.delete(O.hash)},b=async(O,R,z)=>{const _=await n.run({html:O,iframeHosts:i,dataPath:t,maxNodes:o,maxAttributeChars:c,maxSanitizedChars:l},{scope:R,signal:z});if(_.status==="refused"){const C=_.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(_.status==="aborted")return{outcome:De,lasting:!1};if(_.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(_.status==="unavailable")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker could not start",{cause:_.error})},lasting:!1};if(_.status==="crashed"&&un(_.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:_.error})},lasting:!0};if(_.status==="crashed")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker failed",{cause:_.error})},lasting:!0};const{output:I}=_;return cn(I)?I.status==="too-large"?{outcome:ct,lasting:!0}:I.status==="error"?{outcome:{status:"rejected",reason:"failed",cause:new Error(`[markdown-explorer] the HTML sanitizer failed: ${I.message}`)},lasting:!0}:I.html.length>l?{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer's output of ${String(I.html.length)} characters exceeds its limit of ${String(l)}`)},lasting:!0}:{outcome:{status:"sanitized",html:I.html},lasting:!0}:{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker answered something that is not an outcome")},lasting:!0}},v=(O,R,z,_)=>{let I=()=>{};const C=new Promise(E=>{I=E}),F={hash:R,key:z,outcome:C,answer:I,controller:new AbortController,waiters:0};x.set(z,F);const h=w.get(R);return h===void 0?w.set(R,new Set([F])):h.add(F),b(O,_,F.controller.signal).catch(E=>({outcome:{status:"rejected",reason:"failed",cause:E instanceof Error?E:new Error(String(E))},lasting:!0})).then(({outcome:E,lasting:M})=>{if(g(F),F.answer(E),!M)return;const U=f.get(R),T=U??(E.status==="rejected"?{...E,cause:null}:E);U===void 0&&f.set(R,T);for(const N of w.get(R)??[])g(N),N.answer(T),N.controller.abort()}),F},j=(O,R)=>new Promise(z=>{O.waiters+=1;const _=()=>{O.waiters-=1,z(De),!(O.waiters>0)&&(g(O),O.controller.abort())};R.addEventListener("abort",_,{once:!0}),O.outcome.then(I=>{R.removeEventListener("abort",_),z(I)})});return(O,{scope:R,signal:z})=>{if(O.length>r.maxHtmlBytes||Buffer.byteLength(O,"utf8")>r.maxHtmlBytes)return Promise.resolve(ct);const _=St.createHash("sha256").update(O,"utf8").digest("base64"),I=f.get(_);if(I!==void 0)return Promise.resolve(I);if(z.aborted)return Promise.resolve(De);const C=`${_}\0${R}`,F=x.get(C);return j(F===void 0?v(O,_,C,R):F,z)}},ve=e=>({result:e,json:JSON.stringify(e)}),je=Object.freeze(ve(Object.freeze({status:"error",failure:Object.freeze({reason:"failed"})}))),ln=e=>e.status==="ok"&&e.entries.length>0,fn=({ttlMs:e,maxEntries:t,maxBytes:r,now:n})=>{const i=$t(t,{max:r,of:(w,g)=>2*g.tree.json.length}),o=new Map,c=new Map,l=(w,g)=>{const b=new AbortController,v={waiters:0,superseded:!1,started:!1,loadTree:g},j=c.get(w),O=(C,F)=>{const h=ve(C);return!(v.superseded||b.signal.aborted)&&ln(C)&&i.set(w,{tree:h,loadedAt:F}),h},z=(async()=>{if(j!==void 0&&await j,b.signal.aborted)return je;const C=n();return v.started=!0,O(await v.loadTree(b.signal,C),C)})().finally(()=>{o.get(w)===_&&o.delete(w)}),_={promise:z,controller:b,state:v};o.set(w,_);const I=z.then(()=>{},()=>{});return c.set(w,I),I.then(()=>{c.get(w)===I&&c.delete(w)}),_},f=(w,g,b)=>{g.state.waiters+=1;const v=()=>{g.state.waiters-=1,!(g.state.waiters>0)&&(o.get(w)===g&&o.delete(w),g.controller.abort())};return b.addEventListener("abort",v,{once:!0}),g.promise.finally(()=>{b.removeEventListener("abort",v)})},x=w=>{i.delete(w);const g=o.get(w);g?.state.started&&(g.state.superseded=!0,o.delete(w))};return{load:(w,g,b)=>{if(g.aborted)return Promise.resolve(je);const v=i.get(w);if(v!==void 0){if(n()-v.loadedAt<e)return Promise.resolve(v.tree);i.delete(w)}const j=o.get(w);return f(w,j===void 0?l(w,b):j,g)},refresh:(w,g,b)=>{if(g.aborted)return Promise.resolve(je);x(w);const v=o.get(w);return v===void 0?f(w,l(w,b),g):(v.state.loadTree=b,f(w,v,g))},forget:x}},mn=e=>({load:(t,r,n)=>n(r,e()).then(ve),refresh:(t,r,n)=>n(r,e()).then(ve),forget:()=>{}}),S=e=>{throw new TypeError(`[markdown-explorer] ${e}`)},pn=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"}:y.isAcceptableDocumentPath(r)?null:{path:r,reason:"a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)"}},hn=(e,t,r,n)=>{if(e===null)return null;if(!Array.isArray(e))throw new TypeError(`[markdown-explorer] a source's ancestors must be null or an array of folder paths; got ${typeof e}`);const i=new Set;for(const o of e){if(typeof o!="string"||!y.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(i.has(o))throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");i.add(o)}return Object.freeze([...i])},wn=(e,t,r,n,i)=>{const o=new Set,c=f=>{if(!Array.isArray(f))return S("a source returned entries that are not an array");const x=[];for(const w of f){const g=l(w);g!==null&&x.push(g)}return x},l=f=>{const x=pn(f);if(x!==null)return n(x),null;const w=y.entryViolation(f);if(w!==null)return S(w);const g=f;if(o.has(g))return S("a source returned entries that contain themselves");const{name:b,path:v,type:j,mimeType:O,modifiedAt:R,children:z,lazy:_}=g;if(t.deniesName(b)||t.deniesPath(v))return null;if(!i(v))return n({path:v,reason:"a path outside the source's boundary"}),null;const I={name:b,path:v,...O===void 0?{}:{mimeType:O},...R===void 0?{}:{modifiedAt:R}};if(j==="file")return{...I,type:j};if(_===!0)return r?{...I,type:j,lazy:!0,children:[]}:S("a lazy directory came from a source without a children function");if(z===void 0)return{...I,type:j};o.add(g);const C=c(z);return o.delete(g),{...I,type:j,children:C}};return c(e)},yn=/^[\x21\x23-\x7E]{1,256}$/u,zt=e=>typeof e=="string"&&yn.test(e),gn=new Set(["text","image","media","spreadsheet","file"]),En=e=>typeof e=="string"&&gn.has(e),bn=(e,t,r)=>{if(e!==null&&typeof e=="object"){const o=e,{kind:c}=o;if(En(c)){if(Object.hasOwn(o,"url"))return S(`a ${c} document carries its version, not a url`);if(typeof o.name!="string")return S("a document needs a name string");if(!zt(o.version))return S(`a ${c} document needs a version of 1 to 256 visible ASCII characters other than '"'`);const l=t(o.version);switch(c){case"image":{const{imageType:f}=o;return y.isExplorerImageType(f)?{kind:c,name:o.name,url:l,imageType:f}:S(`unknown image type ${typeof f=="string"?JSON.stringify(f.slice(0,64)):typeof f}`)}case"file":return{kind:c,name:o.name,url:l};case"media":{const{mediaType:f}=o;return y.isExplorerMediaType(f)?{kind:c,name:o.name,url:l,mediaType:f}:S(`unknown media type ${typeof f=="string"?JSON.stringify(f.slice(0,64)):typeof f}`)}case"text":return typeof o.text!="string"||typeof o.truncated!="boolean"?S("a text document needs text and truncated"):{kind:c,name:o.name,text:o.text,truncated:o.truncated,url:l};case"spreadsheet":{const f=y.spreadsheetFieldsViolation(o);if(f!==null)return S(f);const{format:x,firstSheetText:w,edit:g}=o;return{kind:c,name:o.name,url:l,format:x,firstSheetText:w,edit:kn(g)}}}}}const n=y.documentViolation(e);if(n!==null)return S(n);const i=e;switch(i.kind){case"failure":{const{reason:o,code:c}=i.failure;return{kind:"failure",failure:y.failureOf(o,c)}}case"markdown":return i.headings.length>y.EXPLORER_MAX_HEADINGS?{kind:"failure",failure:y.failureOf("too-large")}:(i.edit?.kind==="inline"||i.edit?.kind==="draft")&&!r?S(`a markdown document offers ${i.edit.kind} editing, but the server has no edit ports`):{kind:"unsanitized-markdown",name:i.name,html:i.htmlContent,headings:i.headings.map(({text:o,depth:c,id:l})=>({text:o,depth:c,id:l})),edit:Tn(i.edit)}}},Tn=e=>{if(e===null)return null;switch(e.kind){case"inline":return{kind:"inline"};case"draft":return{kind:"draft"};case"external":return{kind:"external",href:e.href}}},kn=e=>e===null?null:{kind:"external",href:e.href},Ne=(e,t,r)=>typeof e!="string"?S(`${r} needs a text string`):e.includes("\0")?S(`${r} holds NUL, which no text editor can keep`):new TextEncoder().encode(e).byteLength>t?S(`${r} is over editMaxBytes (${t} bytes); refuse a longer source with ExplorerError "too-large"`):e,Ct=e=>y.isRootRelativeUrl(e.href)?{kind:"grant",href:e.href}:S("a grant needs a root-relative href"),xn=(e,t)=>{if(e===null||typeof e!="object")return S("an edit source must be an object");const r=e;return r.kind==="grant"?Ct(r):r.kind==="draft"?{kind:"draft",text:Ne(r.text,t,"a draft source")}:r.kind!=="edit"?S(`an edit source's kind must be "edit", "draft" or "grant"`):y.isExplorerEditToken(r.version)?typeof r.history!="boolean"?S("an edit source needs history"):{kind:"edit",text:Ne(r.text,t,"an edit source"),version:r.version,history:r.history}:S("an edit source needs a version of 1 to 1024 characters")},Sn=(e,t)=>{if(e===null||typeof e!="object")return S("a save result must be an object");const r=e;switch(r.kind){case"grant":return Ct(r);case"saved":return y.isExplorerEditToken(r.version)?{kind:"saved",version:r.version}:S("a saved result needs a version of 1 to 1024 characters");case"conflict":return y.isExplorerEditToken(r.version)?{kind:"conflict",version:r.version,text:Ne(r.text,t,"a conflict's current text")}:S("a conflict needs the current version of 1 to 1024 characters");default:return S(`a save result's kind must be "saved", "conflict" or "grant"`)}},On=e=>{if(e===null||typeof e!="object")return S("a preview must be an object");const{htmlContent:t,headings:r}=e;if(typeof t!="string"||!Array.isArray(r))return S("a preview needs htmlContent and headings");if(r.length>y.EXPLORER_MAX_HEADINGS)return{kind:"failure",failure:y.failureOf("too-large")};for(const n of r){const i=y.headingViolation(n);if(i!==null)return S(i)}return{html:t,headings:r.map(({text:n,depth:i,id:o})=>({text:n,depth:i,id:o}))}},Rn=e=>{if(!Array.isArray(e))return S("revisions must be an array");const t=new Set;return e.map(r=>{const n=y.revisionViolation(r);if(n!==null)return S(n);const{id:i,modifiedAt:o,size:c,author:l,kept:f,current:x}=r;return t.has(i)?S(`two revisions share the id ${JSON.stringify(i.slice(0,64))}`):(t.add(i),{id:i,modifiedAt:o,size:c,author:l,kept:f,current:x})})},_n=(e,t)=>Ne(e,t,"a revision"),He=e=>{if(e===null||typeof e!="object")return S("an asset file must be an object");const{name:t,contentType:r,size:n,version:i,open:o,kind:c}=e;return c!==void 0?S(c==="redirect"?"an asset redirect answers only a request for the stored file (options.delivery file), never one that reads the bytes":'an asset file has no kind (the only kind is "redirect")'):typeof t!="string"||t===""?S("an asset file needs a non-empty name"):typeof r!="string"?S("an asset file needs a contentType string ('' when unknown)"):n!==null&&!(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)?S("an asset file's size must be null or a non-negative safe integer"):zt(i)?typeof o!="function"?S("an asset file needs an open function"):Object.freeze({name:t,contentType:r,size:n,version:i,open:o}):S(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`)},An=e=>{if(e===null||typeof e!="object"||e.kind!=="redirect")return He(e);const{url:t}=e;if(typeof t!="string"||!URL.canParse(t))return S("an asset redirect needs an absolute https URL");const r=new URL(t);return r.protocol!=="https:"||r.username!==""||r.password!==""?S("an asset redirect's URL must be https and carry no credentials"):Object.freeze({kind:"redirect",url:r.href})},vn=e=>Array.isArray(e)?e.map(t=>{if(t===null||typeof t!="object")return S("a notice must be an object");const{id:r,tone:n,title:i,body:o,action:c}=t;if(typeof r!="string"||r===""||typeof i!="string")return S("a notice needs an id and a title");if(!y.isExplorerNoticeTone(n))return S(`unknown notice tone ${typeof n=="string"?JSON.stringify(n.slice(0,64)):typeof n}`);if(o!==void 0&&typeof o!="string")return S("a notice body must be a string");const f={id:r,tone:n,title:i,...o===void 0?{}:{body:o}};if(c===void 0)return f;if(c===null||typeof c!="object")return S("a notice action must be an object");const{label:x,href:w}=c;return typeof x!="string"||!y.isAcceptableUrl(w,y.EXPLORER_LINK_PROTOCOLS)?S("a notice action needs a label and an http(s), mailto or relative href"):{...f,action:{label:x,href:w}}}):S("notices must be an array"),Nn=4e3,Se=Object.freeze({ttlMs:3e5,maxEntries:64,maxBytes:64*1024*1024}),dt=32,Ht="private, no-store",Pn=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"}),In=22,Ln=2147483647,ze=Object.freeze([]),Mn=Object.freeze({status:"ok",source:null,ancestors:null}),lt=Object.freeze(["contains","confirm"]),ft=Object.freeze({readOnly:!1}),$n=Object.freeze({readOnly:!0}),ee=(e,t,r)=>{if(!(r&&t===void 0)&&typeof t!="function")throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${typeof t}`)},ye=(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},Dn=e=>{if(e===null||typeof e!="object"||!Object.isFrozen(e))throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");return J.revalidateExplorerConfig(e)},mt=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)")}},pt=e=>e instanceof Response?new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`):e,jn=e=>{if(typeof e!="string")throw new TypeError(`[markdown-explorer] scopeSecret must be a string; got ${typeof e}`);if(e.length<dt)throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(dt)} characters; got ${String(e.length)}`);return e},zn=(e,t)=>{if(!J.isPlainObject(t))throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);for(const r of Object.keys(t))if(!lt.includes(r))throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${lt.join(", ")}`);ee(`${e}.boundary.contains`,t.contains,!1),ee(`${e}.boundary.confirm`,t.confirm,!0)},Cn=e=>{if(!Array.isArray(e))throw new TypeError("[markdown-explorer] sources must be an array");const t=e;if(t.length===0)throw new RangeError("[markdown-explorer] sources must hold at least one source");const r=new Set;for(const[n,i]of t.entries()){if(i===null||typeof i!="object")throw new TypeError(`[markdown-explorer] sources[${String(n)}] must be an object`);const{id:o,label:c,boundary:l,tree:f,children:x,ancestors:w,cacheScope:g}=i;if(!J.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 b=`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 c!="string"&&typeof c!="function")throw new TypeError(`[markdown-explorer] ${b}.label must be a string or a function`);if(typeof c=="string"&&c.trim()==="")throw new RangeError(`[markdown-explorer] ${b}.label must not be blank`);if(zn(b,l),ee(`${b}.tree`,f,!1),ee(`${b}.children`,x,!0),ee(`${b}.ancestors`,w,!0),g!==void 0&&g!=="principal"&&g!=="shared")throw new RangeError(`[markdown-explorer] ${b}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(g)}`)}return t},Hn=e=>{if(e===!1)return!1;if(e===void 0)return Se;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?Se.ttlMs:ye("treeCache.ttlMs",t,Number.MAX_SAFE_INTEGER),maxEntries:r===void 0?Se.maxEntries:ye("treeCache.maxEntries",r,Number.MAX_SAFE_INTEGER),maxBytes:n===void 0?Se.maxBytes:ye("treeCache.maxBytes",n,Number.MAX_SAFE_INTEGER)}},ht=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},wt=(e,t)=>{if(!(t instanceof Response))throw new TypeError(`[markdown-explorer] ${e} must return a Response`);return t},yt=(e,t)=>{if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");return St.createHmac("sha256",e).update(t,"utf8").digest("base64url").slice(0,In)},Bn=e=>e.view==="multi"?e.docs:e.doc===null?[]:[e.doc],de=(e,t)=>{const r=e.getAll(t),[n]=r;return r.length===1&&n!==void 0&&n!==""?n:null},q=(e,t,r,n={})=>{const i=new Headers(r);for(const[o,c]of Object.entries({...Pn,...n}))i.set(o,c);return new Response(t,{status:e,headers:i})},$=(e,t,r)=>q(y.EXPLORER_FAILURE_STATUS[e.reason],JSON.stringify({failure:e}),t,r),Fn=new Set(["refresh","save","preview"]),Un=new Set(["edit","save","preview","revisions","revision"]),gt=(e,t)=>{const r=Fn.has(t)?["POST"]:["GET","HEAD"];return r.includes(e.method.toUpperCase())?null:q(405,JSON.stringify({failure:{reason:"invalid"}}),void 0,{Allow:r.join(", ")})},Et=e=>e.headers.get(y.EXPLORER_PROOF_HEADER)===y.EXPLORER_REFRESH_PROOF&&Ae.crossOriginRefusal(e,Ae.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Xn=e=>e.headers.get(y.EXPLORER_PROOF_HEADER)===y.EXPLORER_EDIT_PROOF&&Ae.crossOriginRefusal(e,Ae.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Gn=async(e,t)=>{const[r,...n]=(e.headers.get("Content-Type")??"").split(";").map(b=>b.trim().toLowerCase()),i=n.find(b=>b.startsWith("charset="));if(r!==y.EXPLORER_DRAFT_MEDIA_TYPE||i!==void 0&&i!=="charset=utf-8")return{status:"error",failure:{reason:"invalid"}};const o=Number(e.headers.get("Content-Length")??"0");if(Number.isFinite(o)&&o>t)return{status:"error",failure:{reason:"too-large"}};if(e.body===null)return{status:"ok",text:""};const c=e.body.getReader(),l=[];let f=0;for(;;){const{done:b,value:v}=await c.read();if(b)break;if(f+=v.byteLength,f>t)return await c.cancel(),{status:"error",failure:{reason:"too-large"}};l.push(v)}const x=new Uint8Array(f);let w=0;for(const b of l)x.set(b,w),w+=b.byteLength;let g;try{g=new TextDecoder("utf-8",{fatal:!0}).decode(x)}catch{return{status:"error",failure:{reason:"invalid"}}}return g.includes("\0")?{status:"error",failure:{reason:"invalid"}}:{status:"ok",text:g}},Jn=e=>{if(e===void 0)return;if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] edit must be an object of the editor's ports");const t=e;for(const r of["source","save","preview","revisions","revision"])ee(`edit.${r}`,t[r],!1);return e},Yn=({parentHeaders:e,loaderHeaders:t,errorHeaders:r})=>{const n=new Headers,i=r===void 0?[e,t]:[e,t,r];for(const o of i)for(const[c,l]of o)c!=="set-cookie"&&n.set(c,l);return n},Wn=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the server configuration must be an object");const t=Dn(e.config),r=jn(e.scopeSecret);ee("authenticate",e.authenticate,!1),ee("principalKey",e.principalKey,!1),ee("document",e.document,!1),ee("asset",e.asset,!1),ee("signedOutPage",e.signedOutPage,!1),ee("forbiddenPage",e.forbiddenPage,!0),ee("notices",e.notices,!0),ee("onTreeRefreshed",e.onTreeRefreshed,!0);const n=Cn(e.sources),i=J.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 c=e.logger===void 0?_r:e.logger,l=y.resolvePathRules(e.deny),f=e.deferredTimeoutMs===void 0?Nn:ye("deferredTimeoutMs",e.deferredTimeoutMs,Ln),x=e.textMaxBytes===void 0?nt:ye("textMaxBytes",e.textMaxBytes,ot),w=Jn(e.edit);if(w===void 0&&e.editMaxBytes!==void 0)throw new TypeError("[markdown-explorer] editMaxBytes needs the edit ports");const g=e.editMaxBytes===void 0?nt:ye("editMaxBytes",e.editMaxBytes,ot),b=Hn(e.treeCache),v=()=>Date.now(),j=b===!1?mn(v):fn({...b,now:v}),O=on(e.sanitizer,t.multiView.maxPanels),R=dn({iframeHosts:t.iframeHosts,dataPath:t.dataPath,options:O,pool:an(sn(),O)}),z=new Map(n.map(s=>[s.id,s])),_=J.documentStyleNames(t),{authenticate:I,principalKey:C,signedOutPage:F,forbiddenPage:h,onTreeRefreshed:E}=e,M=(s,u)=>{if(typeof s.label=="string")return s.label;const a=s.label(u);if(typeof a!="string"||a.trim()==="")throw new TypeError(`[markdown-explorer] the label of source ${JSON.stringify(s.id)} must be a non-blank string`);return a},U=(s,u)=>s.cacheScope==="shared"?s.id:`${s.id}\0${u}`,T=(s,u)=>{const a=m=>ae(c,{operation:"boundary",sourceId:s.id,path:u,error:m});let d;try{d=s.boundary.contains(u)}catch(m){return a(m),!1}return typeof d=="boolean"?d:(rt(d,a),a(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(s.id)} must return a boolean; got ${typeof d}`)),!1)},N=async(s,u,a)=>{const{confirm:d}=s.boundary;if(d===void 0)return{status:"inside",readPath:a};let m;try{m=await d(u,a)}catch(X){return{status:"error",failure:V(X,{operation:"boundary",sourceId:s.id,path:a},u.signal,c)}}const p=X=>(ae(c,{operation:"boundary",sourceId:s.id,path:a,error:new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(s.id)} ${X}`)}),{status:"outside"});if(m===null||typeof m!="object")return p(`must resolve to { inside, readPath? }; got ${m===null?"null":typeof m}`);const{inside:k,readPath:A}=m;return k===!1?{status:"outside"}:k!==!0||typeof A!="string"?p("must resolve to { inside: false } or { inside: true, readPath: string }"):!y.isAcceptableDocumentPath(A)||l.deniesPath(A)?(ae(c,{operation:"boundary",sourceId:s.id,path:a,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:A}},P=async(s,u)=>{const a=n.filter(m=>T(m,u));if(a.length===0)return{status:"error",failure:{reason:"forbidden"}};if(a.some(m=>m.boundary.confirm===void 0))return{status:"inside",readPath:u};let d=null;for(const m of a){const p=await N(m,s,u);if(p.status==="inside")return p;p.status==="error"&&d===null&&(d=p.failure)}return{status:"error",failure:d===null?{reason:"forbidden"}:d}},D=(s,u,a)=>{const d=({path:m,reason:p})=>Nr(c,{operation:a.operation,sourceId:a.sourceId,path:m,error:new TypeError(`[markdown-explorer] an entry with ${p} was left out`)});try{return{status:"ok",entries:wn(s,l,u.children!==void 0,d,m=>T(u,m))}}catch(m){return ae(c,{...a,error:m}),{status:"error",failure:{reason:"failed"}}}},G=async(s,u,a)=>{let d;try{d=await s.tree(u)}catch(p){return{status:"error",failure:V(p,{operation:"tree",sourceId:s.id},u.signal,c)}}const m=D(d,s,{operation:"tree",sourceId:s.id});return m.status==="ok"?{status:"ok",entries:m.entries,loadedAt:a}:m},W=(s,u,a,d)=>(m,p)=>G(s,{principal:u,request:a,signal:m,refresh:d},p),L=(s,u,a,d,m)=>j.load(U(s,a),m,W(s,u,d,!1)),K=(s,u,a,d)=>j.refresh(U(s,a),d.signal,W(s,u,d,!0)),Q=(s,u)=>{if(E===void 0)return;const a=d=>ae(c,{operation:"refresh",sourceId:s.id,error:d});try{rt(E(u),a)}catch(d){a(d)}},Y=async(s,u,a,d)=>{if(l.deniesPath(d)||!T(s,d))return{status:"error",failure:{reason:"forbidden"}};const m=await N(s,a,d);if(m.status==="outside")return{status:"error",failure:{reason:"forbidden"}};if(m.status==="error")return{status:"error",failure:m.failure};let p;try{p=await u(a,d,m.readPath)}catch(k){return{status:"error",failure:V(k,{operation:"children",sourceId:s.id,path:d},a.signal,c)}}return D(p,s,{operation:"children",sourceId:s.id,path:d})},ce=async(s,u,a,d)=>{const m=await N(s,a,d);if(m.status==="outside")return{status:"ok",ancestors:null};if(m.status==="error")return{status:"error",failure:m.failure};let p;try{p=await u(a,d,m.readPath,{maxDepth:t.revealDocument.maxDepth})}catch(k){return{status:"error",failure:V(k,{operation:"ancestors",sourceId:s.id,path:d},a.signal,c)}}if(Array.isArray(p)&&p.length>t.revealDocument.maxDepth)return{status:"ok",ancestors:null};try{return{status:"ok",ancestors:hn(p,d,l,k=>T(s,k))}}catch(k){return ae(c,{operation:"ancestors",sourceId:s.id,path:d,error:k}),{status:"error",failure:{reason:"failed"}}}},H=async(s,u,a,d)=>l.deniesPath(d)?{status:"error",failure:{reason:"forbidden"}}:T(s,d)?ce(s,u,a,d):{status:"ok",ancestors:null},re=async(s,u,a)=>{if(l.deniesPath(a))return{status:"error",failure:{reason:"forbidden"}};for(const d of[s,...n.filter(m=>m!==s)]){if(u.signal.aborted)break;const m=d.ancestors;if(m===void 0||!T(d,a))continue;const p=await ce(d,m,u,a);if(p.status==="ok"&&p.ancestors!==null)return{status:"ok",source:d.id,ancestors:p.ancestors}}return Mn},te=async(s,u,a)=>{if(l.deniesPath(a))return y.failureDocument("forbidden");const d=await P(s,a);if(d.status==="error")return{kind:"failure",failure:d.failure};let m;try{m=await e.document(s,a,d.readPath)}catch(A){return{kind:"failure",failure:V(A,{operation:"document",path:a},s.signal,c)}}let p;try{p=bn(m,A=>y.explorerAssetHref(t.dataPath,a,A),w!==void 0)}catch(A){return ae(c,{operation:"document",path:a,error:A}),y.failureDocument("failed")}if(p.kind!=="unsanitized-markdown")return p;const k=await R(p.html,{scope:u,signal:s.signal});return k.status==="sanitized"?{kind:"markdown",name:p.name,htmlContent:k.html,headings:p.headings,edit:p.edit}:(k.cause!==null&&ae(c,{operation:"document",path:a,error:k.cause}),y.failureDocument(k.reason))},ne=async s=>{if(e.notices===void 0)return ze;try{return vn(await e.notices(s))}catch(u){return V(u,{operation:"notices"},s.signal,c),ze}},le=async(s,u,a)=>{const d=de(u,y.EXPLORER_DATA_QUERY.path);if(d===null||!y.isAcceptableDocumentPath(d))return $({reason:"invalid"},a);const m=y.readExplorerAssetDisplay(u);if(m===null)return $({reason:"invalid"},a);if(l.deniesPath(d))return $e(c,{operation:"asset",path:d}),$({reason:"forbidden"},a);const p=await P(s,d);if(p.status==="error")return $(p.failure,a);try{const k=await e.asset(s,d,p.readPath,{delivery:m}),A=m==="file"?An(k):He(k);return"kind"in A?Rr(A.url,a):m==="text"?await kr(s.request,A,a,t.legacyTextEncoding):m==="workbook"?await Sr(s.request,A,a):await Er(s.request,A,a)}catch(k){return $(V(k,{operation:"asset",path:d},s.signal,c),a)}},Te=async(s,u)=>{if(l.deniesPath(u))return $e(c,{operation:"text",path:u}),y.failureDocument("forbidden");const a=await P(s,u);if(a.status==="error")return{kind:"failure",failure:a.failure};try{const d=He(await e.asset(s,u,a.readPath,{delivery:"text"})),m=await Ir(d,x,t.legacyTextEncoding);return m===null?y.failureDocument("unsupported"):{kind:"text",name:d.name,text:m.text,truncated:m.truncated,url:y.explorerAssetHref(t.dataPath,u,d.version)}}catch(d){return{kind:"failure",failure:V(d,{operation:"text",path:u},s.signal,c)}}},ge=async(s,u,a)=>l.deniesPath(a)?($e(c,{operation:u,path:a}),{status:"error",failure:{reason:"forbidden"}}):P(s,a),Yt=async(s,u,a)=>{const d=await ge(u,"edit",a);if(d.status==="error")return{kind:"failure",failure:d.failure};try{return xn(await s.source(u,a,d.readPath),g)}catch(m){return{kind:"failure",failure:V(m,{operation:"edit",path:a},u.signal,c)}}},Wt=async(s,u,a,d,m)=>{const p=await ge(u,"save",a);if(p.status==="error")return{kind:"failure",failure:p.failure};try{return Sn(await s.save(u,a,p.readPath,{text:m,baseVersion:d}),g)}catch(k){return{kind:"failure",failure:V(k,{operation:"save",path:a},u.signal,c)}}},Vt=async(s,u,a,d,m)=>{const p=await ge(u,"preview",d);if(p.status==="error")return{kind:"failure",failure:p.failure};let k;try{k=On(await s.preview(u,d,p.readPath,m))}catch(X){return{kind:"failure",failure:V(X,{operation:"preview",path:d},u.signal,c)}}if("kind"in k)return k.kind==="failure"?k:y.failureDocument("failed");const A=await R(k.html,{scope:a,signal:u.signal});return A.status==="sanitized"?{kind:"preview",htmlContent:A.html,headings:k.headings}:(A.cause!==null&&ae(c,{operation:"preview",path:d,error:A.cause}),y.failureDocument(A.reason))},Kt=async(s,u,a)=>{const d=await ge(u,"revisions",a);if(d.status==="error")return{kind:"failure",failure:d.failure};try{return{kind:"revisions",revisions:Rn(await s.revisions(u,a,d.readPath))}}catch(m){return{kind:"failure",failure:V(m,{operation:"revisions",path:a},u.signal,c)}}},Qt=async(s,u,a,d)=>{const m=await ge(u,"revision",a);if(m.status==="error")return{kind:"failure",failure:m.failure};try{return{kind:"revision",id:d,text:_n(await s.revision(u,a,m.readPath,d),g)}}catch(p){return{kind:"failure",failure:V(p,{operation:"revision",path:a},u.signal,c)}}},Zt=async(s,u,a,d,m,p)=>{const k=de(m,y.EXPLORER_DATA_QUERY.path);if(k===null||!y.isAcceptableDocumentPath(k))return $({reason:"invalid"},p);if(u==="edit")return q(200,JSON.stringify(await Yt(s,a,k)),p);if(u==="revisions")return q(200,JSON.stringify(await Kt(s,a,k)),p);if(u==="revision"){const oe=de(m,y.EXPLORER_DATA_QUERY.revision);return y.isExplorerEditToken(oe)?q(200,JSON.stringify(await Qt(s,a,k,oe)),p):$({reason:"invalid"},p)}const A=de(m,y.EXPLORER_DATA_QUERY.base);if(u==="save"&&!y.isExplorerEditToken(A))return $({reason:"invalid"},p);const X=await Gn(a.request,g);return X.status==="error"?$(X.failure,p):u==="preview"?q(200,JSON.stringify(await Vt(s,a,d,k,X.text)),p):q(200,JSON.stringify(await Wt(s,a,k,A,X.text)),p)},qt=async({request:s,url:u,params:a})=>{const d=ht(await I(s,ft)),m=mt(d.headers);if(m.set("Cache-Control",Ht),d.status==="signed-out")throw wt("signedOutPage",F(s,m));if(d.status==="forbidden")throw h===void 0?Pe.data(null,{status:403,headers:m}):wt("forbiddenPage",h(s,m));const p=J.resolveExplorerLocation(i,a["*"],u.searchParams);if(p.kind==="redirect")throw Pe.redirect(p.href,{headers:m});const{location:k}=p,{principal:A}=d,X=yt(r,C(A)),oe=z.get(k.source);if(oe===void 0)throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(k.source)}`);const Ee={signal:s.signal,timeoutMs:f,late:null,handOverMs:f},se={scope:X,sources:n.map(B=>({id:B.id,label:M(B,A)})),settings:J.parseViewSettings(J.readCookieValue(s.headers.get("Cookie"),t.settingsCookie),_),tree:k.view==="single"?null:{sourceId:k.source,result:Me(Ee,B=>L(oe,A,X,s,B).then(Z=>Z.result))},documents:Bn(k).map(B=>({path:B,document:Me(Ee,Z=>te({principal:A,request:s,signal:Z,refresh:!1},X,B))})),notices:Me({signal:s.signal,timeoutMs:f,late:ze,handOverMs:0},B=>ne({principal:A,request:s,signal:B,refresh:!1}))};return Pe.data(se,{headers:m})},Je=async(s,u)=>{const a=ht(await I(s,u));return{authentication:a,headers:mt(a.headers)}},er=async(s,u,a)=>{let d;try{d=await Je(u,ft)}catch(Z){return $(V(pt(Z),{operation:"authenticate"},u.signal,c))}const{authentication:m,headers:p}=d;if(m.status==="signed-out")return $({reason:"unauthorized"},p);if(m.status==="forbidden")return $({reason:"forbidden"},p);const{principal:k}=m;if(s==="asset")return le({principal:k,request:u,signal:u.signal,refresh:!1},a,p);const A=yt(r,C(k));p.set(y.EXPLORER_SCOPE_HEADER,A);const X={principal:k,request:u,signal:u.signal,refresh:!1},oe=()=>$({reason:"invalid"},p);if(s==="document"){const Z=de(a,y.EXPLORER_DATA_QUERY.path);if(Z===null||!y.isAcceptableDocumentPath(Z))return oe();const Ve=u.headers.has(y.EXPLORER_PROOF_HEADER);return Ve&&!Et(u)?$({reason:"forbidden"},p):q(200,JSON.stringify(await te({...X,refresh:Ve},A,Z)),p)}if(s==="text"){const Z=de(a,y.EXPLORER_DATA_QUERY.path);return Z===null||!y.isAcceptableDocumentPath(Z)?oe():q(200,JSON.stringify(await Te(X,Z)),p)}if(s==="edit"||s==="save"||s==="preview"||s==="revisions"||s==="revision")return w===void 0?$({reason:"not-found"},p):Zt(w,s,X,A,a,p);const Ee=de(a,y.EXPLORER_DATA_QUERY.source),se=de(a,y.EXPLORER_DATA_QUERY.path);if(Ee===null||(s==="children"||s==="ancestors"||s==="reveal")&&(se===null||!y.isAcceptableDocumentPath(se)))return oe();const B=z.get(Ee);if(B===void 0)return $({reason:"not-found"},p);if(s==="tree")return q(200,(await L(B,k,A,u,u.signal)).json,p);if(s==="refresh"){const Z=await K(B,k,A,u);return u.signal.aborted||Q(B,U(B,A)),q(200,Z.json,p)}return s==="ancestors"?B.ancestors===void 0||se===null?$({reason:"not-found"},p):q(200,JSON.stringify(await H(B,B.ancestors,X,se)),p):s==="reveal"?se===null?oe():q(200,JSON.stringify(await re(B,X,se)),p):B.children===void 0||se===null?$({reason:"not-found"},p):q(200,JSON.stringify(await Y(B,B.children,X,se)),p)},tr=async s=>{const{authentication:u,headers:a}=await Je(s,$n);if(!a.keys().next().done)throw new TypeError("[markdown-explorer] authenticate returned headers in read-only mode; a read-only authentication must only read the session (none was forwarded)");return u.status==="signed-in"},Ye=t.embeds.linkCardEndpoint===null?null:nr.createLinkCardHandler({authorize:tr}),rr=async(s,u)=>{try{return await s(u)}catch(a){return $(V(pt(a),{operation:"authenticate"},u.signal,c))}},We=async(s,u,a)=>{if(new URL(s.url).pathname.endsWith(".data"))return $({reason:"not-found"});if(!y.isExplorerDataOperation(a))return $({reason:"not-found"});if(a==="link-card"){if(Ye===null)return $({reason:"not-found"});const m=gt(s,a);return m!==null?m:rr(Ye,s)}if(Un.has(a)&&w===void 0)return $({reason:"not-found"});const d=gt(s,a);if(d!==null)return d;if(a==="refresh"&&!Et(s))return $({reason:"forbidden"});if((a==="save"||a==="preview")&&!Xn(s))return $({reason:"forbidden"});try{return await er(a,s,u.searchParams)}catch(m){return $(V(m,{operation:a},s.signal,c))}};return Object.freeze({loader:qt,headers:Yn,dataLoader:({request:s,url:u,params:a})=>We(s,u,a["*"]),dataAction:({request:s,url:u,params:a})=>We(s,u,a["*"]),forgetTree:s=>{if(typeof s!="string")throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof s}`);j.forget(s)}})},Oe=Object.freeze({maxEntries:2e4,maxDocumentBytes:2*1024*1024,textPreviewBytes:8*1024,walkConcurrency:8}),Vn=new Set(["md","markdown","mdx"]),bt="image/svg+xml",Bt=new Map([...[["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"],["svg",bt],["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",imageType:t===bt?"svg":"raster",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"}]]),Kn=new Map([["csv","csv"],["tsv","tsv"],["tab","tsv"],["xlsx","workbook"],["xlsm","workbook"],["ods","workbook"]]),Qn=new Set(["txt","text","log","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"]),Zn=new Set(["readme","license","licence","copying","notice","authors","contributors","changelog","changes","todo","makefile","dockerfile","containerfile","procfile","gemfile","rakefile","vagrantfile","jenkinsfile","brewfile","codeowners"]),Ft=typeof ue.constants.O_NOFOLLOW=="number"?ue.constants.O_NOFOLLOW:0,Ut=typeof ue.constants.O_NONBLOCK=="number"?ue.constants.O_NONBLOCK:0,Tt=e=>`${e.size}-${e.mtimeNs}`,qn=e=>e!==""&&e!=="."&&e!==".."&&!e.includes(":")&&!e.endsWith(".")&&!e.endsWith(" "),kt=e=>y.isAcceptableDocumentPath(e)&&e===e.normalize("NFC")&&e.split("/").every(qn),Xt=e=>{const t=e.toLowerCase(),r=t.lastIndexOf(".");return r<0?"":t.slice(r+1)},eo=e=>{const t=Xt(e);if(Vn.has(t))return{kind:"markdown"};const r=Bt.get(t);if(r!==void 0)return r.kind==="image"?{kind:"image",imageType:r.imageType}:{kind:"media",mediaType:r.mediaType};const n=Kn.get(t);if(n!==void 0)return{kind:"spreadsheet",format:n};const i=e.toLowerCase();return Qn.has(t)||!i.includes(".")&&Zn.has(i)?{kind:"text"}:{kind:"file"}},Be=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}},Gt=e=>{const t=Be(e);return t===null?e:new be(t)},Jt=e=>{const t=typeof e=="object"&&e!==null?e.code:void 0;return t==="EACCES"||t==="EPERM"||t==="ENOENT"||t==="ENOTDIR"},to=async e=>{try{return Math.trunc((await we.lstat(e)).mtimeMs)}catch(t){if(Jt(t))return;throw t}},xt=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)},ro=(e,t)=>e!==null?{start:e.offset,end:e.offset+e.length-1}:t===0n?{}:{start:0,end:Number(t)-1},no=async(e,t,r,n)=>{let i;try{i=await we.open(e,ue.constants.O_RDONLY|Ft|Ut);const f=await i.stat({bigint:!0});if(!f.isFile()||f.ino!==t.ino||f.dev!==t.dev||f.size!==t.size||f.mtimeNs!==t.mtimeNs)throw new be("not-found")}catch(f){throw await i?.close(),Gt(f)}const o=i.createReadStream(ro(r,t.size)),c=sr.Readable.toWeb(o),l=()=>{o.destroy(n.reason)};return n.aborted?l():n.addEventListener("abort",l,{once:!0}),c},oo=(e,t)=>{const r=J.NAME_COLLATOR.compare(e,t);return r!==0?r:e===t?0:e<t?-1:1},so=e=>{let t=0;const r=[];return async n=>{t<e?t+=1:await new Promise(i=>r.push(i));try{return await n()}finally{const i=r.shift();i===void 0?t-=1:i()}}},io=(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":y.isAcceptableDocumentPath(r)?y.isAcceptableDocumentPath(t)?null:"path-too-long":"control-character-or-backslash"},ao=new Set(["id","label","root","pathPrefix","parse","deny","maxEntries","maxDocumentBytes","textPreviewBytes","legacyTextEncoding","walkConcurrency","cacheScope","reportSkipped"]),Re=(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},co=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] createFileSystemSource needs an options object");for(const T of Object.keys(e))if(!ao.has(T))throw new TypeError(`[markdown-explorer] createFileSystemSource does not know the option ${JSON.stringify(T)}`);const{id:t,label:r,root:n,parse:i}=e;if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] a file-system source needs a non-empty id");if(typeof r!="string"||r.trim()==="")throw new TypeError("[markdown-explorer] a file-system source needs a non-blank label");if(typeof i!="function")throw new TypeError("[markdown-explorer] a file-system source needs a parse function");if(typeof n!="string"||!ie.isAbsolute(n))throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);let o;try{o=ue.statSync(n).isDirectory()}catch(T){throw new RangeError(`[markdown-explorer] root does not exist: ${n}`,{cause:T})}if(!o)throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);const c=ue.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("/")&&kt(l.slice(0,-1))))throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(l)}`);const f=y.resolvePathRules(e.deny),x=Re("maxEntries",e.maxEntries,Oe.maxEntries),w=Re("maxDocumentBytes",e.maxDocumentBytes,Oe.maxDocumentBytes),g=Re("textPreviewBytes",e.textPreviewBytes,Oe.textPreviewBytes),b=e.legacyTextEncoding;if(b!=null&&typeof b!="string")throw new TypeError("[markdown-explorer] legacyTextEncoding must be a string or null");const v=typeof b=="string"?J.legacyTextEncodingOf(b):null,j=Re("walkConcurrency",e.walkConcurrency,Oe.walkConcurrency),O=e.cacheScope===void 0?"principal":e.cacheScope;if(O!=="principal"&&O!=="shared")throw new RangeError(`[markdown-explorer] cacheScope must be "principal" or "shared"; got ${JSON.stringify(O)}`);const R=e.reportSkipped;if(R!==void 0&&typeof R!="function")throw new TypeError("[markdown-explorer] reportSkipped must be a function");const z=R===void 0?T=>{console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(T.sourceId)} does not list ${JSON.stringify(T.path)}: ${T.reason}`)}:R,_=new Set,I=T=>{const N=ie.resolve(c,...T.split("/")),P=ie.relative(c,N);return P===""||P===".."||P.startsWith(`..${ie.sep}`)||ie.isAbsolute(P)?null:N},C=(T,N)=>{const P=`${N}\0${T}`;_.has(P)||_.size>=x||(_.add(P),z({sourceId:t,path:T,reason:N}))},F=async({signal:T})=>{T.throwIfAborted();const N=new AbortController,P=()=>{N.abort(T.reason)};T.addEventListener("abort",P,{once:!0});const D=so(j);let G=0;const W=async(L,K)=>{const Q=await D(async()=>{N.signal.throwIfAborted();try{return await we.readdir(L,{withFileTypes:!0})}catch(H){if(K===""||!Jt(H))throw H;return null}});if(N.signal.throwIfAborted(),Q===null)return C(`${l}${K}`,"unreadable-directory"),null;const Y=[];for(const H of Q){if(f.deniesName(H.name))continue;const re=K===""?H.name:`${K}/${H.name}`,te=`${l}${re}`,ne=io(H,te);if(ne!==null){C(te,ne);continue}Y.push({dirent:H,relativePath:re,path:te})}if(G+=Y.length,G>x)throw new be("too-large");return Y.sort((H,re)=>oo(H.dirent.name,re.dirent.name)),(await Promise.all(Y.map(async({dirent:H,relativePath:re,path:te})=>{const ne=await to(ie.join(L,H.name)),le=ne===void 0?{}:{modifiedAt:ne};if(!H.isDirectory())return{name:H.name,path:te,type:"file",...le};const Te=await W(ie.join(L,H.name),re);return Te===null?null:{name:H.name,path:te,type:"directory",...le,children:Te}}))).filter(H=>H!==null)};try{const L=await W(c,"");if(L===null)throw new Error("[markdown-explorer] the source's root could not be listed");return L}catch(L){throw N.abort(),L}finally{T.removeEventListener("abort",P)}},h=async T=>{if(!T.startsWith(l))return{status:"refused",reason:"not-found"};const N=T.slice(l.length);if(!kt(N))return{status:"refused",reason:"invalid"};if(f.deniesPath(N))return{status:"refused",reason:"forbidden"};const P=I(N);if(P===null)return{status:"refused",reason:"forbidden"};const D=await we.lstat(P,{bigint:!0});if(D.isSymbolicLink())return{status:"refused",reason:"forbidden"};if(!D.isFile())return{status:"refused",reason:"unsupported"};const G=await we.realpath(P);return G!==P||f.deniesPath(ie.relative(c,G).split(ie.sep).join("/"))?{status:"refused",reason:"forbidden"}:{status:"file",target:P,name:N.slice(N.lastIndexOf("/")+1),stats:D}},E=async(T,N,P)=>{let D;try{const G=await h(P);if(G.status==="refused")return y.failureDocument(G.reason);const{target:W,name:L,stats:K}=G,Q=eo(L),Y=Tt(K);if(Q.kind==="image")return{kind:"image",name:L,imageType:Q.imageType,version:Y};if(Q.kind==="media")return{kind:"media",name:L,mediaType:Q.mediaType,version:Y};if(Q.kind==="spreadsheet")return{kind:"spreadsheet",name:L,format:Q.format,firstSheetText:null,edit:null,version:Y};if(Q.kind==="file")return{kind:"file",name:L,version:Y};D=await we.open(W,ue.constants.O_RDONLY|Ft|Ut);const ce=await D.stat({bigint:!0});if(!ce.isFile()||ce.ino!==K.ino||ce.dev!==K.dev)return y.failureDocument("forbidden");if(Q.kind==="markdown"){if(ce.size>BigInt(w))return y.failureDocument("too-large");const ne=await xt(D,w+1);if(ne.length>w)return y.failureDocument("too-large");const le=await i(J.decodeTextLeniently(ne,!0,v),N);return{kind:"markdown",name:L,htmlContent:le.htmlContent,headings:le.headings,edit:null}}const H=await xt(D,g),re=ce.size>BigInt(g),te=J.decodeTextLeniently(H,!re,v);return te.includes("\0")?{kind:"file",name:L,version:Y}:{kind:"text",name:L,text:te,truncated:re,version:Y}}catch(G){const W=Be(G);if(W===null)throw G;return y.failureDocument(W)}finally{await D?.close()}},M=async(T,N,P)=>{let D;try{D=await h(P)}catch(Y){throw Gt(Y)}if(D.status==="refused")throw new be(D.reason);const{target:G,name:W,stats:L}=D,K=Bt.get(Xt(W)),Q=K===void 0?"":K.contentType;return{name:W,contentType:Q,size:Number(L.size),version:Tt(L),open:Y=>no(G,L,Y,T.signal)}},U=async(T,N,P)=>{let D;try{D=await h(P)}catch(L){if(Be(L)!==null)return null;throw L}if(D.status==="refused")return null;const G=P.slice(l.length).split("/");if(G.some(L=>f.deniesName(L)))return null;const W=G.slice(0,-1);return W.map((L,K)=>`${l}${W.slice(0,K+1).join("/")}`)};return Object.freeze({id:t,label:r,cacheScope:O,boundary:Object.freeze({contains:T=>T.startsWith(l)}),tree:F,ancestors:U,document:E,asset:M})};exports.DEFAULT_DENIED_PATH_SEGMENTS=y.DEFAULT_DENIED_PATH_SEGMENTS;exports.MAX_DOCUMENT_PATH_LENGTH=y.MAX_DOCUMENT_PATH_LENGTH;exports.isAcceptableDocumentPath=y.isAcceptableDocumentPath;exports.isDeniedPath=y.isDeniedPath;exports.decodeText=J.decodeText;exports.decodeTextLeniently=J.decodeTextLeniently;exports.legacyTextEncodingOf=J.legacyTextEncodingOf;exports.ExplorerError=be;exports.anonymousAccess=ir;exports.createFileSystemSource=co;exports.createMarkdownExplorer=Wn;
package/dist/server.js CHANGED
@@ -1,7 +1,7 @@
1
- import { b as Nt, c as hr, f as ve, g as yr, h as gr, s as Er, j as br, k as Tr, l as kr, E as It, m as Ee, r as xr, n as Sr, i as re, o as Or, p as Rr, q as vr, t as Pt, u as _r, v as Ar, w as Be, x as Nr, y as Ir, z as Pr, A as ce, B as ee, e as Ke, C as Mr, D as $r } from "./dataRoute-DLhQfdoW.js";
2
- import { F as xs, M as Ss, G as Os } from "./dataRoute-DLhQfdoW.js";
3
- import { t as Mt, f as ze, w as Lr, g as jr, r as zr, i as Cr, h as Dr, p as Hr, j as Br, k as Fr, l as Ur, N as Xr } from "./location-perTmwct.js";
4
- import { m as vs } from "./location-perTmwct.js";
1
+ import { b as Nt, c as hr, f as ve, g as yr, h as gr, s as Er, j as br, k as Tr, m as kr, E as It, n as Ee, r as xr, o as Sr, i as re, p as Or, q as Rr, t as vr, u as Pt, v as _r, w as Ar, x as Be, y as Nr, z as Ir, A as Pr, B as ce, C as ee, e as Ke, D as Mr, F as $r } from "./dataRoute-D6KiSHIc.js";
2
+ import { G as xs, M as Ss, H as Os } from "./dataRoute-D6KiSHIc.js";
3
+ import { t as Mt, f as ze, w as Lr, g as jr, r as zr, i as Cr, h as Dr, p as Hr, j as Br, k as Fr, l as Ur, N as Xr } from "./location-C44b9H1S.js";
4
+ import { m as vs } from "./location-C44b9H1S.js";
5
5
  import { createHash as Jr, createHmac as Gr } from "node:crypto";
6
6
  import { createLinkCardHandler as Wr } from "@aiquants/markdown/server";
7
7
  import { crossOriginRefusal as $t, NO_CROSS_ORIGIN_NAVIGATION as Lt } from "@aiquants/request-isolation";