@aiquants/markdown-explorer 0.34.0 → 0.36.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 (146) hide show
  1. package/CHANGELOG.md +608 -0
  2. package/README.md +121 -41
  3. package/dist/EditSurface-B70iRFkG.cjs +6 -0
  4. package/dist/EditSurface-BCFJRyIM.js +990 -0
  5. package/dist/ExplorerSplit-BNrHrIus.cjs +2 -0
  6. package/dist/ExplorerSplit-Bgccz2nm.js +1589 -0
  7. package/dist/MultiLayout-Bo9LAXiY.cjs +1 -0
  8. package/dist/{MultiLayout-kcZyVnvK.js → MultiLayout-Dy5TIC2t.js} +249 -248
  9. package/dist/{NativeScrollBar-pUbA4Zq3.cjs → NativeScrollBar-Bj-LKej0.cjs} +1 -1
  10. package/dist/{NativeScrollBar-UNed10Na.js → NativeScrollBar-DpZMYhmf.js} +2 -2
  11. package/dist/TreeLayout-DsSKW_Qj.js +103 -0
  12. package/dist/TreeLayout-T8sc_wg7.cjs +1 -0
  13. package/dist/client/MarkdownExplorer.d.cts +14 -1
  14. package/dist/client/MarkdownExplorer.d.ts +14 -1
  15. package/dist/client/edit/lineEndings.d.cts +4 -0
  16. package/dist/client/edit/lineEndings.d.ts +4 -0
  17. package/dist/client/hostContract.d.cts +67 -0
  18. package/dist/client/hostContract.d.ts +67 -0
  19. package/dist/core/config.d.cts +13 -0
  20. package/dist/core/config.d.ts +13 -0
  21. package/dist/core/contracts.d.cts +31 -4
  22. package/dist/core/contracts.d.ts +31 -4
  23. package/dist/core/dataRoute.d.cts +5 -1
  24. package/dist/core/dataRoute.d.ts +5 -1
  25. package/dist/core/documentId.d.cts +6 -0
  26. package/dist/core/documentId.d.ts +6 -0
  27. package/dist/core/draftAnswer.d.cts +23 -0
  28. package/dist/core/draftAnswer.d.ts +23 -0
  29. package/dist/core/labels.d.cts +78 -0
  30. package/dist/core/labels.d.ts +78 -0
  31. package/dist/core/location.d.cts +22 -2
  32. package/dist/core/location.d.ts +22 -2
  33. package/dist/core/ownUrls.d.cts +15 -0
  34. package/dist/core/ownUrls.d.ts +15 -0
  35. package/dist/core/treeSettings.d.cts +3 -2
  36. package/dist/core/treeSettings.d.ts +3 -2
  37. package/dist/core/viewSettings.d.cts +3 -1
  38. package/dist/core/viewSettings.d.ts +3 -1
  39. package/dist/describeValue-CLlVRO8d.js +17 -0
  40. package/dist/describeValue-Ccvhbt36.cjs +1 -0
  41. package/dist/explorerCore-B3RGmMG6.js +1083 -0
  42. package/dist/explorerCore-CUkyKtm8.cjs +1 -0
  43. package/dist/index-D0l_BJqb.js +5980 -0
  44. package/dist/index-lpL7GltU.cjs +18 -0
  45. package/dist/index.cjs +1 -1
  46. package/dist/index.d.cts +8 -4
  47. package/dist/index.d.ts +8 -4
  48. package/dist/index.js +53 -43
  49. package/dist/licenses/@heroicons/react/LICENSE +21 -0
  50. package/dist/licenses/entities/LICENSE +11 -0
  51. package/dist/licenses/parse5/LICENSE +19 -0
  52. package/dist/location-Dh6K-y7w.js +761 -0
  53. package/dist/location-DrOP6t1F.cjs +1 -0
  54. package/dist/lru-DC8GBmkX.js +39 -0
  55. package/dist/lru-SGmUyBQU.cjs +1 -0
  56. package/dist/{merge-C1MWvhCS.js → merge-BwcqBd4c.js} +1 -1
  57. package/dist/{merge-BziXxZkE.cjs → merge-Dckw7r9T.cjs} +1 -1
  58. package/dist/nestingGuardWorker.js +5511 -0
  59. package/dist/ownUrls-BTPGNhBt.cjs +1 -0
  60. package/dist/ownUrls-DD0cSCsF.js +409 -0
  61. package/dist/sanitizeJob-BYqzjFJC.js +21 -0
  62. package/dist/sanitizeJob-CudE1RUP.cjs +1 -0
  63. package/dist/sanitizePolicy-C-ehd0J_.cjs +2 -0
  64. package/dist/sanitizePolicy-DAPnUUVm.js +139 -0
  65. package/dist/sanitizeWorker.cjs +1 -1
  66. package/dist/sanitizeWorker.js +134 -139
  67. package/dist/sanitizerService-B8v4ap9t.js +240 -0
  68. package/dist/sanitizerService-DomN7lwC.cjs +1 -0
  69. package/dist/server/assetResponse.d.cts +60 -0
  70. package/dist/server/assetResponse.d.ts +60 -0
  71. package/dist/server/browser/browserPlatform.d.cts +12 -0
  72. package/dist/server/browser/browserPlatform.d.ts +12 -0
  73. package/dist/server/createMarkdownExplorer.d.cts +0 -10
  74. package/dist/server/createMarkdownExplorer.d.ts +0 -10
  75. package/dist/server/errors.d.cts +1 -1
  76. package/dist/server/errors.d.ts +1 -1
  77. package/dist/server/explorerCore.d.cts +12 -0
  78. package/dist/server/explorerCore.d.ts +12 -0
  79. package/dist/server/fileSystemSource.d.cts +1 -0
  80. package/dist/server/fileSystemSource.d.ts +1 -0
  81. package/dist/server/inProcessFetch.d.cts +5 -0
  82. package/dist/server/inProcessFetch.d.ts +5 -0
  83. package/dist/server/platform.d.cts +18 -0
  84. package/dist/server/platform.d.ts +18 -0
  85. package/dist/server/ports.d.cts +55 -5
  86. package/dist/server/ports.d.ts +55 -5
  87. package/dist/server/sanitizeProtocol.d.cts +3 -0
  88. package/dist/server/sanitizeProtocol.d.ts +3 -0
  89. package/dist/server/sanitizer.d.cts +5 -40
  90. package/dist/server/sanitizer.d.ts +5 -40
  91. package/dist/server/sanitizerOptions.d.cts +24 -0
  92. package/dist/server/sanitizerOptions.d.ts +24 -0
  93. package/dist/server/sanitizerService.d.cts +41 -0
  94. package/dist/server/sanitizerService.d.ts +41 -0
  95. package/dist/server/{workerPool.d.cts → workerJobs.d.cts} +0 -16
  96. package/dist/server/{workerPool.d.ts → workerJobs.d.ts} +0 -16
  97. package/dist/server.cjs +1 -1
  98. package/dist/server.d.cts +3 -1
  99. package/dist/server.d.ts +3 -1
  100. package/dist/server.js +270 -1343
  101. package/dist/serverBrowser.cjs +1 -0
  102. package/dist/serverBrowser.d.cts +1 -0
  103. package/dist/serverBrowser.d.ts +1 -0
  104. package/dist/serverBrowser.js +120 -0
  105. package/dist/serverCore.cjs +1 -0
  106. package/dist/serverCore.d.cts +14 -0
  107. package/dist/serverCore.d.ts +14 -0
  108. package/dist/serverCore.js +46 -0
  109. package/dist/storage-BpYsprog.cjs +1 -0
  110. package/dist/{storage-CmGHg7OA.js → storage-D1uSw-xj.js} +19 -18
  111. package/dist/storage.cjs +1 -1
  112. package/dist/storage.js +1 -1
  113. package/dist/styles/markdown-explorer.css +1 -1
  114. package/dist/{tapScrollCircle-DigcJCsu.cjs → tapScrollCircle-DyLInGck.cjs} +1 -1
  115. package/dist/{tapScrollCircle-D_BpaLwY.js → tapScrollCircle-smKLgRa2.js} +1 -1
  116. package/dist/testing.cjs +1 -0
  117. package/dist/testing.d.cts +11 -0
  118. package/dist/testing.d.ts +11 -0
  119. package/dist/testing.js +82 -0
  120. package/dist/useSplitPersistence-BUa_KMsV.cjs +1 -0
  121. package/dist/useSplitPersistence-pnb21dsr.js +44 -0
  122. package/docs/behavior/dom-hooks.md +5 -1
  123. package/docs/behavior/hosting.md +123 -0
  124. package/docs/behavior/layout.md +5 -3
  125. package/docs/behavior/localization.md +25 -8
  126. package/docs/behavior/security.md +55 -15
  127. package/docs/behavior/url-contract.md +30 -3
  128. package/package.json +48 -10
  129. package/dist/EditSurface-CF82jZQg.cjs +0 -6
  130. package/dist/EditSurface-CqHk2R3k.js +0 -982
  131. package/dist/ExplorerSplit-D325YGEf.cjs +0 -1
  132. package/dist/ExplorerSplit-DGH9bckm.js +0 -1500
  133. package/dist/MultiLayout-CzR7yJ0m.cjs +0 -1
  134. package/dist/TreeLayout-BnIU87HX.js +0 -96
  135. package/dist/TreeLayout-DtvIpuOe.cjs +0 -1
  136. package/dist/dataRoute-D6KiSHIc.js +0 -298
  137. package/dist/dataRoute-DwYtgyt6.cjs +0 -1
  138. package/dist/index-BDCbvHDs.cjs +0 -15
  139. package/dist/index-DR31S_-4.js +0 -5012
  140. package/dist/location-C44b9H1S.js +0 -676
  141. package/dist/location-hGLhCCg4.cjs +0 -1
  142. package/dist/sanitizePolicy-CwvyPpp5.js +0 -98
  143. package/dist/sanitizePolicy-T5T-3vV5.cjs +0 -1
  144. package/dist/storage-DM0EvkVf.cjs +0 -1
  145. package/dist/useSplitPersistence-DCeYbJMx.js +0 -38
  146. package/dist/useSplitPersistence-QGcvyMAa.cjs +0 -1
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-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;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("./ownUrls-BTPGNhBt.cjs"),v=require("./location-DrOP6t1F.cjs"),P=require("./explorerCore-CUkyKtm8.cjs"),ne=require("node:crypto"),ye=require("@aiquants/markdown/server"),N=require("node:fs"),S=require("node:path"),U=require("node:url"),O=require("./describeValue-Ccvhbt36.cjs"),i=require("./sanitizerService-DomN7lwC.cjs"),q=require("./lru-SGmUyBQU.cjs"),be=require("node:worker_threads"),R=require("node:fs/promises"),xe=require("node:stream");var G=typeof document<"u"?document.currentScript:null;const J=Object.freeze({kind:"anonymous"}),Se=Object.freeze({authenticate:async()=>({status:"signed-in",principal:J}),principalKey:()=>J.kind,signedOutPage:(e,t)=>new Response(null,{status:401,headers:t})}),ke=(e,t)=>{const r=new be.Worker(e,{resourceLimits:t});return{postMessage:o=>{r.postMessage(o)},terminate:()=>r.terminate(),ref:()=>{r.ref()},unref:()=>{r.unref()},listen:({message:o,failure:a})=>{r.on("message",o),r.on("error",a),r.on("messageerror",a),r.on("exit",p=>{a(new Error(`[markdown-explorer] a worker exited with code ${String(p)}`))})}}},Te=({url:e,size:t,deadlineMs:r,jobsPerScope:o,maxQueuedJobs:a,heapLimits:p})=>{i.assertPoolLimit("size",t,Number.MAX_SAFE_INTEGER),i.assertPoolLimit("deadline",r,q.MAX_TIMER_MILLISECONDS),i.assertPoolLimit("jobsPerScope",o,Number.MAX_SAFE_INTEGER),i.assertPoolLimit("maxQueuedJobs",a,Number.MAX_SAFE_INTEGER),i.assertPoolLimit("maxOldGenerationSizeMb",p.maxOldGenerationSizeMb,Number.MAX_SAFE_INTEGER),i.assertPoolLimit("maxYoungGenerationSizeMb",p.maxYoungGenerationSizeMb,Number.MAX_SAFE_INTEGER);const x=Object.freeze({maxOldGenerationSizeMb:p.maxOldGenerationSizeMb,maxYoungGenerationSizeMb:p.maxYoungGenerationSizeMb});return i.createWorkerPoolCore({start:()=>ke(e,x),size:t,deadlineMs:r,jobsPerScope:o,maxQueuedJobs:a})},_e=2,Oe=32,se=({workerHeapMb:e,maxHtmlBytes:t})=>i.htmlNodeBudgetOf(t,e),Ne=64,Me=1024*1024,ve=(e,t)=>{if(e!==void 0&&!O.isPlainObject(e))throw new TypeError("[markdown-explorer] sanitizer must be a plain object of { workers, deadlineMs, maxHtmlBytes, cacheBytes, workerHeapMb, jobsPerScope, maxQueuedJobs }");const{workers:r,deadlineMs:o,maxHtmlBytes:a,cacheBytes:p,workerHeapMb:x,jobsPerScope:l,maxQueuedJobs:w}=e??{},L=i.readLimit("workers",r,_e,Ne),I=i.readLimit("jobsPerScope",l,i.defaultSanitizerJobsPerScope(t,L),Number.MAX_SAFE_INTEGER),k=Object.freeze({workers:L,deadlineMs:i.readLimit("deadlineMs",o,i.DEFAULT_SANITIZER_DEADLINE_MS,q.MAX_TIMER_MILLISECONDS),maxHtmlBytes:i.readLimit("maxHtmlBytes",a,i.DEFAULT_SANITIZER_MAX_HTML_BYTES,i.MAX_HTML_BYTES),cacheBytes:i.readLimit("cacheBytes",p,i.DEFAULT_SANITIZER_CACHE_BYTES,Number.MAX_SAFE_INTEGER),workerHeapMb:i.readLimit("workerHeapMb",x,i.DEFAULT_SANITIZER_WORKER_HEAP_MB,Me),jobsPerScope:I,maxQueuedJobs:i.readLimit("maxQueuedJobs",w,i.SANITIZER_QUEUED_READERS*I,Number.MAX_SAFE_INTEGER)});if(i.assertAdmissionCoversPanels(k,t),se(k)<i.MIN_HTML_NODE_BUDGET)throw new RangeError(`[markdown-explorer] sanitizer.workerHeapMb (${String(k.workerHeapMb)} MiB) must leave room for ${String(i.MIN_HTML_NODE_BUDGET)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(k.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`);return k},Le=()=>{const e=typeof document>"u"?require("url").pathToFileURL(__filename).href:G&&G.tagName.toUpperCase()==="SCRIPT"&&G.src||new URL("server.cjs",document.baseURI).href,t=new URL(`./sanitizeWorker${S.extname(U.fileURLToPath(e))}`,e);if(!N.existsSync(U.fileURLToPath(t)))throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${U.fileURLToPath(t)}`);return t},Q=new Map,Ae=(e,t)=>{const r=[e.href,t.workers,t.deadlineMs,t.workerHeapMb,t.jobsPerScope,t.maxQueuedJobs].map(String).join("\0");let o=Q.get(r);return o===void 0&&(o=Te({url:e,size:t.workers,deadlineMs:t.deadlineMs,jobsPerScope:t.jobsPerScope,maxQueuedJobs:t.maxQueuedJobs,heapLimits:{maxOldGenerationSizeMb:t.workerHeapMb,maxYoungGenerationSizeMb:Oe}}),Q.set(r,o)),o},Re=e=>e instanceof Error&&e.code==="ERR_WORKER_OUT_OF_MEMORY",Pe=e=>({utf8Bytes:Buffer.byteLength(e,"utf8"),hash:ne.createHash("sha256").update(e,"utf8").digest("base64")}),Ie=e=>t=>Re(t)?{reason:"too-large",message:`[markdown-explorer] the HTML sanitizer ran out of its ${String(e)} MiB worker heap`}:null,Z=32,De=e=>{if(typeof e!="string")throw new TypeError(`[markdown-explorer] scopeSecret must be a string; got ${typeof e}`);if(e.length<Z)throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(Z)} characters; got ${String(e.length)}`);return e},je=({scopeSecret:e})=>Object.freeze({prepareScope:()=>{const r=De(e);return o=>ne.createHmac("sha256",r).update(o,"utf8").digest("base64url").slice(0,q.EXPLORER_SCOPE_LENGTH)},createSanitizer:({options:r,maxPanels:o,iframeHosts:a,dataPath:p,ownUrls:x})=>{const l=ve(r,o);return i.createHtmlSanitizerService({iframeHosts:a,dataPath:p,ownUrls:x,limits:l,nodeBudget:se(l),measureHtml:Pe,classifyCrash:Ie(l.workerHeapMb),pool:Ae(Le(),l)})},createLinkCardHandler:r=>ye.createLinkCardHandler(r)}),Be=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the server configuration must be an object");const{scopeSecret:t,...r}=e;return P.createExplorerServer({...r,readSettings:o=>v.readCookieValue(o.headers.get("Cookie"),e.config.settingsCookie),assetMaxRangeBytes:null},je({scopeSecret:t}))},z=Object.freeze({maxEntries:2e4,maxDocumentBytes:2*1024*1024,textPreviewBytes:8*1024,walkConcurrency:8}),Ce=new Set(["md","markdown","mdx"]),ee="image/svg+xml",ae=new Map([...[["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"],["svg",ee],["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===ee?"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"}]]),ze=new Map([["csv","csv"],["tsv","tsv"],["tab","tsv"],["xlsx","workbook"],["xlsm","workbook"],["ods","workbook"]]),He=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"]),Fe=new Set(["readme","license","licence","copying","notice","authors","contributors","changelog","changes","todo","makefile","dockerfile","containerfile","procfile","gemfile","rakefile","vagrantfile","jenkinsfile","brewfile","codeowners"]),ie=typeof N.constants.O_NOFOLLOW=="number"?N.constants.O_NOFOLLOW:0,ce=typeof N.constants.O_NONBLOCK=="number"?N.constants.O_NONBLOCK:0,te=e=>`${e.size}-${e.mtimeNs}`,$e=e=>e!==""&&e!=="."&&e!==".."&&!e.includes(":")&&!e.endsWith(".")&&!e.endsWith(" "),re=e=>g.isAcceptableDocumentPath(e)&&e===e.normalize("NFC")&&e.split("/").every($e),le=e=>{const t=e.toLowerCase(),r=t.lastIndexOf(".");return r<0?"":t.slice(r+1)},Ue=e=>{const t=le(e);if(Ce.has(t))return{kind:"markdown"};const r=ae.get(t);if(r!==void 0)return r.kind==="image"?{kind:"image",imageType:r.imageType}:{kind:"media",mediaType:r.mediaType};const o=ze.get(t);if(o!==void 0)return{kind:"spreadsheet",format:o};const a=e.toLowerCase();return He.has(t)||!a.includes(".")&&Fe.has(a)?{kind:"text"}:{kind:"file"}},W=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}},de=e=>{const t=W(e);return t===null?e:new P.ExplorerError(t)},ue=e=>{const t=typeof e=="object"&&e!==null?e.code:void 0;return t==="EACCES"||t==="EPERM"||t==="ENOENT"||t==="ENOTDIR"},Ge=async e=>{try{return Math.trunc((await R.lstat(e)).mtimeMs)}catch(t){if(ue(t))return;throw t}},oe=async(e,t)=>{const r=[];for await(const o of e.createReadStream({start:0,end:t-1,autoClose:!1}))r.push(o);return Buffer.concat(r)},We=(e,t)=>e!==null?{start:e.offset,end:e.offset+e.length-1}:t===0n?{}:{start:0,end:Number(t)-1},qe=async(e,t,r,o)=>{let a;try{a=await R.open(e,N.constants.O_RDONLY|ie|ce);const w=await a.stat({bigint:!0});if(!w.isFile()||w.ino!==t.ino||w.dev!==t.dev||w.size!==t.size||w.mtimeNs!==t.mtimeNs)throw new P.ExplorerError("not-found")}catch(w){throw await a?.close(),de(w)}const p=a.createReadStream(We(r,t.size)),x=xe.Readable.toWeb(p),l=()=>{p.destroy(o.reason)};return o.aborted?l():o.addEventListener("abort",l,{once:!0}),x},Xe=(e,t)=>{const r=v.NAME_COLLATOR.compare(e,t);return r!==0?r:e===t?0:e<t?-1:1},Ye=e=>{let t=0;const r=[];return async o=>{t<e?t+=1:await new Promise(a=>r.push(a));try{return await o()}finally{const a=r.shift();a===void 0?t-=1:a()}}},Ve=(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":g.isAcceptableDocumentPath(r)?g.isAcceptableDocumentPath(t)?null:"path-too-long":"control-character-or-backslash"},Ke=new Set(["id","label","root","pathPrefix","lang","parse","deny","maxEntries","maxDocumentBytes","textPreviewBytes","legacyTextEncoding","walkConcurrency","cacheScope","reportSkipped"]),H=(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 ${O.describeValue(t)}`);return t},Je=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] createFileSystemSource needs an options object");for(const n of Object.keys(e))if(!Ke.has(n))throw new TypeError(`[markdown-explorer] createFileSystemSource does not know the option ${O.describeValue(n)}`);const{id:t,label:r,root:o,parse:a}=e;if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] a file-system source needs a non-empty id");if(typeof r!="string"||r.trim()==="")throw new TypeError("[markdown-explorer] a file-system source needs a non-blank label");if(typeof a!="function")throw new TypeError("[markdown-explorer] a file-system source needs a parse function");if(typeof o!="string"||!S.isAbsolute(o))throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${O.describeValue(o)}`);let p;try{p=N.statSync(o).isDirectory()}catch(n){throw new RangeError(`[markdown-explorer] root does not exist: ${o}`,{cause:n})}if(!p)throw new RangeError(`[markdown-explorer] root is not a directory: ${o}`);const x=N.realpathSync(o),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("/")&&re(l.slice(0,-1))))throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${O.describeValue(l)}`);const w=e.lang;if(typeof w!="string")throw new TypeError('[markdown-explorer] lang is required: the language of the documents, a canonical BCP 47 language tag such as "ja" or "en-US"');if(!g.isExplorerDocumentLang(w))throw new RangeError(`[markdown-explorer] lang must be a canonical BCP 47 language tag (such as "ja" or "en-US"); got ${O.describeValue(w)}`);const L=g.resolvePathRules(e.deny),I=H("maxEntries",e.maxEntries,z.maxEntries),k=H("maxDocumentBytes",e.maxDocumentBytes,z.maxDocumentBytes),X=H("textPreviewBytes",e.textPreviewBytes,z.textPreviewBytes),D=e.legacyTextEncoding;if(D!=null&&typeof D!="string")throw new TypeError("[markdown-explorer] legacyTextEncoding must be a string or null");const Y=typeof D=="string"?v.legacyTextEncodingOf(D):null,me=H("walkConcurrency",e.walkConcurrency,z.walkConcurrency),B=e.cacheScope===void 0?"principal":e.cacheScope;if(B!=="principal"&&B!=="shared")throw new RangeError(`[markdown-explorer] cacheScope must be "principal" or "shared"; got ${O.describeValue(B)}`);const C=e.reportSkipped;if(C!==void 0&&typeof C!="function")throw new TypeError("[markdown-explorer] reportSkipped must be a function");const fe=C===void 0?n=>{console.warn(`[markdown-explorer] the file-system source ${O.describeValue(n.sourceId)} does not list ${O.describeValue(n.path)}: ${n.reason}`)}:C,F=new Set,pe=n=>{const d=S.resolve(x,...n.split("/")),c=S.relative(x,d);return c===""||c===".."||c.startsWith(`..${S.sep}`)||S.isAbsolute(c)?null:d},V=(n,d)=>{const c=`${d}\0${n}`;F.has(c)||F.size>=I||(F.add(c),fe({sourceId:t,path:n,reason:d}))},we=async({signal:n})=>{n.throwIfAborted();const d=new AbortController,c=()=>{d.abort(n.reason)};n.addEventListener("abort",c,{once:!0});const m=Ye(me);let f=0;const h=async(s,y)=>{const b=await m(async()=>{d.signal.throwIfAborted();try{return await R.readdir(s,{withFileTypes:!0})}catch(u){if(y===""||!ue(u))throw u;return null}});if(d.signal.throwIfAborted(),b===null)return V(`${l}${y}`,"unreadable-directory"),null;const E=[];for(const u of b){if(L.deniesName(u.name))continue;const T=y===""?u.name:`${y}/${u.name}`,_=`${l}${T}`,M=Ve(u,_);if(M!==null){V(_,M);continue}E.push({dirent:u,relativePath:T,path:_})}if(f+=E.length,f>I)throw new P.ExplorerError("too-large");return E.sort((u,T)=>Xe(u.dirent.name,T.dirent.name)),(await Promise.all(E.map(async({dirent:u,relativePath:T,path:_})=>{const M=await Ge(S.join(s,u.name)),j=M===void 0?{}:{modifiedAt:M};if(!u.isDirectory())return{name:u.name,path:_,type:"file",...j};const K=await h(S.join(s,u.name),T);return K===null?null:{name:u.name,path:_,type:"directory",...j,children:K}}))).filter(u=>u!==null)};try{const s=await h(x,"");if(s===null)throw new Error("[markdown-explorer] the source's root could not be listed");return s}catch(s){throw d.abort(),s}finally{n.removeEventListener("abort",c)}},$=async n=>{if(!n.startsWith(l))return{status:"refused",reason:"not-found"};const d=n.slice(l.length);if(!re(d))return{status:"refused",reason:"invalid"};if(L.deniesPath(d))return{status:"refused",reason:"forbidden"};const c=pe(d);if(c===null)return{status:"refused",reason:"forbidden"};const m=await R.lstat(c,{bigint:!0});if(m.isSymbolicLink())return{status:"refused",reason:"forbidden"};if(!m.isFile())return{status:"refused",reason:"unsupported"};const f=await R.realpath(c);return f!==c||L.deniesPath(S.relative(x,f).split(S.sep).join("/"))?{status:"refused",reason:"forbidden"}:{status:"file",target:c,name:d.slice(d.lastIndexOf("/")+1),stats:m}},Ee=async(n,d,c)=>{let m;try{const f=await $(c);if(f.status==="refused")return g.failureDocument(f.reason);const{target:h,name:s,stats:y}=f,b=Ue(s),E=te(y);if(b.kind==="image")return{kind:"image",name:s,imageType:b.imageType,version:E};if(b.kind==="media")return{kind:"media",name:s,mediaType:b.mediaType,version:E};if(b.kind==="spreadsheet")return{kind:"spreadsheet",name:s,format:b.format,firstSheetText:null,edit:null,version:E};if(b.kind==="file")return{kind:"file",name:s,version:E};m=await R.open(h,N.constants.O_RDONLY|ie|ce);const A=await m.stat({bigint:!0});if(!A.isFile()||A.ino!==y.ino||A.dev!==y.dev)return g.failureDocument("forbidden");if(b.kind==="markdown"){if(A.size>BigInt(k))return g.failureDocument("too-large");const M=await oe(m,k+1);if(M.length>k)return g.failureDocument("too-large");const j=await a(v.decodeTextLeniently(M,!0,Y),d);return{kind:"markdown",name:s,htmlContent:j.htmlContent,headings:j.headings,lang:w,edit:null}}const u=await oe(m,X),T=A.size>BigInt(X),_=v.decodeTextLeniently(u,!T,Y);return _.includes("\0")?{kind:"file",name:s,version:E}:{kind:"text",name:s,text:_,truncated:T,lang:w,version:E}}catch(f){const h=W(f);if(h===null)throw f;return g.failureDocument(h)}finally{await m?.close()}},ge=async(n,d,c)=>{let m;try{m=await $(c)}catch(E){throw de(E)}if(m.status==="refused")throw new P.ExplorerError(m.reason);const{target:f,name:h,stats:s}=m,y=ae.get(le(h)),b=y===void 0?"":y.contentType;return{name:h,contentType:b,size:Number(s.size),version:te(s),open:E=>qe(f,s,E,n.signal)}},he=async(n,d,c)=>{let m;try{m=await $(c)}catch(s){if(W(s)!==null)return null;throw s}if(m.status==="refused")return null;const f=c.slice(l.length).split("/");if(f.some(s=>L.deniesName(s)))return null;const h=f.slice(0,-1);return h.map((s,y)=>`${l}${h.slice(0,y+1).join("/")}`)};return Object.freeze({id:t,label:r,cacheScope:B,boundary:Object.freeze({contains:n=>n.startsWith(l)}),tree:we,ancestors:he,document:Ee,asset:ge})};exports.DEFAULT_DENIED_PATH_SEGMENTS=g.DEFAULT_DENIED_PATH_SEGMENTS;exports.MAX_DOCUMENT_PATH_LENGTH=g.MAX_DOCUMENT_PATH_LENGTH;exports.isAcceptableDocumentPath=g.isAcceptableDocumentPath;exports.isDeniedPath=g.isDeniedPath;exports.decodeText=v.decodeText;exports.decodeTextLeniently=v.decodeTextLeniently;exports.legacyTextEncodingOf=v.legacyTextEncodingOf;exports.ExplorerError=P.ExplorerError;exports.anonymousAccess=Se;exports.createFileSystemSource=Je;exports.createMarkdownExplorer=Be;
package/dist/server.d.cts CHANGED
@@ -1,8 +1,10 @@
1
+ export type { ExplorerAssetDisplay } from "./core/dataRoute.cjs";
1
2
  export { DEFAULT_DENIED_PATH_SEGMENTS, type ExplorerPathRules, isAcceptableDocumentPath, isDeniedPath, MAX_DOCUMENT_PATH_LENGTH } from "./core/paths.cjs";
2
3
  export { decodeText, decodeTextLeniently, legacyTextEncodingOf } from "./core/textEncoding.cjs";
3
4
  export { type AnonymousAccess, type AnonymousPrincipal, anonymousAccess } from "./server/anonymous.cjs";
4
5
  export { createMarkdownExplorer } from "./server/createMarkdownExplorer.cjs";
5
6
  export { ExplorerError, type ExplorerLogDetail, type ExplorerLogger, type ExplorerOperation } from "./server/errors.cjs";
6
7
  export { createFileSystemSource, type FileSystemSkippedEntry, type FileSystemSkipReason, type FileSystemSource, type FileSystemSourceOptions } from "./server/fileSystemSource.cjs";
7
- export type { ExplorerAncestorsOptions, ExplorerAssetFile, ExplorerAssetOptions, ExplorerAssetRedirect, ExplorerAuthentication, ExplorerAuthenticationMode, ExplorerBoundaryAnswer, ExplorerByteRange, ExplorerDraft, ExplorerEditPorts, ExplorerHostDocument, ExplorerHostEditSource, ExplorerHostPreview, ExplorerHostSaveResult, ExplorerPageLoaderResult, ExplorerSource, ExplorerSourceBoundary, ExplorerSourceContext, MarkdownExplorerServer, MarkdownExplorerServerConfig, } from "./server/ports.cjs";
8
+ export type { ExplorerAncestorsOptions, ExplorerAssetFile, ExplorerAssetOptions, ExplorerAssetRedirect, ExplorerAuthentication, ExplorerAuthenticationMode, ExplorerBoundaryAnswer, ExplorerByteRange, ExplorerDataPlan, ExplorerDocumentIdBinding, ExplorerDocumentIdIssue, ExplorerDocumentIdPorts, ExplorerEditPorts, ExplorerHostDocument, ExplorerHostEditSource, ExplorerHostPreview, ExplorerHostSaveDraft, ExplorerHostSaveResult, ExplorerPageLoaderResult, ExplorerServerSharedConfig, ExplorerSource, ExplorerSourceBoundary, ExplorerSourceContext, MarkdownExplorerServer, MarkdownExplorerServerConfig, } from "./server/ports.cjs";
8
9
  export type { HtmlSanitizerOptions } from "./server/sanitizer.cjs";
10
+ export type { SanitizerLimitsInput } from "./server/sanitizerOptions.cjs";
package/dist/server.d.ts CHANGED
@@ -1,8 +1,10 @@
1
+ export type { ExplorerAssetDisplay } from "./core/dataRoute.js";
1
2
  export { DEFAULT_DENIED_PATH_SEGMENTS, type ExplorerPathRules, isAcceptableDocumentPath, isDeniedPath, MAX_DOCUMENT_PATH_LENGTH } from "./core/paths.js";
2
3
  export { decodeText, decodeTextLeniently, legacyTextEncodingOf } from "./core/textEncoding.js";
3
4
  export { type AnonymousAccess, type AnonymousPrincipal, anonymousAccess } from "./server/anonymous.js";
4
5
  export { createMarkdownExplorer } from "./server/createMarkdownExplorer.js";
5
6
  export { ExplorerError, type ExplorerLogDetail, type ExplorerLogger, type ExplorerOperation } from "./server/errors.js";
6
7
  export { createFileSystemSource, type FileSystemSkippedEntry, type FileSystemSkipReason, type FileSystemSource, type FileSystemSourceOptions } from "./server/fileSystemSource.js";
7
- export type { ExplorerAncestorsOptions, ExplorerAssetFile, ExplorerAssetOptions, ExplorerAssetRedirect, ExplorerAuthentication, ExplorerAuthenticationMode, ExplorerBoundaryAnswer, ExplorerByteRange, ExplorerDraft, ExplorerEditPorts, ExplorerHostDocument, ExplorerHostEditSource, ExplorerHostPreview, ExplorerHostSaveResult, ExplorerPageLoaderResult, ExplorerSource, ExplorerSourceBoundary, ExplorerSourceContext, MarkdownExplorerServer, MarkdownExplorerServerConfig, } from "./server/ports.js";
8
+ export type { ExplorerAncestorsOptions, ExplorerAssetFile, ExplorerAssetOptions, ExplorerAssetRedirect, ExplorerAuthentication, ExplorerAuthenticationMode, ExplorerBoundaryAnswer, ExplorerByteRange, ExplorerDataPlan, ExplorerDocumentIdBinding, ExplorerDocumentIdIssue, ExplorerDocumentIdPorts, ExplorerEditPorts, ExplorerHostDocument, ExplorerHostEditSource, ExplorerHostPreview, ExplorerHostSaveDraft, ExplorerHostSaveResult, ExplorerPageLoaderResult, ExplorerServerSharedConfig, ExplorerSource, ExplorerSourceBoundary, ExplorerSourceContext, MarkdownExplorerServer, MarkdownExplorerServerConfig, } from "./server/ports.js";
8
9
  export type { HtmlSanitizerOptions } from "./server/sanitizer.js";
10
+ export type { SanitizerLimitsInput } from "./server/sanitizerOptions.js";