@aiquants/markdown-explorer 0.39.0 → 0.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/README.md +3 -1
- package/dist/{EditSurface-CZnjX0sv.cjs → EditSurface-DFHZLbWC.cjs} +1 -1
- package/dist/{EditSurface-CUPN9dUY.js → EditSurface-DV4FuQVx.js} +3 -3
- package/dist/{ExplorerSplit-DHpgdXhb.js → ExplorerSplit-DTkr0q2C.js} +4 -4
- package/dist/{ExplorerSplit-DWBhCe7m.cjs → ExplorerSplit-DnuuUifU.cjs} +1 -1
- package/dist/{MultiLayout-BkHbfUuh.cjs → MultiLayout-CC0VPiFf.cjs} +1 -1
- package/dist/{MultiLayout-HmvjE8ht.js → MultiLayout-S77I1xQr.js} +3 -3
- package/dist/{NativeScrollBar-CzGhZ-w3.cjs → NativeScrollBar-C2n-DzEJ.cjs} +1 -1
- package/dist/{NativeScrollBar-DAukiH01.js → NativeScrollBar-DMCPxFeR.js} +2 -2
- package/dist/{TreeLayout-dtnugwQ7.js → TreeLayout-BGTzh0L4.js} +3 -3
- package/dist/{TreeLayout-BEvPaxLb.cjs → TreeLayout-DjJMAxWJ.cjs} +1 -1
- package/dist/core/config.d.cts +2 -0
- package/dist/core/config.d.ts +2 -0
- package/dist/{explorerCore-CUtc1Vmx.js → explorerCore-COhVrnGO.js} +1 -1
- package/dist/{explorerCore-Dj7RxZRd.cjs → explorerCore-diILGZTv.cjs} +1 -1
- package/dist/{index-D6at9qMs.cjs → index-AfEbgYQI.cjs} +8 -8
- package/dist/{index-BBJoJu-b.js → index-CWFyLa0N.js} +9 -8
- package/dist/index.cjs +1 -1
- package/dist/index.js +2 -2
- package/dist/location-Csj3eAm_.cjs +1 -0
- package/dist/{location-T9o5XYpX.js → location-DFfbnUZ9.js} +26 -19
- package/dist/{merge-CkMe5hqA.js → merge-D-Oak4Xy.js} +1 -1
- package/dist/{merge-XyuOlVWP.cjs → merge-DvoikrFp.cjs} +1 -1
- package/dist/server.cjs +1 -1
- package/dist/server.js +3 -3
- package/dist/serverCore.cjs +1 -1
- package/dist/serverCore.js +3 -3
- package/dist/styles/markdown-explorer.css +1 -1
- package/dist/{tapScrollCircle-ExxyHVWY.cjs → tapScrollCircle-CS3hbyGb.cjs} +1 -1
- package/dist/{tapScrollCircle-CvWJKtbF.js → tapScrollCircle-DKoj17z6.js} +1 -1
- package/dist/{useSplitPersistence-BCitqdAe.cjs → useSplitPersistence-C6s7a4Iu.cjs} +1 -1
- package/dist/{useSplitPersistence-C86jW1yY.js → useSplitPersistence-CC9bx9iq.js} +1 -1
- package/package.json +3 -3
- package/dist/location-DFXJSMit.cjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("react/jsx-runtime"),c=require("react"),Y=require("./describeValue-Ccvhbt36.cjs"),j=require("./location-DFXJSMit.cjs"),P=require("./index-D6at9qMs.cjs"),re=require("./ExplorerSplit-DWBhCe7m.cjs"),D=require("@aiquants/drag-drop-panels"),fe=require("react-router"),ne=require("./storage-BpYsprog.cjs"),Ce=require("./ownUrls-BTPGNhBt.cjs"),qe=require("react-dom"),Be=require("@aiquants/markdown"),je=()=>{const e=new Map;return{hold:(n,t)=>{e.set(n,t),queueMicrotask(()=>{e.get(n)===t&&e.delete(n)})},take:n=>{const t=e.get(n);return e.delete(n),t===void 0?null:t}}},Oe=c.createContext(null),ie=()=>{const e=c.use(Oe);if(e===null)throw new Error("[markdown-explorer] multi-view panels must be rendered inside the multi-view stage");return e},Fe=(e,n)=>{const t=e.pendingHashes.get(n);return t===void 0?null:t},Ve=0xcbf29ce484222325n,Ue=0x100000001b3n,$e=(1n<<64n)-1n,Ge=(1n<<53n)-1n,Ye=new TextEncoder,We=e=>{let n=Ve;for(const t of Ye.encode(e))n=(n^BigInt(t))*Ue&$e;return Number(n&Ge)},Q=256,Ke=e=>`aqmx-p-${We(e).toString(36)}`,be=(e,n)=>{const t=Ke(e);let o=t;for(let r=2;n.has(o);r+=1)o=`${t}-${String(r)}`;return o},Je=new Map,Xe=(e,n=Je)=>{const t=new Set(e.flatMap(r=>n.get(r)??[])),o=new Map;for(const r of e){const s=n.get(r)??be(r,t);t.add(s),o.set(r,s)}return o},Pe=(e,n,t)=>{const o=e.columnOf.get(n);return o===void 0?void 0:Math.min(t-1,Math.max(0,o))},Te=(e,n)=>{const[t,...o]=j.columnGroups(n.logical,n.visible);if(t===void 0)throw new RangeError("[markdown-explorer] there must be at least one visible column");const r=([m,g])=>e.slice(m,g).reduce((i,v)=>i+v.length,0);let s=t;for(const m of o)r(m)<r(s)&&(s=m);let a=s[0];for(let m=s[0];m<s[1];m+=1)(e[m]?.length??0)<(e[a]?.length??0)&&(a=m);return a},ee=(e,n)=>{const t=Array.from({length:n.logical},()=>[]),o=[];for(const r of e.docs){const s=Pe(e,r,n.logical);s===void 0?o.push(r):t[s]?.push(r)}for(const r of o)t[Te(t,n)]?.push(r);return t},Ze=(e,n)=>j.columnGroups(e.length,n).map(([t,o])=>e.slice(t,o).flat()),Qe=(e,n,t)=>{const[o,r]=n,s=r-o,a=e.length,m=Array.from({length:s},(y,d)=>{const x=[0];for(const h of e)x.push((x.at(-1)??0)+(t(h)===o+d?1:0));return x}),g=(y,d,x)=>(m[y]?.[x]??0)-(m[y]?.[d]??0),i=Array.from({length:s+1},()=>Array.from({length:a+1},()=>Number.NEGATIVE_INFINITY)),v=Array.from({length:s+1},()=>Array.from({length:a+1},()=>0)),C=i[0];C&&(C[0]=0);for(let y=0;y<s;y+=1)for(let d=0;d<=a;d+=1)for(let x=0;x<=d;x+=1){const h=(i[y]?.[x]??Number.NEGATIVE_INFINITY)+g(y,x,d),O=i[y+1],L=v[y+1];O&&L&&h>(O[d]??Number.NEGATIVE_INFINITY)&&(O[d]=h,L[d]=x)}const T=Array.from({length:s},()=>[]);let A=a;for(let y=s;y>0;y-=1){const d=v[y]?.[A]??0;T[y-1]=e.slice(d,A),A=d}return T},Le=(e,n)=>{const t=n.flat(),o=new Map(e.columnOf);for(const[r,s]of n.entries())for(const a of s)o.delete(a),o.set(a,r);for(const r of o.keys()){if(o.size<=Q)break;o.delete(r)}return{docs:t,columnOf:o}},en=(e,n,t,o)=>{if(e.docs.includes(n))return{state:e,outcome:"existing"};if(e.docs.length>=o)return{state:e,outcome:"rejected"};const r=ee(e,t),s=Pe(e,n,t.logical)??Te(r,t);r[s]?.push(n);const a=new Map(e.panelIds);return a.set(n,be(n,new Set(a.values()))),{state:{...e,...Le(e,r),panelIds:a},outcome:"opened"}},Me=(e,n)=>{if(!e.docs.includes(n))return e;const t=new Set(e.hidden);t.delete(n);const o=new Set(e.markup);o.delete(n);const r=new Map(e.panelIds);return r.delete(n),{...e,docs:e.docs.filter(s=>s!==n),hidden:t,markup:o,panelIds:r,maximized:e.maximized===n?null:e.maximized}},nn=(e,n,t,o)=>{if(e.hidden.has(n))return{state:ke(e,n,!1),outcome:"shown"};if(e.docs.includes(n))return{state:Me(e,n),outcome:"closed"};const r=en(e,n,t,o);return{state:r.state,outcome:r.outcome==="rejected"?"rejected":"opened"}},tn=(e,n,t)=>{if(n===t||!e.docs.includes(n))return{state:e,outcome:"ignored"};if(e.docs.includes(t))return{state:e,outcome:"existing"};const o=new Map(e.columnOf),r=o.get(n);r!==void 0&&(o.delete(t),o.set(t,r));const s=new Set(e.hidden);s.delete(n);const a=new Map(e.panelIds),m=a.get(n);if(m===void 0)throw new Error(`[markdown-explorer] the open document ${Y.describeValue(n)} has no panel id`);a.delete(n),a.set(t,m);const g=new Set(e.markup);return g.delete(n),{state:{docs:e.docs.map(i=>i===n?t:i),maximized:e.maximized===n?t:e.maximized,columnOf:o,hidden:s,markup:g,panelIds:a},outcome:"navigated"}},ke=(e,n,t)=>{if(!e.docs.includes(n)||e.hidden.has(n)===t)return e;const o=new Set(e.hidden);return t?o.add(n):o.delete(n),{...e,hidden:o,maximized:t&&e.maximized===n?null:e.maximized}},on=(e,n,t)=>{if(!e.docs.includes(n)||e.markup.has(n)===t)return e;const o=new Set(e.markup);return t?o.add(n):o.delete(n),{...e,markup:o}},rn=(e,n)=>{if(e.maximized===n||n!==null&&!e.docs.includes(n))return e;if(n===null||!e.hidden.has(n))return{...e,maximized:n};const t=new Set(e.hidden);return t.delete(n),{...e,maximized:n,hidden:t}},sn=(e,n,t)=>{const o=ee(e,t),r=new Map;for(const[i,v]of o.entries())for(const C of v)r.set(C,i);const s=new Set(e.docs),a=new Set,m=j.columnGroups(t.logical,t.visible),g=Array.from({length:t.logical},()=>[]);for(const[i,v]of m.entries()){const C=(n[i]??[]).filter(T=>s.has(T)&&!a.has(T));for(const T of C)a.add(T);for(const[T,A]of Qe(C,v,y=>r.get(y)).entries())g[v[0]+T]?.push(...A)}for(const i of e.docs)a.has(i)||g[r.get(i)??0]?.push(i);return g.every((i,v)=>i.length===o[v]?.length&&i.every((C,T)=>o[v]?.[T]===C))?e:{...e,...Le(e,g)}},te=(e,n)=>{const t=[...new Set(e.docs)].slice(0,n),o=new Set(t),r=e.maximized!==null&&o.has(e.maximized)?e.maximized:null;return{docs:t,maximized:r,columnOf:e.stored.columnOf,hidden:new Set([...e.stored.hidden].filter(s=>o.has(s)&&s!==r)),markup:new Set(e.markup.filter(s=>o.has(s))),panelIds:Xe(t,e.panelIds)}},pe=(e,n)=>{if(e.docs.every(o=>e.columnOf.has(o)))return e;const t=new Map(e.columnOf);for(const[o,r]of ee(e,n).entries())for(const s of r)t.delete(s),t.set(s,o);for(const o of t.keys()){if(t.size<=Q)break;t.delete(o)}return{...e,columnOf:t}},Re=1,U=Object.freeze({columnOf:new Map,hidden:new Set}),ln=(e,n)=>{if(e===null||e==="")return U;let t;try{t=JSON.parse(e)}catch{return U}if(t===null||typeof t!="object"||Array.isArray(t))return U;const o=t;if(o.v!==Re)return U;const r=new Map;if(Array.isArray(o.columnOf))for(const a of o.columnOf.slice(-Q))Array.isArray(a)&&a.length===2&&typeof a[0]=="string"&&a[0]!==""&&Number.isInteger(a[1])&&a[1]>=0&&a[1]<n&&(r.delete(a[0]),r.set(a[0],a[1]));const s=new Set(Array.isArray(o.hidden)?o.hidden.filter(a=>typeof a=="string"&&a!==""):[]);return{columnOf:r,hidden:s}},an=e=>JSON.stringify({v:Re,columnOf:[...e.columnOf.entries()].slice(-Q),hidden:e.docs.filter(n=>e.hidden.has(n))}),ae=(e,n)=>{const t=e.get(n);return t===void 0?Ce.lastPathSegment(n):t},W=e=>{const n=new Map;for(const[t,o]of e.panelIds)n.set(o,t);return n},ge=e=>{if(!Ce.isAcceptableDocumentPath(e))throw new RangeError(`[markdown-explorer] not an acceptable document path: ${Y.describeValue(e)}`)},cn=({config:e,location:n,writeUrl:t,persist:o})=>{const{maxPanels:r,columns:s}=e.multiView,a=P.createEmitter(),m=new Map,g=new Map;let i={layout:te({docs:n.docs,maximized:n.maximized,markup:n.markup,stored:U},r),source:n.source,visibleColumns:s,ready:!1,splitDragging:!1,titles:new Map,pendingHashes:new Map},v=!1;const C=l=>v?pe(l,{logical:s,visible:i.visibleColumns}):l,T=(l,S)=>j.explorerHref(e,{view:"multi",source:l,docs:S.docs,maximized:S.maximized,markup:S.markup}),A=l=>({docs:l.docs,maximized:l.maximized,markup:[...l.markup]});let y=T(n.source,n),d=n.source,x=y;const h=[],O=[];let L=null;const N=()=>{if(!(h.length>0))for(const l of O.splice(0))l()},R=l=>{i={...i,...l},a.emit()},u=()=>{if(!i.ready)return;const l=an(i.layout);l!==L&&(L=l,o(l))},p=(l,S,b)=>{const I=T(l,A(S));I!==y&&(y=I,d=l,h.push(I),t(I,b))},f=l=>{const S=new Set(l.panelIds.values());for(const E of[...m.keys()])S.has(E)||m.delete(E);for(const E of[...g.keys()])S.has(E)||g.delete(E);const b=new Set(l.docs),I=[...i.titles.keys()].every(E=>b.has(E))?i.titles:new Map([...i.titles].filter(([E])=>b.has(E))),w=[...i.pendingHashes.keys()].every(E=>S.has(E))?i.pendingHashes:new Map([...i.pendingHashes].filter(([E])=>S.has(E)));return{titles:I,pendingHashes:w}},M=l=>l===i.layout?!1:(R({layout:l,...f(l)}),p(d,l,"replace"),u(),!0),_=()=>({logical:s,visible:i.visibleColumns});return{getSnapshot:()=>i,subscribe:a.subscribe,toggle:l=>{ge(l);const{state:S,outcome:b}=nn(i.layout,l,_(),r);return M(S),b},close:l=>M(Me(i.layout,l)),navigate:(l,S)=>{ge(S);const{state:b,outcome:I}=tn(i.layout,l,S);if(I!=="navigated")return I;const w=b.panelIds.get(S);return w!==void 0&&(m.delete(w),g.delete(w)),M(b),I},setHidden:(l,S)=>M(ke(i.layout,l,S)),maximize:l=>M(rn(i.layout,l)),setMarkup:(l,S)=>M(on(i.layout,l,S)),arrange:l=>M(sn(i.layout,l,{logical:s,visible:l.length})),changeSource:l=>{p(l,i.layout,"push")},revealSource:l=>{p(l,i.layout,"replace")},observeLocation:l=>{const S=T(l.source,l);if(S===y)return h.length=0,x=S,l.source!==i.source&&R({source:l.source}),N(),!1;if(S===x)return!1;x=S;const b=h.indexOf(S);if(b>=0)return h.splice(0,b+1),l.source!==i.source&&R({source:l.source}),N(),!1;h.length=0,y=S,d=l.source;const I=C(te({docs:l.docs,maximized:l.maximized,markup:l.markup,stored:{columnOf:i.layout.columnOf,hidden:i.layout.hidden},panelIds:i.layout.panelIds},r));return R({layout:I,source:l.source,...f(I)}),u(),N(),!0},whenUrlRendered:l=>{O.push(l),N()},loadStored:l=>{R({layout:C(te({docs:i.layout.docs,maximized:i.layout.maximized,markup:[...i.layout.markup],stored:l,panelIds:i.layout.panelIds},r)),ready:!0}),u()},setVisibleColumns:l=>{if(!Number.isInteger(l)||l<1||l>s)throw new RangeError(`[markdown-explorer] visible columns must be an integer in 1..${String(s)}; got ${Y.describeValue(l)}`);v=!0;const S=pe(i.layout,{logical:s,visible:l});l===i.visibleColumns&&S===i.layout||(R({visibleColumns:l,layout:S}),S!==i.layout&&u())},setSplitDragging:l=>{l!==i.splitDragging&&R({splitDragging:l})},setTitle:(l,S)=>{!i.layout.docs.includes(l)||i.titles.get(l)===S||R({titles:new Map(i.titles).set(l,S)})},titleOf:l=>ae(i.titles,l),setPendingHash:(l,S)=>{const b=i.pendingHashes.get(l);if(S===null||S===""){if(b===void 0)return;const I=new Map(i.pendingHashes);I.delete(l),R({pendingHashes:I});return}b!==S&&R({pendingHashes:new Map(i.pendingHashes).set(l,S)})},saveReadingPosition:(l,S,b)=>{i.layout.panelIds.get(S)===l&&m.set(l,{doc:S,position:b})},readingPositionOf:(l,S)=>{const b=m.get(l);return b===void 0||b.doc!==S?null:b.position},saveImageView:(l,S,b)=>{g.set(l,{url:S,state:b})},imageViewOf:(l,S)=>{const b=g.get(l);return b===void 0||b.url!==S?null:b.state}}},z=(e,n)=>{const t=()=>n(e.getSnapshot());return c.useSyncExternalStore(e.subscribe,t,t)},un=e=>{const{config:n,storageNamespace:t}=P.useExplorer(),o=fe.useNavigate(),r=c.useRef(o),s=ne.storageKeys(t).multiLayout,[a]=c.useState(()=>cn({config:n,location:e,writeUrl:(i,v)=>{r.current(i,P.explorerNavigationOptions(v==="replace"?"browse":"switch-source"))},persist:i=>ne.writeStorage(s,i)}));c.useLayoutEffect(()=>{r.current=o},[o]);const m=fe.useLocation(),g=c.useMemo(()=>({location:e,navigated:m}),[e,m]);return c.useLayoutEffect(()=>{a.observeLocation(g.location)},[a,g]),c.useLayoutEffect(()=>{a.loadStored(ln(ne.readStorage(s),n.multiView.columns))},[a,s,n]),a},dn=e=>{const n=e.closest(D.SCROLL_AREA_SELECTOR);if(n===null)throw new Error("[markdown-explorer] a panel's document region is not inside the panel's scroll area");return n},mn=({docPath:e,panelId:n,maximized:t,title:o,onContentShown:r})=>{const{store:s,followLink:a,revealInPanel:m,keepAtStartInPanel:g}=ie(),{announcer:i}=P.useExplorer(),v=z(s,u=>Fe(u,n)),C=z(s,u=>u.layout.markup.has(e)),T=c.useCallback((u,p)=>a(n,e,u,p),[a,n,e]),A=c.useCallback(()=>s.setPendingHash(n,null),[s,n]),y=c.useMemo(()=>({read:u=>s.imageViewOf(n,u),save:(u,p)=>s.saveImageView(n,u,p)}),[s,n]),d=c.useCallback((u,p)=>{p.kind!=="failure"&&s.setTitle(u,p.name),r(u)},[s,r]),x=c.useCallback(u=>{s.whenUrlRendered(()=>i.announce(u))},[s,i]),h=c.useMemo(()=>({scrollerOf:dn,reveal:u=>m(n,u),keepAtStart:(u,p)=>g(n,u,p)}),[m,g,n]),O=c.useMemo(()=>({kind:"panel",maximized:t,onDocumentLink:T,pendingHash:v,onHashConsumed:A,announceFailure:x,paneScroll:h}),[t,T,v,A,x,h]),L=c.useMemo(()=>({kind:"panel",documentName:o,maximized:t}),[o,t]),N=c.useCallback(()=>s.setMarkup(e,!s.getSnapshot().layout.markup.has(e)),[s,e]),R=c.useMemo(()=>({shown:C,toggle:N}),[C,N]);return k.jsxs(P.ImageViewMemoryContext,{value:y,children:[k.jsx(P.DocumentRefreshBar,{path:e,placement:L,markup:R,maximize:null}),k.jsx(P.DocumentPane,{path:e,absence:P.NO_DOCUMENT,markup:C,variant:O,onDocumentShown:d})]})},he=()=>typeof HTMLElement<"u"&&typeof HTMLElement.prototype.showPopover=="function"&&typeof HTMLElement.prototype.hidePopover=="function",ce="data-aqmx-column-probe",J="data-panel-id",se="--aqmx-multi-panel-chrome",fn=e=>e==="normal"?0:P.cssPixels(e),pn=(e,n)=>{const t=e.querySelector(D.SCROLL_ROOT_SELECTOR)?.firstElementChild,o=e.querySelector(`[${ce}]`),r=o instanceof HTMLElement?o.getBoundingClientRect().width:Number.NaN;if(!(t instanceof HTMLElement))return{plan:{trackInlineSize:Number.NaN,gap:Number.NaN,minColumnInlineSize:r,logicalColumns:n},stageBlockSize:Number.NaN};const s=getComputedStyle(t),a=t.clientWidth-P.cssPixels(s.paddingLeft)-P.cssPixels(s.paddingRight),m=t.clientHeight-P.cssPixels(s.paddingTop)-P.cssPixels(s.paddingBottom);return{plan:{trackInlineSize:a,gap:fn(s.columnGap),minColumnInlineSize:r,logicalColumns:n},stageBlockSize:m}},gn=(e,n)=>{if(e.getClientRects().length===0)return Number.NaN;const t=getComputedStyle(e);return n.getBoundingClientRect().top-e.getBoundingClientRect().top+P.cssPixels(t.paddingBottom)+P.cssPixels(t.borderBottomWidth)},X="data-aqmx-panel-frame",Se="--aqmx-multi-panel-pinned-block-size",hn=e=>{const{docPath:n,panelId:t}=e;if(typeof n!="string"||typeof t!="string")throw new TypeError("[markdown-explorer] a multi-view panel needs string docPath and panelId props");return{docPath:n,panelId:t}},Sn=e=>{const n=getComputedStyle(e),t=Number.parseFloat(n.lineHeight);return Number.isFinite(t)?t:Number.parseFloat(n.fontSize)},xn=(e,n,t)=>e.deltaMode===WheelEvent.DOM_DELTA_PAGE?e.deltaY*n.clientHeight:e.deltaMode!==WheelEvent.DOM_DELTA_LINE?e.deltaY:e.deltaY*t(n),$=e=>{const n=e.closest(D.SCROLL_AREA_SELECTOR);return n instanceof HTMLElement?n:null},Ne=e=>{const n=e.firstElementChild;return n instanceof HTMLElement&&getComputedStyle(n).position==="sticky"?n:null},Ae=(e,n)=>{const t=n.getBoundingClientRect().top,o=Ne(e);return o===null?t:Math.max(t,o.getBoundingClientRect().bottom)},xe=(e,n)=>{let t=0,o=e.length;for(;t<o;){const r=t+o>>>1;(e[r]?.getBoundingClientRect().bottom??Number.NEGATIVE_INFINITY)>n?o=r:t=r+1}return t<e.length?t:-1},yn=(e,n)=>{const t=Ae(e,n),o=[];let r=e;for(let a=xe([...r.children],t);a>=0;a=xe([...r.children],t)){const m=r.children[a];if(m===void 0)break;o.push(a),r=m}const s=r.getBoundingClientRect();return{scrollTop:n.scrollTop,anchor:o.length===0?null:{path:o,offset:s.top-t,height:s.height}}},ye=(e,n,t)=>{if(n.scrollTop=t.scrollTop,t.anchor===null)return;let o=e;for(const g of t.anchor.path)o=o?.children[g];if(o===void 0)return;const r=o.getBoundingClientRect(),{offset:s,height:a}=t.anchor,m=s<0&&a>0?s/a*r.height:s;n.scrollTop+=r.top-Ae(e,n)-m},vn=Object.freeze(["data-testid","aria-label","title","href","id","name"]),Ie=e=>{const n=e.getAttribute(D.PANEL_ACTION_ATTRIBUTE);return JSON.stringify(n===null?[e.tagName,...vn.map(t=>e.getAttribute(t))]:[e.tagName,D.PANEL_ACTION_ATTRIBUTE,n])},wn=(e,n)=>{if(n===null||!e.contains(n))return null;const t=[];for(let o=n;o!==e;){const r=o.parentElement;if(r===null)return null;t.unshift([...r.children].indexOf(o)),o=r}return{path:t,signature:Ie(n)}},En=(e,n,t)=>{let o=e;for(const r of t.path)o=o?.children[r];o instanceof HTMLElement&&Ie(o)===t.signature&&P.focusWithoutScroll(o)||n.focus({preventScroll:!0})},Cn=(e,n,t)=>{if(e.shiftKey||Math.abs(e.deltaX)>Math.abs(e.deltaY))return;const o=e.ctrlKey||e.metaKey,r=o?$(n):n.closest(D.SCROLL_ROOT_SELECTOR);if(!(r instanceof HTMLElement))return;const s=xn(e,r,t);(o||On(r,s))&&(e.preventDefault(),r.scrollTop+=s)},On=(e,n)=>n<0?e.scrollTop>0:n>0?Math.ceil(e.scrollTop+e.clientHeight)<e.scrollHeight:!1,bn=e=>e.scrollHeight>e.clientHeight,Pn=(e,n,t)=>{let o=Number.NaN,r=Number.NaN;const s=Ne(t),a=()=>{const i=gn(e,n);if(!Number.isFinite(i))return;const v=s===null?0:s.getBoundingClientRect().height;v!==r&&(r=v,t.style.setProperty(Se,`${String(v)}px`));const C=i+v;C!==o&&(o=C,e.style.setProperty(se,`${String(C)}px`))};a();let m=null;const g=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>{m===null&&(m=requestAnimationFrame(()=>{m=null,a()}))});return g?.observe(e),g?.observe(n),s!==null&&g?.observe(s),()=>{g?.disconnect(),m!==null&&cancelAnimationFrame(m),e.style.removeProperty(se),t.style.removeProperty(Se)}},Tn=e=>{const{docPath:n,panelId:t}=hn(e),{store:o,Body:r,maximize:s,focusCarry:a}=ie(),m=z(o,d=>d.layout.maximized===n),g=z(o,d=>ae(d.titles,n)),i=c.useRef(null),v=c.useRef(null),C=c.useRef(null),T=c.useRef(null);c.useEffect(()=>{const d=i.current,x=d===null?null:$(d);if(d===null||x===null||m)return;const h=new Map,O=p=>{const f=h.get(p);if(f!==void 0)return f;const M=Sn(p);return h.set(p,M),M},L=p=>Cn(p,d,O);let N=!1;const R=()=>{const p=bn(x);p!==N&&(N=p,p?d.addEventListener("wheel",L,{capture:!0,passive:!1}):d.removeEventListener("wheel",L,{capture:!0}))};R();const u=typeof ResizeObserver>"u"?null:new ResizeObserver(R);return u?.observe(x),u?.observe(d),()=>{u?.disconnect(),d.removeEventListener("wheel",L,{capture:!0})}},[m]),c.useLayoutEffect(()=>{const d=i.current,x=d===null?null:$(d),h=d===null?null:d.closest(`[${J}]`);if(!(d===null||x===null||!(h instanceof HTMLElement)))return Pn(h,x,d)},[]),c.useLayoutEffect(()=>{const d=i.current,x=d===null?null:$(d);if(d===null||x===null)return;const h=p=>{ye(d,x,p),T.current=x.scrollTop},O=o.readingPositionOf(t,n);v.current=O===null?null:{doc:n,position:O},O!==null&&h(O);let L=null,N=d.getBoundingClientRect().width;const R=()=>{L===null&&(L=requestAnimationFrame(()=>{L=null;const p=T.current;if(T.current=null,p!==null&&x.scrollTop===p||d.getBoundingClientRect().width!==N)return;const f=C.current;f!==null&&o.saveReadingPosition(t,f,yn(d,x))}))};x.addEventListener("scroll",R,{passive:!0});const u=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>{const p=d.getBoundingClientRect().width;if(p===N)return;N=p;const f=o.readingPositionOf(t,n);f!==null&&h(f)});return u?.observe(d),()=>{x.removeEventListener("scroll",R),u?.disconnect(),L!==null&&cancelAnimationFrame(L)}},[o,t,n]),c.useLayoutEffect(()=>{const d=i.current,x=d===null?null:d.closest(`[${J}]`);if(d===null||x===null)return;const h=a.take(t);return h!==null&&En(x,d,h),()=>{const O=wn(x,x.ownerDocument.activeElement);O!==null&&a.hold(t,O)}},[a,t]);const A=c.useCallback(d=>{const x=i.current,h=x===null?null:$(x);if(x===null||h===null)return;const O=C.current;C.current=d;const L=v.current;v.current=null,L!==null&&L.doc===d?(ye(x,h,L.position),T.current=h.scrollTop):O!==null&&O!==d&&(h.scrollTop=0)},[]),y=c.useCallback(d=>{P.isInFullscreenBlock(d.target)||s(n)},[s,n]);return k.jsx("div",{ref:i,role:"group","aria-label":g,className:"aqmx-multi-panel-frame",tabIndex:-1,"data-aqmx-panel-frame":t,"data-aqmx-maximized":m?"true":"false","data-testid":"markdown-explorer-panel-frame",...m?P.CONTENT_PANE:{},onDoubleClick:m?void 0:y,children:k.jsx(r,{docPath:n,panelId:t,maximized:m,title:g,onContentShown:A})})},Ln=c.memo(Tn),K=(e,n)=>{const t=e.panelIds.get(n);if(t===void 0)throw new Error(`[markdown-explorer] the open document ${Y.describeValue(n)} has no panel id`);return t},ve=e=>Object.fromEntries(D.generateColumnIds(e).map(n=>[n,[]])),Mn=(e,n)=>{const t=Ze(ee(e,n),n.visible);return Object.fromEntries(t.map((o,r)=>[D.generateColumnId(r),o.map(s=>K(e,s))]))},kn=(e,n)=>{const t=W(e);return D.sortColumnIds(Object.keys(n)).map(o=>(n[o]??[]).flatMap(r=>{const s=t.get(r);return s===void 0?[]:[s]}))},Rn=e=>({switchToCustomDragMode:e.panelSwitchToCustomDrag,switchToNormalDragMode:e.panelSwitchToNormalDrag,hidePanel:e.panelHide,maximizePanel:e.panelMaximize,restorePanel:e.panelRestore,closePanel:e.panelClose,movePanel:e.panelMove,movePanelToPreviousColumn:e.panelMovePreviousColumn,movePanelToNextColumn:e.panelMoveNextColumn,movePanelUp:e.panelMoveUp,movePanelDown:e.panelMoveDown,morePanelActions:e.panelMoreActions,customDragModeBadge:e.panelCustomDragBadge,panelMoved:e.panelMoved,panelMoveUnavailable:e.panelMoveUnavailable,panelDragStarted:e.panelDragStarted,panelDragCancelled:e.panelDragCancelled,hiddenPanels:e.hiddenPanelsTitle,hiddenPanelBadge:e.hiddenPanelBadge,hiddenPanelNotice:e.hiddenPanelNotice,emptyColumn:e.multiColumnEmpty,dropZone:e.multiColumnRegion,dropHere:e.panelDropHere}),Nn="--aqmx-multi-stage-bar-gutter",An=Object.freeze({[Nn]:`${String(P.NATIVE_SCROLL_BAR_WIDTH)}px`}),In=Object.freeze({blockSize:"100%",paddingInlineEnd:P.TAP_SCROLL_CIRCLE_GUTTER_LENGTH}),_n=Object.freeze({[D.NO_PANEL_DRAG_ATTRIBUTE]:"",style:Object.freeze({display:"flex"})}),Dn=e=>k.jsx("div",{..._n,children:k.jsx(P.LazyNativeScrollBar,{scroller:e,kind:"content"})}),zn=({props:e,children:n})=>k.jsx(Be.HostedScrollArea,{scrollerProps:{...e,style:In},renderScrollBar:Dn,barInlineSize:P.NATIVE_SCROLL_BAR_SLOT_LENGTH,children:n}),Hn=e=>k.jsx(P.LazyNativeScrollBar,{scroller:e,kind:"stage"}),ue="--aqmx-stage-block",qn="--aqmx-multi-panel-body-floor",Bn=`calc(var(${ue}) * ${String(j.PANEL_MIN_BLOCK_RATIO)})`,jn=`max(calc(var(${ue}) * ${String(j.PANEL_MAX_BLOCK_RATIO)}), calc(var(${se}) + var(${qn})))`,Fn=(e,n)=>{const t=Object.entries(e);return t.length!==Object.keys(n).length?!1:t.every(([o,r])=>{const s=n[o];return s!==void 0&&s.length===r.length&&s.every((a,m)=>r[m]===a)})},G=(e,n,t,o)=>{P.stopKeepingInView(e);const r=e.querySelector(`[${J}="${n}"]`);if(!(r instanceof HTMLElement))return;const s=t!==null&&r.contains(t)?t:null,a=[{element:r,boundary:r.closest(D.SCROLL_ROOT_SELECTOR)}];s!==null&&a.push({element:s,boundary:r}),P.keepInView(e,()=>r.isConnected?(r.scrollIntoView(P.NEAREST),s?.isConnected!==!0?r:(o(s),s)):null,a)},Z=e=>{e.scrollIntoView(P.NEAREST)},_e=(e,n)=>{const t=e.querySelector(`[${X}="${n}"]`);return t instanceof HTMLElement?(G(e,n,null,Z),t.focus({preventScroll:!0}),!0):!1},de=(e,n)=>{const t=e.querySelector(`[${J}="${n}"]`);return t instanceof HTMLElement&&t.contains(e.ownerDocument.activeElement)},we=(e,n)=>{if(!de(e,n))return null;const t=[...e.querySelectorAll(`[${X}]`)].map(a=>a.getAttribute(X)),o=t.indexOf(n),r=t[o+1];if(o>=0&&typeof r=="string")return{kind:"panel",panelId:r};const s=t[o-1];return o>0&&typeof s=="string"?{kind:"panel",panelId:s}:{kind:"stage"}},Ee=(e,n)=>{requestAnimationFrame(()=>{const t=e.current;t!==null&&(n.kind==="panel"&&_e(t,n.panelId)||t.focus({preventScroll:!0}))})},De=(e,n)=>{requestAnimationFrame(()=>{const t=e.current;t!==null&&_e(t,n)})},Vn=(e,n,t)=>{requestAnimationFrame(()=>{const o=e.current;if(o===null)return;const{activeElement:r,body:s}=o.ownerDocument;if(G(o,n,t&&de(o,n)?r:null,Z),!t||r!==null&&r!==s&&r.isConnected)return;const a=o.querySelector(`[${X}="${n}"]`);a instanceof HTMLElement&&a.focus({preventScroll:!0})})},Un=({store:e,stageRef:n})=>{const{config:t,labels:o,announcer:r,edits:s}=P.useExplorer(),{maximize:a}=ie(),m=t.multiView.columns,g=z(e,w=>w.layout),i=z(e,w=>w.visibleColumns),v=z(e,w=>w.titles),C=z(e,w=>w.layout.maximized!==null||w.splitDragging),[T,A]=c.useState(!1),[y]=c.useState(()=>ve(i)),d=c.useMemo(()=>Rn(o),[o]),x=c.useCallback(w=>{e.arrange(kn(e.getSnapshot().layout,w))},[e]),h=D.useDragDropColumns({initialColumnPanels:y,initialPanelVisibility:{},debugConfig:D.DEFAULT_DEBUG_CONFIG,onColumnPanelsChange:x}),{columnPanels:O,setColumnPanels:L}=h,N=c.useRef(C),R=c.useRef(O);c.useLayoutEffect(()=>{N.current=C,R.current=O},[C,O]);const u=c.useCallback(w=>{const E=n.current;if(E===null)return;const{plan:B,stageBlockSize:H}=pn(E,m);if(Number.isFinite(H)&&H>0&&E.style.setProperty(ue,`${String(H)}px`),N.current&&!w)return;const q=j.replanVisibleColumns(e.getSnapshot().visibleColumns,B);q!==null&&e.setVisibleColumns(q)},[e,n,m]);c.useLayoutEffect(()=>{u(!0),A(!0)},[u]),c.useEffect(()=>{const w=n.current;if(w===null||typeof ResizeObserver>"u")return;let E=null;const B=new ResizeObserver(()=>{E===null&&(E=requestAnimationFrame(()=>{E=null,u(!1)}))}),H=w.querySelector(D.SCROLL_ROOT_SELECTOR)?.firstElementChild,q=w.querySelector(`[${ce}]`);return H instanceof Element&&B.observe(H),q instanceof Element&&B.observe(q),()=>{B.disconnect(),E!==null&&cancelAnimationFrame(E)}},[n,u]),c.useEffect(()=>{C||u(!1)},[C,u]);const p=c.useMemo(()=>T?Mn(g,{logical:m,visible:i}):ve(i),[T,g,m,i]);c.useLayoutEffect(()=>{Fn(R.current,p)||L(p)},[p,L]);const f=c.useMemo(()=>D.sortColumnIds(Object.keys(O)).map(w=>({id:w,key:w,className:"aqmx-multi-column"})),[O]),M=c.useMemo(()=>g.docs.map(w=>{const E=K(g,w);return{id:E,component:Ln,title:ae(v,w),props:{docPath:w,panelId:E},minHeight:Bn,maxHeight:jn}}),[g,v]),_=c.useMemo(()=>Object.fromEntries(g.docs.map(w=>[K(g,w),!g.hidden.has(w)])),[g]),l=g.maximized===null?null:K(g,g.maximized),S=c.useCallback(w=>{const{layout:E}=e.getSnapshot();for(const[B,H]of W(E)){const q=w[B];if(q===void 0||q!==E.hidden.has(H))continue;const F=e.titleOf(H);if(q){if(!e.setHidden(H,!1))continue;r.announce(o.panelShown(F)),De(n,B);continue}const V=n.current,me=V===null?null:we(V,B);e.setHidden(H,!0)&&(r.announce(o.panelHidden(F)),me!==null&&Ee(n,me))}},[e,n,r,o]),b=c.useCallback(w=>{const E=W(e.getSnapshot().layout).get(w);if(E===void 0)return;const B=()=>{const q=e.titleOf(E),F=n.current,V=F===null?null:we(F,w);e.close(E)&&(r.announce(o.panelClosed(q)),V!==null&&Ee(n,V))},H=s.unsavedAmong([E]);H.length===0?B():s.askToDiscard(H).then(q=>{q&&B()})},[e,n,r,o,s]),I=c.useCallback(w=>{if(w===null){a(null);return}const E=W(e.getSnapshot().layout).get(w);E!==void 0&&a(E)},[e,a]);return k.jsx("div",{className:"aqmx-multi-layout","aria-busy":!T,children:k.jsx(D.DragDropLayout,{columns:f,panels:M,columnPanels:O,onColumnPanelsChange:x,panelVisibility:_,onPanelVisibilityChange:S,dragState:h.dragState,dragOverPosition:h.dragOverPosition,originalPanelPosition:h.originalPanelPosition,dragModes:h.dragModes,debugConfig:D.DEFAULT_DEBUG_CONFIG,panelSizes:h.panelSizes,customDrag:h.customDrag,setPanelRef:h.setPanelRef,onDragStart:h.handleDragStart,onDragEnd:h.handleDragEnd,onPlaceholderDragEnter:h.handlePlaceholderDragEnter,onPlaceholderDragLeave:h.handlePlaceholderDragLeave,onDragOverWithInsert:h.handleDragOverWithInsert,onDropWithInsert:h.handleDropWithInsert,onColumnDragLeave:h.handleColumnDragLeave,onPanelMouseDown:h.handleMouseDown,onPanelSizeInfoClick:h.handlePanelSizeInfoClick,onToggleDragMode:h.toggleDragMode,onPanelClose:b,onPanelMaximizeChange:I,maximizedPanel:l,dragHandle:"header",labels:d,panelClassName:"aqmx-multi-panel",renderPanelScrollArea:zn,renderStageScrollBar:Hn})})},oe={blockStart:"--aqmx-multi-toast-block-start",inlineEnd:"--aqmx-multi-toast-inline-end",room:"--aqmx-multi-toast-room"},$n=(e,n)=>{const t=n.getBoundingClientRect(),o=[t.left+1,t.left+t.width/2,t.right-1],r=[t.top+1,t.top+t.height/2,t.bottom-1];return o.some(s=>r.some(a=>{const m=n.ownerDocument.elementsFromPoint(s,a),g=m.findIndex(v=>n.contains(v)),i=m.findIndex(v=>e.contains(v));return g!==-1&&i!==-1&&i<g}))},Gn=(e,n)=>{const t=n.getBoundingClientRect(),o=n.ownerDocument.documentElement.clientWidth,r=getComputedStyle(n).direction==="rtl";return e.style.setProperty(oe.blockStart,`${String(t.top)}px`),e.style.setProperty(oe.inlineEnd,`${String(r?t.left:o-t.right)}px`),e.style.setProperty(oe.room,`${String(t.width)}px`),e.showPopover(),()=>{e.isConnected&&e.hidePopover()}},Yn=({store:e,body:n,limitNotice:t,onLimitNoticeCovered:o,ref:r})=>{const{config:s,labels:a,announcer:m,edits:g}=P.useExplorer(),i=c.useRef(null),v=c.useRef(null),C=z(e,u=>u.ready),T=z(e,u=>u.layout.docs.length>0),A=z(e,u=>u.visibleColumns),y=c.use(re.SheetNoticeSlotContext),d=c.useCallback(u=>{const{layout:p}=e.getSnapshot(),f=p.maximized,M=u===null&&f!==null?p.panelIds.get(f):void 0,_=i.current,l=M!==void 0&&_!==null&&de(_,M);e.maximize(u)&&(u!==null?m.announce(a.panelMaximized(e.titleOf(u))):f!==null&&m.announce(a.panelRestored(e.titleOf(f))),M!==void 0&&Vn(i,M,l))},[e,m,a]),x=c.useCallback((u,p,f,M)=>{if(f===p){e.setPendingHash(u,M);return}const _=g.unsavedAmong([p]);if(_.length>0){g.askToDiscard(_).then(I=>{I&&x(u,p,f,M)});return}const l=e.navigate(p,f);if(l==="navigated"){e.setPendingHash(u,M);return}if(l!=="existing")return;const{layout:S}=e.getSnapshot(),b=S.panelIds.get(f);b!==void 0&&(m.announce(a.panelAlreadyOpen(e.titleOf(f))),S.maximized===null?e.setHidden(f,!1):d(f),e.setPendingHash(b,M),De(i,b))},[e,m,a,d,g]);c.useLayoutEffect(()=>{if(t===null||y!==null||!he())return;const u=v.current,p=i.current;if(u===null||p===null)throw new Error("[markdown-explorer] the panel-limit notice and the stage must be mounted together");return Gn(u,p)},[t,y]),c.useEffect(()=>{const u=v.current;if(t===null||u===null)return;const{ownerDocument:p}=u;let f=null;const M=_=>{const l=_.target;l instanceof Element&&(f!==null&&cancelAnimationFrame(f),f=requestAnimationFrame(()=>{f=null,p.activeElement===l&&u.isConnected&&$n(u,l)&&o()}))};return p.addEventListener("focusin",M,!0),()=>{p.removeEventListener("focusin",M,!0),f!==null&&cancelAnimationFrame(f)}},[t,y,o]),c.useImperativeHandle(r,()=>({bringIntoView:u=>{requestAnimationFrame(()=>{const p=i.current,f=e.getSnapshot().layout.panelIds.get(u);p!==null&&f!==void 0&&G(p,f,null,Z)})}}),[e]),c.useEffect(()=>{const u=i.current;return()=>{u!==null&&P.stopKeepingInView(u)}},[]);const h=c.useCallback((u,p)=>{const f=i.current;f!==null&&G(f,u,p,Z)},[]),O=c.useCallback((u,p,f)=>{const M=i.current;M!==null&&G(M,u,f,_=>P.alignToStart(p,_))},[]),[L]=c.useState(je),N=c.useMemo(()=>({store:e,Body:n,followLink:x,maximize:d,revealInPanel:h,keepAtStartInPanel:O,focusCarry:L}),[e,n,x,d,h,O,L]),R=c.useMemo(()=>Array.from({length:s.multiView.columns},(u,p)=>D.generateColumnId(p)),[s]);return k.jsxs("section",{ref:i,className:"aqmx-multi-stage",style:An,tabIndex:-1,"aria-label":a.multiRegion,"aria-busy":T&&!C,"data-testid":"markdown-explorer-stage","data-aqmx-visible-columns":A,...P.CONTENT_PANE,children:[k.jsx("span",{className:"aqmx-multi-probe","aria-hidden":"true",[ce]:""}),T?C?k.jsx(Oe,{value:N,children:k.jsx(Un,{store:e,stageRef:i})}):k.jsx("div",{className:"aqmx-multi-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-stage-skeleton",children:R.map(u=>k.jsxs("div",{className:"aqmx-skeleton aqmx-multi-skeleton-column",children:[k.jsx("span",{}),k.jsx("span",{}),k.jsx("span",{})]},u))}):k.jsx("div",{className:"aqmx-empty","data-testid":"markdown-explorer-multi-empty",children:k.jsx("p",{className:"aqmx-empty-title",children:a.multiEmpty})}),t===null?null:y!==null?qe.createPortal(k.jsx("div",{ref:v,className:"aqmx-toast aqmx-multi-toast","data-testid":"markdown-explorer-panel-limit",children:t}),y):k.jsx("div",{ref:v,popover:he()?"manual":void 0,className:"aqmx-toast aqmx-multi-toast","data-testid":"markdown-explorer-panel-limit",children:t})]})},ze=3e3,He=(e,n)=>{if(n!==null)return n;const[t]=e;return t===void 0?null:t},le=(e,n,t)=>{const o=new Set(e),r=n.filter(a=>!o.has(a)),s=r.length>0?r.at(-1):t!==null&&n.includes(t)?t:n.at(-1);return s===void 0?null:s},Wn=(e,n,t)=>{switch(n){case"opened":return e.panelOpened(t);case"shown":return e.panelShown(t);case"closed":return e.panelClosed(t);default:{const o=n;throw new RangeError(`[markdown-explorer] unknown toggle outcome ${Y.describeValue(o)}`)}}},Kn=({location:e})=>{const{config:n,labels:t,announcer:o}=P.useExplorer(),r=un(e),s=z(r,f=>f.layout.docs),a=z(r,f=>f.layout.maximized),m=z(r,f=>f.layout.markup),g=z(r,f=>f.source),[i,v]=c.useState(()=>({docs:s,latest:le([],s,null)}));i.docs!==s&&v({docs:s,latest:le(i.docs,s,i.latest)});const C=a!==null?a:i.latest,[T,A]=c.useState(!1),y=c.useRef(null),[d,x]=c.useState(0),h=c.useRef(null),O=c.useRef(null);c.useLayoutEffect(()=>{const f=h.current;h.current=null,f!==null&&(r.whenUrlRendered(()=>o.announce(f.announcement)),O.current?.bringIntoView(f.doc))}),c.useEffect(()=>()=>{y.current!==null&&clearTimeout(y.current)},[]);const L=c.useCallback(()=>{y.current!==null&&clearTimeout(y.current),A(!0),y.current=setTimeout(()=>{y.current=null,A(!1)},ze)},[]),N=c.useCallback(()=>{y.current!==null&&clearTimeout(y.current),y.current=null,A(!1)},[]),R=c.useCallback(f=>{const M=r.titleOf(f),_=r.toggle(f);_==="rejected"&&L();const l=_==="rejected"?t.panelLimit(n.multiView.maxPanels):Wn(t,_,M);if(_==="shown"){h.current={doc:f,announcement:l},x(S=>S+1);return}r.whenUrlRendered(()=>{o.announce(l),_==="opened"&&O.current?.bringIntoView(f)})},[r,L,o,t,n]),u=c.useMemo(()=>new Set(s),[s]),p=c.useMemo(()=>{const f=He(s,a);return{href:j.explorerHref(n,{view:"tree",source:g,doc:f,markup:f!==null&&m.has(f)}),target:"tree"}},[n,g,s,a,m]);return k.jsx(re.ExplorerSplit,{view:"multi",explorer:k.jsx(re.ExplorerPane,{mode:"multi",sourceId:g,currentPath:C,openPaths:u,onOpenDocument:R,onSourceChange:r.changeSource,onRevealSource:r.revealSource,viewSwitch:p}),content:k.jsx(Yn,{ref:O,store:r,body:mn,limitNotice:T?t.panelLimit(n.multiView.maxPanels):null,onLimitNoticeCovered:N}),contentCoversPage:a!==null,sheetDismissals:d,onDraggingChange:r.setSplitDragging})};exports.MultiLayout=Kn;exports.PANEL_LIMIT_NOTICE_MS=ze;exports.latestOpenedDocument=le;exports.treeSwitchDocument=He;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("react/jsx-runtime"),c=require("react"),Y=require("./describeValue-Ccvhbt36.cjs"),j=require("./location-Csj3eAm_.cjs"),P=require("./index-AfEbgYQI.cjs"),re=require("./ExplorerSplit-DnuuUifU.cjs"),D=require("@aiquants/drag-drop-panels"),fe=require("react-router"),ne=require("./storage-BpYsprog.cjs"),Ce=require("./ownUrls-BTPGNhBt.cjs"),qe=require("react-dom"),Be=require("@aiquants/markdown"),je=()=>{const e=new Map;return{hold:(n,t)=>{e.set(n,t),queueMicrotask(()=>{e.get(n)===t&&e.delete(n)})},take:n=>{const t=e.get(n);return e.delete(n),t===void 0?null:t}}},Oe=c.createContext(null),ie=()=>{const e=c.use(Oe);if(e===null)throw new Error("[markdown-explorer] multi-view panels must be rendered inside the multi-view stage");return e},Fe=(e,n)=>{const t=e.pendingHashes.get(n);return t===void 0?null:t},Ve=0xcbf29ce484222325n,Ue=0x100000001b3n,$e=(1n<<64n)-1n,Ge=(1n<<53n)-1n,Ye=new TextEncoder,We=e=>{let n=Ve;for(const t of Ye.encode(e))n=(n^BigInt(t))*Ue&$e;return Number(n&Ge)},Q=256,Ke=e=>`aqmx-p-${We(e).toString(36)}`,be=(e,n)=>{const t=Ke(e);let o=t;for(let r=2;n.has(o);r+=1)o=`${t}-${String(r)}`;return o},Je=new Map,Xe=(e,n=Je)=>{const t=new Set(e.flatMap(r=>n.get(r)??[])),o=new Map;for(const r of e){const s=n.get(r)??be(r,t);t.add(s),o.set(r,s)}return o},Pe=(e,n,t)=>{const o=e.columnOf.get(n);return o===void 0?void 0:Math.min(t-1,Math.max(0,o))},Te=(e,n)=>{const[t,...o]=j.columnGroups(n.logical,n.visible);if(t===void 0)throw new RangeError("[markdown-explorer] there must be at least one visible column");const r=([m,g])=>e.slice(m,g).reduce((i,v)=>i+v.length,0);let s=t;for(const m of o)r(m)<r(s)&&(s=m);let a=s[0];for(let m=s[0];m<s[1];m+=1)(e[m]?.length??0)<(e[a]?.length??0)&&(a=m);return a},ee=(e,n)=>{const t=Array.from({length:n.logical},()=>[]),o=[];for(const r of e.docs){const s=Pe(e,r,n.logical);s===void 0?o.push(r):t[s]?.push(r)}for(const r of o)t[Te(t,n)]?.push(r);return t},Ze=(e,n)=>j.columnGroups(e.length,n).map(([t,o])=>e.slice(t,o).flat()),Qe=(e,n,t)=>{const[o,r]=n,s=r-o,a=e.length,m=Array.from({length:s},(y,d)=>{const x=[0];for(const h of e)x.push((x.at(-1)??0)+(t(h)===o+d?1:0));return x}),g=(y,d,x)=>(m[y]?.[x]??0)-(m[y]?.[d]??0),i=Array.from({length:s+1},()=>Array.from({length:a+1},()=>Number.NEGATIVE_INFINITY)),v=Array.from({length:s+1},()=>Array.from({length:a+1},()=>0)),C=i[0];C&&(C[0]=0);for(let y=0;y<s;y+=1)for(let d=0;d<=a;d+=1)for(let x=0;x<=d;x+=1){const h=(i[y]?.[x]??Number.NEGATIVE_INFINITY)+g(y,x,d),O=i[y+1],L=v[y+1];O&&L&&h>(O[d]??Number.NEGATIVE_INFINITY)&&(O[d]=h,L[d]=x)}const T=Array.from({length:s},()=>[]);let A=a;for(let y=s;y>0;y-=1){const d=v[y]?.[A]??0;T[y-1]=e.slice(d,A),A=d}return T},Le=(e,n)=>{const t=n.flat(),o=new Map(e.columnOf);for(const[r,s]of n.entries())for(const a of s)o.delete(a),o.set(a,r);for(const r of o.keys()){if(o.size<=Q)break;o.delete(r)}return{docs:t,columnOf:o}},en=(e,n,t,o)=>{if(e.docs.includes(n))return{state:e,outcome:"existing"};if(e.docs.length>=o)return{state:e,outcome:"rejected"};const r=ee(e,t),s=Pe(e,n,t.logical)??Te(r,t);r[s]?.push(n);const a=new Map(e.panelIds);return a.set(n,be(n,new Set(a.values()))),{state:{...e,...Le(e,r),panelIds:a},outcome:"opened"}},Me=(e,n)=>{if(!e.docs.includes(n))return e;const t=new Set(e.hidden);t.delete(n);const o=new Set(e.markup);o.delete(n);const r=new Map(e.panelIds);return r.delete(n),{...e,docs:e.docs.filter(s=>s!==n),hidden:t,markup:o,panelIds:r,maximized:e.maximized===n?null:e.maximized}},nn=(e,n,t,o)=>{if(e.hidden.has(n))return{state:ke(e,n,!1),outcome:"shown"};if(e.docs.includes(n))return{state:Me(e,n),outcome:"closed"};const r=en(e,n,t,o);return{state:r.state,outcome:r.outcome==="rejected"?"rejected":"opened"}},tn=(e,n,t)=>{if(n===t||!e.docs.includes(n))return{state:e,outcome:"ignored"};if(e.docs.includes(t))return{state:e,outcome:"existing"};const o=new Map(e.columnOf),r=o.get(n);r!==void 0&&(o.delete(t),o.set(t,r));const s=new Set(e.hidden);s.delete(n);const a=new Map(e.panelIds),m=a.get(n);if(m===void 0)throw new Error(`[markdown-explorer] the open document ${Y.describeValue(n)} has no panel id`);a.delete(n),a.set(t,m);const g=new Set(e.markup);return g.delete(n),{state:{docs:e.docs.map(i=>i===n?t:i),maximized:e.maximized===n?t:e.maximized,columnOf:o,hidden:s,markup:g,panelIds:a},outcome:"navigated"}},ke=(e,n,t)=>{if(!e.docs.includes(n)||e.hidden.has(n)===t)return e;const o=new Set(e.hidden);return t?o.add(n):o.delete(n),{...e,hidden:o,maximized:t&&e.maximized===n?null:e.maximized}},on=(e,n,t)=>{if(!e.docs.includes(n)||e.markup.has(n)===t)return e;const o=new Set(e.markup);return t?o.add(n):o.delete(n),{...e,markup:o}},rn=(e,n)=>{if(e.maximized===n||n!==null&&!e.docs.includes(n))return e;if(n===null||!e.hidden.has(n))return{...e,maximized:n};const t=new Set(e.hidden);return t.delete(n),{...e,maximized:n,hidden:t}},sn=(e,n,t)=>{const o=ee(e,t),r=new Map;for(const[i,v]of o.entries())for(const C of v)r.set(C,i);const s=new Set(e.docs),a=new Set,m=j.columnGroups(t.logical,t.visible),g=Array.from({length:t.logical},()=>[]);for(const[i,v]of m.entries()){const C=(n[i]??[]).filter(T=>s.has(T)&&!a.has(T));for(const T of C)a.add(T);for(const[T,A]of Qe(C,v,y=>r.get(y)).entries())g[v[0]+T]?.push(...A)}for(const i of e.docs)a.has(i)||g[r.get(i)??0]?.push(i);return g.every((i,v)=>i.length===o[v]?.length&&i.every((C,T)=>o[v]?.[T]===C))?e:{...e,...Le(e,g)}},te=(e,n)=>{const t=[...new Set(e.docs)].slice(0,n),o=new Set(t),r=e.maximized!==null&&o.has(e.maximized)?e.maximized:null;return{docs:t,maximized:r,columnOf:e.stored.columnOf,hidden:new Set([...e.stored.hidden].filter(s=>o.has(s)&&s!==r)),markup:new Set(e.markup.filter(s=>o.has(s))),panelIds:Xe(t,e.panelIds)}},pe=(e,n)=>{if(e.docs.every(o=>e.columnOf.has(o)))return e;const t=new Map(e.columnOf);for(const[o,r]of ee(e,n).entries())for(const s of r)t.delete(s),t.set(s,o);for(const o of t.keys()){if(t.size<=Q)break;t.delete(o)}return{...e,columnOf:t}},Re=1,U=Object.freeze({columnOf:new Map,hidden:new Set}),ln=(e,n)=>{if(e===null||e==="")return U;let t;try{t=JSON.parse(e)}catch{return U}if(t===null||typeof t!="object"||Array.isArray(t))return U;const o=t;if(o.v!==Re)return U;const r=new Map;if(Array.isArray(o.columnOf))for(const a of o.columnOf.slice(-Q))Array.isArray(a)&&a.length===2&&typeof a[0]=="string"&&a[0]!==""&&Number.isInteger(a[1])&&a[1]>=0&&a[1]<n&&(r.delete(a[0]),r.set(a[0],a[1]));const s=new Set(Array.isArray(o.hidden)?o.hidden.filter(a=>typeof a=="string"&&a!==""):[]);return{columnOf:r,hidden:s}},an=e=>JSON.stringify({v:Re,columnOf:[...e.columnOf.entries()].slice(-Q),hidden:e.docs.filter(n=>e.hidden.has(n))}),ae=(e,n)=>{const t=e.get(n);return t===void 0?Ce.lastPathSegment(n):t},W=e=>{const n=new Map;for(const[t,o]of e.panelIds)n.set(o,t);return n},ge=e=>{if(!Ce.isAcceptableDocumentPath(e))throw new RangeError(`[markdown-explorer] not an acceptable document path: ${Y.describeValue(e)}`)},cn=({config:e,location:n,writeUrl:t,persist:o})=>{const{maxPanels:r,columns:s}=e.multiView,a=P.createEmitter(),m=new Map,g=new Map;let i={layout:te({docs:n.docs,maximized:n.maximized,markup:n.markup,stored:U},r),source:n.source,visibleColumns:s,ready:!1,splitDragging:!1,titles:new Map,pendingHashes:new Map},v=!1;const C=l=>v?pe(l,{logical:s,visible:i.visibleColumns}):l,T=(l,S)=>j.explorerHref(e,{view:"multi",source:l,docs:S.docs,maximized:S.maximized,markup:S.markup}),A=l=>({docs:l.docs,maximized:l.maximized,markup:[...l.markup]});let y=T(n.source,n),d=n.source,x=y;const h=[],O=[];let L=null;const N=()=>{if(!(h.length>0))for(const l of O.splice(0))l()},R=l=>{i={...i,...l},a.emit()},u=()=>{if(!i.ready)return;const l=an(i.layout);l!==L&&(L=l,o(l))},p=(l,S,b)=>{const I=T(l,A(S));I!==y&&(y=I,d=l,h.push(I),t(I,b))},f=l=>{const S=new Set(l.panelIds.values());for(const E of[...m.keys()])S.has(E)||m.delete(E);for(const E of[...g.keys()])S.has(E)||g.delete(E);const b=new Set(l.docs),I=[...i.titles.keys()].every(E=>b.has(E))?i.titles:new Map([...i.titles].filter(([E])=>b.has(E))),w=[...i.pendingHashes.keys()].every(E=>S.has(E))?i.pendingHashes:new Map([...i.pendingHashes].filter(([E])=>S.has(E)));return{titles:I,pendingHashes:w}},M=l=>l===i.layout?!1:(R({layout:l,...f(l)}),p(d,l,"replace"),u(),!0),_=()=>({logical:s,visible:i.visibleColumns});return{getSnapshot:()=>i,subscribe:a.subscribe,toggle:l=>{ge(l);const{state:S,outcome:b}=nn(i.layout,l,_(),r);return M(S),b},close:l=>M(Me(i.layout,l)),navigate:(l,S)=>{ge(S);const{state:b,outcome:I}=tn(i.layout,l,S);if(I!=="navigated")return I;const w=b.panelIds.get(S);return w!==void 0&&(m.delete(w),g.delete(w)),M(b),I},setHidden:(l,S)=>M(ke(i.layout,l,S)),maximize:l=>M(rn(i.layout,l)),setMarkup:(l,S)=>M(on(i.layout,l,S)),arrange:l=>M(sn(i.layout,l,{logical:s,visible:l.length})),changeSource:l=>{p(l,i.layout,"push")},revealSource:l=>{p(l,i.layout,"replace")},observeLocation:l=>{const S=T(l.source,l);if(S===y)return h.length=0,x=S,l.source!==i.source&&R({source:l.source}),N(),!1;if(S===x)return!1;x=S;const b=h.indexOf(S);if(b>=0)return h.splice(0,b+1),l.source!==i.source&&R({source:l.source}),N(),!1;h.length=0,y=S,d=l.source;const I=C(te({docs:l.docs,maximized:l.maximized,markup:l.markup,stored:{columnOf:i.layout.columnOf,hidden:i.layout.hidden},panelIds:i.layout.panelIds},r));return R({layout:I,source:l.source,...f(I)}),u(),N(),!0},whenUrlRendered:l=>{O.push(l),N()},loadStored:l=>{R({layout:C(te({docs:i.layout.docs,maximized:i.layout.maximized,markup:[...i.layout.markup],stored:l,panelIds:i.layout.panelIds},r)),ready:!0}),u()},setVisibleColumns:l=>{if(!Number.isInteger(l)||l<1||l>s)throw new RangeError(`[markdown-explorer] visible columns must be an integer in 1..${String(s)}; got ${Y.describeValue(l)}`);v=!0;const S=pe(i.layout,{logical:s,visible:l});l===i.visibleColumns&&S===i.layout||(R({visibleColumns:l,layout:S}),S!==i.layout&&u())},setSplitDragging:l=>{l!==i.splitDragging&&R({splitDragging:l})},setTitle:(l,S)=>{!i.layout.docs.includes(l)||i.titles.get(l)===S||R({titles:new Map(i.titles).set(l,S)})},titleOf:l=>ae(i.titles,l),setPendingHash:(l,S)=>{const b=i.pendingHashes.get(l);if(S===null||S===""){if(b===void 0)return;const I=new Map(i.pendingHashes);I.delete(l),R({pendingHashes:I});return}b!==S&&R({pendingHashes:new Map(i.pendingHashes).set(l,S)})},saveReadingPosition:(l,S,b)=>{i.layout.panelIds.get(S)===l&&m.set(l,{doc:S,position:b})},readingPositionOf:(l,S)=>{const b=m.get(l);return b===void 0||b.doc!==S?null:b.position},saveImageView:(l,S,b)=>{g.set(l,{url:S,state:b})},imageViewOf:(l,S)=>{const b=g.get(l);return b===void 0||b.url!==S?null:b.state}}},z=(e,n)=>{const t=()=>n(e.getSnapshot());return c.useSyncExternalStore(e.subscribe,t,t)},un=e=>{const{config:n,storageNamespace:t}=P.useExplorer(),o=fe.useNavigate(),r=c.useRef(o),s=ne.storageKeys(t).multiLayout,[a]=c.useState(()=>cn({config:n,location:e,writeUrl:(i,v)=>{r.current(i,P.explorerNavigationOptions(v==="replace"?"browse":"switch-source"))},persist:i=>ne.writeStorage(s,i)}));c.useLayoutEffect(()=>{r.current=o},[o]);const m=fe.useLocation(),g=c.useMemo(()=>({location:e,navigated:m}),[e,m]);return c.useLayoutEffect(()=>{a.observeLocation(g.location)},[a,g]),c.useLayoutEffect(()=>{a.loadStored(ln(ne.readStorage(s),n.multiView.columns))},[a,s,n]),a},dn=e=>{const n=e.closest(D.SCROLL_AREA_SELECTOR);if(n===null)throw new Error("[markdown-explorer] a panel's document region is not inside the panel's scroll area");return n},mn=({docPath:e,panelId:n,maximized:t,title:o,onContentShown:r})=>{const{store:s,followLink:a,revealInPanel:m,keepAtStartInPanel:g}=ie(),{announcer:i}=P.useExplorer(),v=z(s,u=>Fe(u,n)),C=z(s,u=>u.layout.markup.has(e)),T=c.useCallback((u,p)=>a(n,e,u,p),[a,n,e]),A=c.useCallback(()=>s.setPendingHash(n,null),[s,n]),y=c.useMemo(()=>({read:u=>s.imageViewOf(n,u),save:(u,p)=>s.saveImageView(n,u,p)}),[s,n]),d=c.useCallback((u,p)=>{p.kind!=="failure"&&s.setTitle(u,p.name),r(u)},[s,r]),x=c.useCallback(u=>{s.whenUrlRendered(()=>i.announce(u))},[s,i]),h=c.useMemo(()=>({scrollerOf:dn,reveal:u=>m(n,u),keepAtStart:(u,p)=>g(n,u,p)}),[m,g,n]),O=c.useMemo(()=>({kind:"panel",maximized:t,onDocumentLink:T,pendingHash:v,onHashConsumed:A,announceFailure:x,paneScroll:h}),[t,T,v,A,x,h]),L=c.useMemo(()=>({kind:"panel",documentName:o,maximized:t}),[o,t]),N=c.useCallback(()=>s.setMarkup(e,!s.getSnapshot().layout.markup.has(e)),[s,e]),R=c.useMemo(()=>({shown:C,toggle:N}),[C,N]);return k.jsxs(P.ImageViewMemoryContext,{value:y,children:[k.jsx(P.DocumentRefreshBar,{path:e,placement:L,markup:R,maximize:null}),k.jsx(P.DocumentPane,{path:e,absence:P.NO_DOCUMENT,markup:C,variant:O,onDocumentShown:d})]})},he=()=>typeof HTMLElement<"u"&&typeof HTMLElement.prototype.showPopover=="function"&&typeof HTMLElement.prototype.hidePopover=="function",ce="data-aqmx-column-probe",J="data-panel-id",se="--aqmx-multi-panel-chrome",fn=e=>e==="normal"?0:P.cssPixels(e),pn=(e,n)=>{const t=e.querySelector(D.SCROLL_ROOT_SELECTOR)?.firstElementChild,o=e.querySelector(`[${ce}]`),r=o instanceof HTMLElement?o.getBoundingClientRect().width:Number.NaN;if(!(t instanceof HTMLElement))return{plan:{trackInlineSize:Number.NaN,gap:Number.NaN,minColumnInlineSize:r,logicalColumns:n},stageBlockSize:Number.NaN};const s=getComputedStyle(t),a=t.clientWidth-P.cssPixels(s.paddingLeft)-P.cssPixels(s.paddingRight),m=t.clientHeight-P.cssPixels(s.paddingTop)-P.cssPixels(s.paddingBottom);return{plan:{trackInlineSize:a,gap:fn(s.columnGap),minColumnInlineSize:r,logicalColumns:n},stageBlockSize:m}},gn=(e,n)=>{if(e.getClientRects().length===0)return Number.NaN;const t=getComputedStyle(e);return n.getBoundingClientRect().top-e.getBoundingClientRect().top+P.cssPixels(t.paddingBottom)+P.cssPixels(t.borderBottomWidth)},X="data-aqmx-panel-frame",Se="--aqmx-multi-panel-pinned-block-size",hn=e=>{const{docPath:n,panelId:t}=e;if(typeof n!="string"||typeof t!="string")throw new TypeError("[markdown-explorer] a multi-view panel needs string docPath and panelId props");return{docPath:n,panelId:t}},Sn=e=>{const n=getComputedStyle(e),t=Number.parseFloat(n.lineHeight);return Number.isFinite(t)?t:Number.parseFloat(n.fontSize)},xn=(e,n,t)=>e.deltaMode===WheelEvent.DOM_DELTA_PAGE?e.deltaY*n.clientHeight:e.deltaMode!==WheelEvent.DOM_DELTA_LINE?e.deltaY:e.deltaY*t(n),$=e=>{const n=e.closest(D.SCROLL_AREA_SELECTOR);return n instanceof HTMLElement?n:null},Ne=e=>{const n=e.firstElementChild;return n instanceof HTMLElement&&getComputedStyle(n).position==="sticky"?n:null},Ae=(e,n)=>{const t=n.getBoundingClientRect().top,o=Ne(e);return o===null?t:Math.max(t,o.getBoundingClientRect().bottom)},xe=(e,n)=>{let t=0,o=e.length;for(;t<o;){const r=t+o>>>1;(e[r]?.getBoundingClientRect().bottom??Number.NEGATIVE_INFINITY)>n?o=r:t=r+1}return t<e.length?t:-1},yn=(e,n)=>{const t=Ae(e,n),o=[];let r=e;for(let a=xe([...r.children],t);a>=0;a=xe([...r.children],t)){const m=r.children[a];if(m===void 0)break;o.push(a),r=m}const s=r.getBoundingClientRect();return{scrollTop:n.scrollTop,anchor:o.length===0?null:{path:o,offset:s.top-t,height:s.height}}},ye=(e,n,t)=>{if(n.scrollTop=t.scrollTop,t.anchor===null)return;let o=e;for(const g of t.anchor.path)o=o?.children[g];if(o===void 0)return;const r=o.getBoundingClientRect(),{offset:s,height:a}=t.anchor,m=s<0&&a>0?s/a*r.height:s;n.scrollTop+=r.top-Ae(e,n)-m},vn=Object.freeze(["data-testid","aria-label","title","href","id","name"]),Ie=e=>{const n=e.getAttribute(D.PANEL_ACTION_ATTRIBUTE);return JSON.stringify(n===null?[e.tagName,...vn.map(t=>e.getAttribute(t))]:[e.tagName,D.PANEL_ACTION_ATTRIBUTE,n])},wn=(e,n)=>{if(n===null||!e.contains(n))return null;const t=[];for(let o=n;o!==e;){const r=o.parentElement;if(r===null)return null;t.unshift([...r.children].indexOf(o)),o=r}return{path:t,signature:Ie(n)}},En=(e,n,t)=>{let o=e;for(const r of t.path)o=o?.children[r];o instanceof HTMLElement&&Ie(o)===t.signature&&P.focusWithoutScroll(o)||n.focus({preventScroll:!0})},Cn=(e,n,t)=>{if(e.shiftKey||Math.abs(e.deltaX)>Math.abs(e.deltaY))return;const o=e.ctrlKey||e.metaKey,r=o?$(n):n.closest(D.SCROLL_ROOT_SELECTOR);if(!(r instanceof HTMLElement))return;const s=xn(e,r,t);(o||On(r,s))&&(e.preventDefault(),r.scrollTop+=s)},On=(e,n)=>n<0?e.scrollTop>0:n>0?Math.ceil(e.scrollTop+e.clientHeight)<e.scrollHeight:!1,bn=e=>e.scrollHeight>e.clientHeight,Pn=(e,n,t)=>{let o=Number.NaN,r=Number.NaN;const s=Ne(t),a=()=>{const i=gn(e,n);if(!Number.isFinite(i))return;const v=s===null?0:s.getBoundingClientRect().height;v!==r&&(r=v,t.style.setProperty(Se,`${String(v)}px`));const C=i+v;C!==o&&(o=C,e.style.setProperty(se,`${String(C)}px`))};a();let m=null;const g=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>{m===null&&(m=requestAnimationFrame(()=>{m=null,a()}))});return g?.observe(e),g?.observe(n),s!==null&&g?.observe(s),()=>{g?.disconnect(),m!==null&&cancelAnimationFrame(m),e.style.removeProperty(se),t.style.removeProperty(Se)}},Tn=e=>{const{docPath:n,panelId:t}=hn(e),{store:o,Body:r,maximize:s,focusCarry:a}=ie(),m=z(o,d=>d.layout.maximized===n),g=z(o,d=>ae(d.titles,n)),i=c.useRef(null),v=c.useRef(null),C=c.useRef(null),T=c.useRef(null);c.useEffect(()=>{const d=i.current,x=d===null?null:$(d);if(d===null||x===null||m)return;const h=new Map,O=p=>{const f=h.get(p);if(f!==void 0)return f;const M=Sn(p);return h.set(p,M),M},L=p=>Cn(p,d,O);let N=!1;const R=()=>{const p=bn(x);p!==N&&(N=p,p?d.addEventListener("wheel",L,{capture:!0,passive:!1}):d.removeEventListener("wheel",L,{capture:!0}))};R();const u=typeof ResizeObserver>"u"?null:new ResizeObserver(R);return u?.observe(x),u?.observe(d),()=>{u?.disconnect(),d.removeEventListener("wheel",L,{capture:!0})}},[m]),c.useLayoutEffect(()=>{const d=i.current,x=d===null?null:$(d),h=d===null?null:d.closest(`[${J}]`);if(!(d===null||x===null||!(h instanceof HTMLElement)))return Pn(h,x,d)},[]),c.useLayoutEffect(()=>{const d=i.current,x=d===null?null:$(d);if(d===null||x===null)return;const h=p=>{ye(d,x,p),T.current=x.scrollTop},O=o.readingPositionOf(t,n);v.current=O===null?null:{doc:n,position:O},O!==null&&h(O);let L=null,N=d.getBoundingClientRect().width;const R=()=>{L===null&&(L=requestAnimationFrame(()=>{L=null;const p=T.current;if(T.current=null,p!==null&&x.scrollTop===p||d.getBoundingClientRect().width!==N)return;const f=C.current;f!==null&&o.saveReadingPosition(t,f,yn(d,x))}))};x.addEventListener("scroll",R,{passive:!0});const u=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>{const p=d.getBoundingClientRect().width;if(p===N)return;N=p;const f=o.readingPositionOf(t,n);f!==null&&h(f)});return u?.observe(d),()=>{x.removeEventListener("scroll",R),u?.disconnect(),L!==null&&cancelAnimationFrame(L)}},[o,t,n]),c.useLayoutEffect(()=>{const d=i.current,x=d===null?null:d.closest(`[${J}]`);if(d===null||x===null)return;const h=a.take(t);return h!==null&&En(x,d,h),()=>{const O=wn(x,x.ownerDocument.activeElement);O!==null&&a.hold(t,O)}},[a,t]);const A=c.useCallback(d=>{const x=i.current,h=x===null?null:$(x);if(x===null||h===null)return;const O=C.current;C.current=d;const L=v.current;v.current=null,L!==null&&L.doc===d?(ye(x,h,L.position),T.current=h.scrollTop):O!==null&&O!==d&&(h.scrollTop=0)},[]),y=c.useCallback(d=>{P.isInFullscreenBlock(d.target)||s(n)},[s,n]);return k.jsx("div",{ref:i,role:"group","aria-label":g,className:"aqmx-multi-panel-frame",tabIndex:-1,"data-aqmx-panel-frame":t,"data-aqmx-maximized":m?"true":"false","data-testid":"markdown-explorer-panel-frame",...m?P.CONTENT_PANE:{},onDoubleClick:m?void 0:y,children:k.jsx(r,{docPath:n,panelId:t,maximized:m,title:g,onContentShown:A})})},Ln=c.memo(Tn),K=(e,n)=>{const t=e.panelIds.get(n);if(t===void 0)throw new Error(`[markdown-explorer] the open document ${Y.describeValue(n)} has no panel id`);return t},ve=e=>Object.fromEntries(D.generateColumnIds(e).map(n=>[n,[]])),Mn=(e,n)=>{const t=Ze(ee(e,n),n.visible);return Object.fromEntries(t.map((o,r)=>[D.generateColumnId(r),o.map(s=>K(e,s))]))},kn=(e,n)=>{const t=W(e);return D.sortColumnIds(Object.keys(n)).map(o=>(n[o]??[]).flatMap(r=>{const s=t.get(r);return s===void 0?[]:[s]}))},Rn=e=>({switchToCustomDragMode:e.panelSwitchToCustomDrag,switchToNormalDragMode:e.panelSwitchToNormalDrag,hidePanel:e.panelHide,maximizePanel:e.panelMaximize,restorePanel:e.panelRestore,closePanel:e.panelClose,movePanel:e.panelMove,movePanelToPreviousColumn:e.panelMovePreviousColumn,movePanelToNextColumn:e.panelMoveNextColumn,movePanelUp:e.panelMoveUp,movePanelDown:e.panelMoveDown,morePanelActions:e.panelMoreActions,customDragModeBadge:e.panelCustomDragBadge,panelMoved:e.panelMoved,panelMoveUnavailable:e.panelMoveUnavailable,panelDragStarted:e.panelDragStarted,panelDragCancelled:e.panelDragCancelled,hiddenPanels:e.hiddenPanelsTitle,hiddenPanelBadge:e.hiddenPanelBadge,hiddenPanelNotice:e.hiddenPanelNotice,emptyColumn:e.multiColumnEmpty,dropZone:e.multiColumnRegion,dropHere:e.panelDropHere}),Nn="--aqmx-multi-stage-bar-gutter",An=Object.freeze({[Nn]:`${String(P.NATIVE_SCROLL_BAR_WIDTH)}px`}),In=Object.freeze({blockSize:"100%",paddingInlineEnd:P.TAP_SCROLL_CIRCLE_GUTTER_LENGTH}),_n=Object.freeze({[D.NO_PANEL_DRAG_ATTRIBUTE]:"",style:Object.freeze({display:"flex"})}),Dn=e=>k.jsx("div",{..._n,children:k.jsx(P.LazyNativeScrollBar,{scroller:e,kind:"content"})}),zn=({props:e,children:n})=>k.jsx(Be.HostedScrollArea,{scrollerProps:{...e,style:In},renderScrollBar:Dn,barInlineSize:P.NATIVE_SCROLL_BAR_SLOT_LENGTH,children:n}),Hn=e=>k.jsx(P.LazyNativeScrollBar,{scroller:e,kind:"stage"}),ue="--aqmx-stage-block",qn="--aqmx-multi-panel-body-floor",Bn=`calc(var(${ue}) * ${String(j.PANEL_MIN_BLOCK_RATIO)})`,jn=`max(calc(var(${ue}) * ${String(j.PANEL_MAX_BLOCK_RATIO)}), calc(var(${se}) + var(${qn})))`,Fn=(e,n)=>{const t=Object.entries(e);return t.length!==Object.keys(n).length?!1:t.every(([o,r])=>{const s=n[o];return s!==void 0&&s.length===r.length&&s.every((a,m)=>r[m]===a)})},G=(e,n,t,o)=>{P.stopKeepingInView(e);const r=e.querySelector(`[${J}="${n}"]`);if(!(r instanceof HTMLElement))return;const s=t!==null&&r.contains(t)?t:null,a=[{element:r,boundary:r.closest(D.SCROLL_ROOT_SELECTOR)}];s!==null&&a.push({element:s,boundary:r}),P.keepInView(e,()=>r.isConnected?(r.scrollIntoView(P.NEAREST),s?.isConnected!==!0?r:(o(s),s)):null,a)},Z=e=>{e.scrollIntoView(P.NEAREST)},_e=(e,n)=>{const t=e.querySelector(`[${X}="${n}"]`);return t instanceof HTMLElement?(G(e,n,null,Z),t.focus({preventScroll:!0}),!0):!1},de=(e,n)=>{const t=e.querySelector(`[${J}="${n}"]`);return t instanceof HTMLElement&&t.contains(e.ownerDocument.activeElement)},we=(e,n)=>{if(!de(e,n))return null;const t=[...e.querySelectorAll(`[${X}]`)].map(a=>a.getAttribute(X)),o=t.indexOf(n),r=t[o+1];if(o>=0&&typeof r=="string")return{kind:"panel",panelId:r};const s=t[o-1];return o>0&&typeof s=="string"?{kind:"panel",panelId:s}:{kind:"stage"}},Ee=(e,n)=>{requestAnimationFrame(()=>{const t=e.current;t!==null&&(n.kind==="panel"&&_e(t,n.panelId)||t.focus({preventScroll:!0}))})},De=(e,n)=>{requestAnimationFrame(()=>{const t=e.current;t!==null&&_e(t,n)})},Vn=(e,n,t)=>{requestAnimationFrame(()=>{const o=e.current;if(o===null)return;const{activeElement:r,body:s}=o.ownerDocument;if(G(o,n,t&&de(o,n)?r:null,Z),!t||r!==null&&r!==s&&r.isConnected)return;const a=o.querySelector(`[${X}="${n}"]`);a instanceof HTMLElement&&a.focus({preventScroll:!0})})},Un=({store:e,stageRef:n})=>{const{config:t,labels:o,announcer:r,edits:s}=P.useExplorer(),{maximize:a}=ie(),m=t.multiView.columns,g=z(e,w=>w.layout),i=z(e,w=>w.visibleColumns),v=z(e,w=>w.titles),C=z(e,w=>w.layout.maximized!==null||w.splitDragging),[T,A]=c.useState(!1),[y]=c.useState(()=>ve(i)),d=c.useMemo(()=>Rn(o),[o]),x=c.useCallback(w=>{e.arrange(kn(e.getSnapshot().layout,w))},[e]),h=D.useDragDropColumns({initialColumnPanels:y,initialPanelVisibility:{},debugConfig:D.DEFAULT_DEBUG_CONFIG,onColumnPanelsChange:x}),{columnPanels:O,setColumnPanels:L}=h,N=c.useRef(C),R=c.useRef(O);c.useLayoutEffect(()=>{N.current=C,R.current=O},[C,O]);const u=c.useCallback(w=>{const E=n.current;if(E===null)return;const{plan:B,stageBlockSize:H}=pn(E,m);if(Number.isFinite(H)&&H>0&&E.style.setProperty(ue,`${String(H)}px`),N.current&&!w)return;const q=j.replanVisibleColumns(e.getSnapshot().visibleColumns,B);q!==null&&e.setVisibleColumns(q)},[e,n,m]);c.useLayoutEffect(()=>{u(!0),A(!0)},[u]),c.useEffect(()=>{const w=n.current;if(w===null||typeof ResizeObserver>"u")return;let E=null;const B=new ResizeObserver(()=>{E===null&&(E=requestAnimationFrame(()=>{E=null,u(!1)}))}),H=w.querySelector(D.SCROLL_ROOT_SELECTOR)?.firstElementChild,q=w.querySelector(`[${ce}]`);return H instanceof Element&&B.observe(H),q instanceof Element&&B.observe(q),()=>{B.disconnect(),E!==null&&cancelAnimationFrame(E)}},[n,u]),c.useEffect(()=>{C||u(!1)},[C,u]);const p=c.useMemo(()=>T?Mn(g,{logical:m,visible:i}):ve(i),[T,g,m,i]);c.useLayoutEffect(()=>{Fn(R.current,p)||L(p)},[p,L]);const f=c.useMemo(()=>D.sortColumnIds(Object.keys(O)).map(w=>({id:w,key:w,className:"aqmx-multi-column"})),[O]),M=c.useMemo(()=>g.docs.map(w=>{const E=K(g,w);return{id:E,component:Ln,title:ae(v,w),props:{docPath:w,panelId:E},minHeight:Bn,maxHeight:jn}}),[g,v]),_=c.useMemo(()=>Object.fromEntries(g.docs.map(w=>[K(g,w),!g.hidden.has(w)])),[g]),l=g.maximized===null?null:K(g,g.maximized),S=c.useCallback(w=>{const{layout:E}=e.getSnapshot();for(const[B,H]of W(E)){const q=w[B];if(q===void 0||q!==E.hidden.has(H))continue;const F=e.titleOf(H);if(q){if(!e.setHidden(H,!1))continue;r.announce(o.panelShown(F)),De(n,B);continue}const V=n.current,me=V===null?null:we(V,B);e.setHidden(H,!0)&&(r.announce(o.panelHidden(F)),me!==null&&Ee(n,me))}},[e,n,r,o]),b=c.useCallback(w=>{const E=W(e.getSnapshot().layout).get(w);if(E===void 0)return;const B=()=>{const q=e.titleOf(E),F=n.current,V=F===null?null:we(F,w);e.close(E)&&(r.announce(o.panelClosed(q)),V!==null&&Ee(n,V))},H=s.unsavedAmong([E]);H.length===0?B():s.askToDiscard(H).then(q=>{q&&B()})},[e,n,r,o,s]),I=c.useCallback(w=>{if(w===null){a(null);return}const E=W(e.getSnapshot().layout).get(w);E!==void 0&&a(E)},[e,a]);return k.jsx("div",{className:"aqmx-multi-layout","aria-busy":!T,children:k.jsx(D.DragDropLayout,{columns:f,panels:M,columnPanels:O,onColumnPanelsChange:x,panelVisibility:_,onPanelVisibilityChange:S,dragState:h.dragState,dragOverPosition:h.dragOverPosition,originalPanelPosition:h.originalPanelPosition,dragModes:h.dragModes,debugConfig:D.DEFAULT_DEBUG_CONFIG,panelSizes:h.panelSizes,customDrag:h.customDrag,setPanelRef:h.setPanelRef,onDragStart:h.handleDragStart,onDragEnd:h.handleDragEnd,onPlaceholderDragEnter:h.handlePlaceholderDragEnter,onPlaceholderDragLeave:h.handlePlaceholderDragLeave,onDragOverWithInsert:h.handleDragOverWithInsert,onDropWithInsert:h.handleDropWithInsert,onColumnDragLeave:h.handleColumnDragLeave,onPanelMouseDown:h.handleMouseDown,onPanelSizeInfoClick:h.handlePanelSizeInfoClick,onToggleDragMode:h.toggleDragMode,onPanelClose:b,onPanelMaximizeChange:I,maximizedPanel:l,dragHandle:"header",labels:d,panelClassName:"aqmx-multi-panel",renderPanelScrollArea:zn,renderStageScrollBar:Hn})})},oe={blockStart:"--aqmx-multi-toast-block-start",inlineEnd:"--aqmx-multi-toast-inline-end",room:"--aqmx-multi-toast-room"},$n=(e,n)=>{const t=n.getBoundingClientRect(),o=[t.left+1,t.left+t.width/2,t.right-1],r=[t.top+1,t.top+t.height/2,t.bottom-1];return o.some(s=>r.some(a=>{const m=n.ownerDocument.elementsFromPoint(s,a),g=m.findIndex(v=>n.contains(v)),i=m.findIndex(v=>e.contains(v));return g!==-1&&i!==-1&&i<g}))},Gn=(e,n)=>{const t=n.getBoundingClientRect(),o=n.ownerDocument.documentElement.clientWidth,r=getComputedStyle(n).direction==="rtl";return e.style.setProperty(oe.blockStart,`${String(t.top)}px`),e.style.setProperty(oe.inlineEnd,`${String(r?t.left:o-t.right)}px`),e.style.setProperty(oe.room,`${String(t.width)}px`),e.showPopover(),()=>{e.isConnected&&e.hidePopover()}},Yn=({store:e,body:n,limitNotice:t,onLimitNoticeCovered:o,ref:r})=>{const{config:s,labels:a,announcer:m,edits:g}=P.useExplorer(),i=c.useRef(null),v=c.useRef(null),C=z(e,u=>u.ready),T=z(e,u=>u.layout.docs.length>0),A=z(e,u=>u.visibleColumns),y=c.use(re.SheetNoticeSlotContext),d=c.useCallback(u=>{const{layout:p}=e.getSnapshot(),f=p.maximized,M=u===null&&f!==null?p.panelIds.get(f):void 0,_=i.current,l=M!==void 0&&_!==null&&de(_,M);e.maximize(u)&&(u!==null?m.announce(a.panelMaximized(e.titleOf(u))):f!==null&&m.announce(a.panelRestored(e.titleOf(f))),M!==void 0&&Vn(i,M,l))},[e,m,a]),x=c.useCallback((u,p,f,M)=>{if(f===p){e.setPendingHash(u,M);return}const _=g.unsavedAmong([p]);if(_.length>0){g.askToDiscard(_).then(I=>{I&&x(u,p,f,M)});return}const l=e.navigate(p,f);if(l==="navigated"){e.setPendingHash(u,M);return}if(l!=="existing")return;const{layout:S}=e.getSnapshot(),b=S.panelIds.get(f);b!==void 0&&(m.announce(a.panelAlreadyOpen(e.titleOf(f))),S.maximized===null?e.setHidden(f,!1):d(f),e.setPendingHash(b,M),De(i,b))},[e,m,a,d,g]);c.useLayoutEffect(()=>{if(t===null||y!==null||!he())return;const u=v.current,p=i.current;if(u===null||p===null)throw new Error("[markdown-explorer] the panel-limit notice and the stage must be mounted together");return Gn(u,p)},[t,y]),c.useEffect(()=>{const u=v.current;if(t===null||u===null)return;const{ownerDocument:p}=u;let f=null;const M=_=>{const l=_.target;l instanceof Element&&(f!==null&&cancelAnimationFrame(f),f=requestAnimationFrame(()=>{f=null,p.activeElement===l&&u.isConnected&&$n(u,l)&&o()}))};return p.addEventListener("focusin",M,!0),()=>{p.removeEventListener("focusin",M,!0),f!==null&&cancelAnimationFrame(f)}},[t,y,o]),c.useImperativeHandle(r,()=>({bringIntoView:u=>{requestAnimationFrame(()=>{const p=i.current,f=e.getSnapshot().layout.panelIds.get(u);p!==null&&f!==void 0&&G(p,f,null,Z)})}}),[e]),c.useEffect(()=>{const u=i.current;return()=>{u!==null&&P.stopKeepingInView(u)}},[]);const h=c.useCallback((u,p)=>{const f=i.current;f!==null&&G(f,u,p,Z)},[]),O=c.useCallback((u,p,f)=>{const M=i.current;M!==null&&G(M,u,f,_=>P.alignToStart(p,_))},[]),[L]=c.useState(je),N=c.useMemo(()=>({store:e,Body:n,followLink:x,maximize:d,revealInPanel:h,keepAtStartInPanel:O,focusCarry:L}),[e,n,x,d,h,O,L]),R=c.useMemo(()=>Array.from({length:s.multiView.columns},(u,p)=>D.generateColumnId(p)),[s]);return k.jsxs("section",{ref:i,className:"aqmx-multi-stage",style:An,tabIndex:-1,"aria-label":a.multiRegion,"aria-busy":T&&!C,"data-testid":"markdown-explorer-stage","data-aqmx-visible-columns":A,...P.CONTENT_PANE,children:[k.jsx("span",{className:"aqmx-multi-probe","aria-hidden":"true",[ce]:""}),T?C?k.jsx(Oe,{value:N,children:k.jsx(Un,{store:e,stageRef:i})}):k.jsx("div",{className:"aqmx-multi-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-stage-skeleton",children:R.map(u=>k.jsxs("div",{className:"aqmx-skeleton aqmx-multi-skeleton-column",children:[k.jsx("span",{}),k.jsx("span",{}),k.jsx("span",{})]},u))}):k.jsx("div",{className:"aqmx-empty","data-testid":"markdown-explorer-multi-empty",children:k.jsx("p",{className:"aqmx-empty-title",children:a.multiEmpty})}),t===null?null:y!==null?qe.createPortal(k.jsx("div",{ref:v,className:"aqmx-toast aqmx-multi-toast","data-testid":"markdown-explorer-panel-limit",children:t}),y):k.jsx("div",{ref:v,popover:he()?"manual":void 0,className:"aqmx-toast aqmx-multi-toast","data-testid":"markdown-explorer-panel-limit",children:t})]})},ze=3e3,He=(e,n)=>{if(n!==null)return n;const[t]=e;return t===void 0?null:t},le=(e,n,t)=>{const o=new Set(e),r=n.filter(a=>!o.has(a)),s=r.length>0?r.at(-1):t!==null&&n.includes(t)?t:n.at(-1);return s===void 0?null:s},Wn=(e,n,t)=>{switch(n){case"opened":return e.panelOpened(t);case"shown":return e.panelShown(t);case"closed":return e.panelClosed(t);default:{const o=n;throw new RangeError(`[markdown-explorer] unknown toggle outcome ${Y.describeValue(o)}`)}}},Kn=({location:e})=>{const{config:n,labels:t,announcer:o}=P.useExplorer(),r=un(e),s=z(r,f=>f.layout.docs),a=z(r,f=>f.layout.maximized),m=z(r,f=>f.layout.markup),g=z(r,f=>f.source),[i,v]=c.useState(()=>({docs:s,latest:le([],s,null)}));i.docs!==s&&v({docs:s,latest:le(i.docs,s,i.latest)});const C=a!==null?a:i.latest,[T,A]=c.useState(!1),y=c.useRef(null),[d,x]=c.useState(0),h=c.useRef(null),O=c.useRef(null);c.useLayoutEffect(()=>{const f=h.current;h.current=null,f!==null&&(r.whenUrlRendered(()=>o.announce(f.announcement)),O.current?.bringIntoView(f.doc))}),c.useEffect(()=>()=>{y.current!==null&&clearTimeout(y.current)},[]);const L=c.useCallback(()=>{y.current!==null&&clearTimeout(y.current),A(!0),y.current=setTimeout(()=>{y.current=null,A(!1)},ze)},[]),N=c.useCallback(()=>{y.current!==null&&clearTimeout(y.current),y.current=null,A(!1)},[]),R=c.useCallback(f=>{const M=r.titleOf(f),_=r.toggle(f);_==="rejected"&&L();const l=_==="rejected"?t.panelLimit(n.multiView.maxPanels):Wn(t,_,M);if(_==="shown"){h.current={doc:f,announcement:l},x(S=>S+1);return}r.whenUrlRendered(()=>{o.announce(l),_==="opened"&&O.current?.bringIntoView(f)})},[r,L,o,t,n]),u=c.useMemo(()=>new Set(s),[s]),p=c.useMemo(()=>{const f=He(s,a);return{href:j.explorerHref(n,{view:"tree",source:g,doc:f,markup:f!==null&&m.has(f)}),target:"tree"}},[n,g,s,a,m]);return k.jsx(re.ExplorerSplit,{view:"multi",explorer:k.jsx(re.ExplorerPane,{mode:"multi",sourceId:g,currentPath:C,openPaths:u,onOpenDocument:R,onSourceChange:r.changeSource,onRevealSource:r.revealSource,viewSwitch:p}),content:k.jsx(Yn,{ref:O,store:r,body:mn,limitNotice:T?t.panelLimit(n.multiView.maxPanels):null,onLimitNoticeCovered:N}),contentCoversPage:a!==null,sheetDismissals:d,onDraggingChange:r.setSplitDragging})};exports.MultiLayout=Kn;exports.PANEL_LIMIT_NOTICE_MS=ze;exports.latestOpenedDocument=le;exports.treeSwitchDocument=He;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { jsxs as ae, jsx as A } from "react/jsx-runtime";
|
|
2
2
|
import { createContext as Je, use as Ae, useRef as q, useState as $, useLayoutEffect as F, useMemo as D, useSyncExternalStore as Ze, useCallback as R, memo as Qe, useEffect as U, useImperativeHandle as en } from "react";
|
|
3
3
|
import { d as X } from "./describeValue-CLlVRO8d.js";
|
|
4
|
-
import { s as ue, e as Me, u as nn, P as tn, v as on } from "./location-
|
|
5
|
-
import { U as rn, u as J, V as ln, W as sn, D as an, j as cn, g as un, X as V, L as dn, i as ke, Y as mn, N as fn, Z as Ie, _ as pn, $ as gn, a0 as Le, a1 as hn, a2 as Re, a3 as vn } from "./index-
|
|
6
|
-
import { S as wn, a as yn, b as Sn } from "./ExplorerSplit-
|
|
4
|
+
import { s as ue, e as Me, u as nn, P as tn, v as on } from "./location-DFfbnUZ9.js";
|
|
5
|
+
import { U as rn, u as J, V as ln, W as sn, D as an, j as cn, g as un, X as V, L as dn, i as ke, Y as mn, N as fn, Z as Ie, _ as pn, $ as gn, a0 as Le, a1 as hn, a2 as Re, a3 as vn } from "./index-CWFyLa0N.js";
|
|
6
|
+
import { S as wn, a as yn, b as Sn } from "./ExplorerSplit-DTkr0q2C.js";
|
|
7
7
|
import { SCROLL_AREA_SELECTOR as De, SCROLL_ROOT_SELECTOR as oe, PANEL_ACTION_ATTRIBUTE as ve, generateColumnIds as xn, sortColumnIds as _e, generateColumnId as ze, NO_PANEL_DRAG_ATTRIBUTE as En, useDragDropColumns as On, DEFAULT_DEBUG_CONFIG as we, DragDropLayout as Pn } from "@aiquants/drag-drop-panels";
|
|
8
8
|
import { useNavigate as bn, useLocation as Cn } from "react-router";
|
|
9
9
|
import { s as Tn, r as Nn, w as An } from "./storage-D1uSw-xj.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react/jsx-runtime"),T=require("@aiquants/virtualscroll"),S=require("react"),u=require("./index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react/jsx-runtime"),T=require("@aiquants/virtualscroll"),S=require("react"),u=require("./index-AfEbgYQI.cjs"),d=require("./tapScrollCircle-CS3hbyGb.cjs"),v=e=>({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight}),m=(e,t)=>e.scrollTop===t.scrollTop&&e.scrollHeight===t.scrollHeight&&e.clientHeight===t.clientHeight,g=e=>{let t=v(e);return{getSnapshot:()=>t,subscribe:s=>{const o=()=>{const a=v(e);m(t,a)||(t=a,s())};let n=0;const c=()=>{n===0&&(n=requestAnimationFrame(()=>{n=0,o()}))},r=typeof ResizeObserver>"u"?null:new ResizeObserver(c),l=()=>{if(r!==null){r.disconnect(),r.observe(e);for(const a of e.children)r.observe(a)}};l();const i=typeof MutationObserver>"u"?null:new MutationObserver(()=>{l(),c()});return i?.observe(e,{childList:!0}),e.addEventListener("scroll",o,{passive:!0}),o(),()=>{e.removeEventListener("scroll",o),i?.disconnect(),r?.disconnect(),cancelAnimationFrame(n)}}}},b=e=>{const t=S.useMemo(()=>g(e),[e]);return S.useSyncExternalStore(t.subscribe,t.getSnapshot,t.getSnapshot)},h=(e,t)=>{const s=typeof t=="function"?t(e.scrollTop):t;return e.scrollTo({top:s,behavior:"instant"}),e.scrollTop},f=({scroller:e,kind:t})=>{const{locale:s}=u.useExplorer(),o=u.useCoarsePointer(),{scrollTop:n,scrollHeight:c,clientHeight:r}=b(e),l=S.useCallback(i=>h(e,i),[e]);return p.jsx("div",{className:"aqmx-native-scroll-bar",children:p.jsx(T.ScrollBar,{contentSize:c,viewportSize:r,scrollPosition:n,onScroll:l,scrollBarWidth:u.NATIVE_SCROLL_BAR_WIDTH,...u.scrollBarControlsFor(o),enableArrowButtonTabStops:!1,tapScrollCircleOptions:t==="content"?d.tapScrollCircleFor(o):d.NO_TAP_SCROLL_CIRCLE,locale:s})})};exports.NativeScrollBar=f;exports.scrollScrollerTo=h;exports.useScrollerMetrics=b;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { jsx as u } from "react/jsx-runtime";
|
|
2
2
|
import { ScrollBar as m } from "@aiquants/virtualscroll";
|
|
3
3
|
import { useCallback as S, useMemo as d, useSyncExternalStore as h } from "react";
|
|
4
|
-
import { u as b, c as v, N as f, s as T } from "./index-
|
|
5
|
-
import { NO_TAP_SCROLL_CIRCLE as g, tapScrollCircleFor as H } from "./tapScrollCircle-
|
|
4
|
+
import { u as b, c as v, N as f, s as T } from "./index-CWFyLa0N.js";
|
|
5
|
+
import { NO_TAP_SCROLL_CIRCLE as g, tapScrollCircleFor as H } from "./tapScrollCircle-DKoj17z6.js";
|
|
6
6
|
const p = (e) => ({ scrollTop: e.scrollTop, scrollHeight: e.scrollHeight, clientHeight: e.clientHeight }), C = (e, t) => e.scrollTop === t.scrollTop && e.scrollHeight === t.scrollHeight && e.clientHeight === t.clientHeight, O = (e) => {
|
|
7
7
|
let t = p(e);
|
|
8
8
|
return {
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { jsx as h, jsxs as j } from "react/jsx-runtime";
|
|
2
2
|
import { useCallback as d, useMemo as v, useEffect as g, useSyncExternalStore as q, useState as H, useRef as U, useLayoutEffect as $ } from "react";
|
|
3
3
|
import { useLocation as B } from "react-router";
|
|
4
|
-
import { e as f, c as Y } from "./location-
|
|
5
|
-
import { u as S, f as R, r as J, F as K, g as Q, h as V, i as W, D as X, P as Z, j as I } from "./index-
|
|
4
|
+
import { e as f, c as Y } from "./location-DFfbnUZ9.js";
|
|
5
|
+
import { u as S, f as R, r as J, F as K, g as Q, h as V, i as W, D as X, P as Z, j as I } from "./index-CWFyLa0N.js";
|
|
6
6
|
import { isMaximizeEscape as ee } from "@aiquants/drag-drop-panels";
|
|
7
7
|
import { l as te } from "./ownUrls-DD0cSCsF.js";
|
|
8
|
-
import { E as ne, a as re, b as se } from "./ExplorerSplit-
|
|
8
|
+
import { E as ne, a as re, b as se } from "./ExplorerSplit-DTkr0q2C.js";
|
|
9
9
|
const ae = (e) => {
|
|
10
10
|
const { config: r, labels: n, announcer: t } = S(), c = R(), s = d(() => {
|
|
11
11
|
const u = e.doc !== null ? e.doc : e.folder;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("react/jsx-runtime"),o=require("react"),H=require("react-router"),x=require("./location-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("react/jsx-runtime"),o=require("react"),H=require("react-router"),x=require("./location-Csj3eAm_.cjs"),d=require("./index-AfEbgYQI.cjs"),_=require("@aiquants/drag-drop-panels"),j=require("./ownUrls-BTPGNhBt.cjs"),k=require("./ExplorerSplit-DnuuUifU.cjs"),A=e=>{const{config:r,labels:n,announcer:t}=d.useExplorer(),i=d.useExplorerNavigate(),s=o.useCallback(()=>{const u=e.doc!==null?e.doc:e.folder;if(u===null)throw new RangeError("[markdown-explorer] a tree view without a document or a folder has nothing to maximize");i(x.explorerHref(r,{...e,maximized:!e.maximized}),"browse");const a=j.lastPathSegment(u);t.announce(e.maximized?n.documentRestored(a):n.documentMaximized(a))},[r,i,e,t,n]);return o.useMemo(()=>({maximized:e.maximized,toggle:s}),[e.maximized,s])},G=(e,r)=>{o.useEffect(()=>{if(!e)return;const n=t=>{_.isMaximizeEscape(t)&&(t.preventDefault(),r())};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[e,r])},U=(e,r)=>e.claim!==r.claim||e.readme.status!==r.readme.status?!1:e.readme.status==="failed"&&r.readme.status==="failed"?e.readme.failure===r.readme.failure:e.readme.status==="ok"&&r.readme.status==="ok"?e.readme.readme===r.readme.readme:!0,B=(e,r,n)=>{let t=null;return()=>{const i=e.version(),s=e.read(r),u=s.status!=="pending";if(t!==null&&t.version===i&&t.tree===s&&t.settled===u)return t.state;const a=d.readFolderReadme(e,r,n),l=t!==null&&U(t.state,a)?t.state:a;return t={version:i,tree:s,settled:u,state:l},l}},Y=(e,r,n)=>{let t=!0,i=null;const s=()=>{t&&n()},u=()=>{const l=e.read(r);l===i||l.status!=="pending"||(i=l,l.then(s,s))};u();const a=e.subscribe(()=>{u(),n()});return()=>{t=!1,a()}},J=()=>d.FOLDER_README_LOADING,K=(e,r)=>{const{trees:n}=d.useExplorer(),t=o.useMemo(()=>r===null?null:B(n,e,r),[n,e,r]),i=o.useCallback(p=>t===null?()=>{}:Y(n,e,p),[t,n,e]),s=o.useCallback(()=>t===null?null:t(),[t]),u=o.useCallback(()=>t===null?null:J(),[t]),a=o.useSyncExternalStore(i,s,u),l=a?.claim===!0;return o.useEffect(()=>r===null?void 0:n.open(e),[n,e,r]),o.useEffect(()=>r===null||!l?void 0:n.claimChildren(e,new Map([[r,"direct"]])),[n,e,r,l]),a===null?null:a.readme},Q=new Set,V=Object.freeze({kind:"loading"}),W=(e,r)=>r.status==="loading"?V:r.status==="failed"?{kind:"failure",folder:e,failure:r.failure,onRetry:r.retry}:{kind:"no-readme",folder:e},X=({location:e,opening:r})=>{const{config:n}=d.useExplorer(),t=d.useExplorerNavigate(),{hash:i}=H.useLocation(),{source:s,doc:u,folder:a,overrides:l,markup:p,maximized:f}=e,[g,M]=o.useState(k.EMPTY_SELECTION),O=o.useMemo(()=>({gathered:g,onGatheredChange:M}),[g]),w=K(s,a),m=w===null?u:w.status==="ok"?w.readme:null,h=o.useMemo(()=>r!==null?r:a===null||w===null?d.NO_DOCUMENT:W(a,w),[r,a,w]),b=f&&(m!==null||h.kind==="loading"),R=o.useCallback(c=>t(x.explorerHref(n,{view:"tree",source:s,doc:c,overrides:l}),"browse"),[t,n,s,l]),D=o.useCallback(c=>t(x.explorerHref(n,{view:"tree",source:s,folder:c,overrides:l}),"browse"),[t,n,s,l]),N=o.useCallback(c=>{const E=c.kind==="folder"?{folder:c.path}:c.kind==="document"?{doc:c.path}:{};t(x.explorerHref(n,{view:"tree",source:s,...E,overrides:l}),"close-folder")},[t,n,s,l]),P=o.useCallback(c=>t(x.explorerHref(n,{view:"tree",source:c,doc:u,folder:a,overrides:l,markup:p,maximized:f}),"switch-source"),[t,n,u,a,l,p,f]),T=o.useCallback(c=>t(`${x.explorerHref(n,{view:"tree",source:c,doc:u,folder:a,overrides:l,markup:p,maximized:f})}${i}`,"browse"),[t,n,u,a,l,p,f,i]),q=o.useCallback(c=>{const E=x.canonicalMultiDocuments(n,c);t(x.explorerHref(n,{view:"multi",source:s,docs:E,markup:p&&m!==null&&E.includes(m)?[m]:[]}),"switch-view")},[t,n,s,m,p]),y=o.useMemo(()=>({href:x.explorerHref(n,m===null?{view:"multi",source:s}:{view:"multi",source:s,docs:[m],markup:p?[m]:[]}),target:"multi"}),[n,s,m,p]),S=o.useRef(f);o.useLayoutEffect(()=>{S.current=f},[f]);const C=o.useCallback(()=>S.current,[]),F=o.useMemo(()=>({kind:"page",view:"tree",overrides:l,embed:{},maximized:C}),[l,C]),L=d.usePageMarkupToggle(e),z=A(e);return G(b,z.toggle),v.jsx(k.ExplorerSplit,{view:"tree",contentCoversPage:b,explorer:v.jsx(k.ExplorerPane,{mode:"tree",sourceId:s,currentPath:a===null?u:a,openPaths:Q,onOpenDocument:R,onOpenFolder:D,onCloseFolder:N,currentFolder:a!==null,onSourceChange:P,onRevealSource:T,viewSwitch:y,tray:O,onOpenSelection:q}),content:v.jsxs("div",{className:"aqmx-document-column aqmx-tree-document","data-aqmx-maximized":b?"true":"false",...d.CONTENT_PANE,children:[m===null?null:v.jsx(d.DocumentRefreshBar,{path:m,placement:d.PAGE_DOCUMENT_REFRESH,markup:L,maximize:z}),v.jsx(d.DocumentPane,{path:m,absence:h,markup:p,variant:F})]})})};exports.TreeLayout=X;
|
package/dist/core/config.d.cts
CHANGED
|
@@ -32,6 +32,7 @@ export type ExplorerConfigInput = {
|
|
|
32
32
|
readonly documentStyles?: readonly ExplorerDocumentStyle[];
|
|
33
33
|
readonly defaultDocumentStyle?: string;
|
|
34
34
|
readonly mermaidModifier?: PanZoomModifier;
|
|
35
|
+
readonly documentFontFamily?: string;
|
|
35
36
|
readonly iframeHosts?: readonly string[];
|
|
36
37
|
readonly appOrigins?: readonly string[];
|
|
37
38
|
readonly mediaDataPath?: string;
|
|
@@ -69,6 +70,7 @@ export type ExplorerConfig = {
|
|
|
69
70
|
readonly documentStyles: readonly ExplorerDocumentStyle[];
|
|
70
71
|
readonly defaultDocumentStyle: string;
|
|
71
72
|
readonly mermaidModifier: PanZoomModifier | undefined;
|
|
73
|
+
readonly documentFontFamily: string | undefined;
|
|
72
74
|
readonly iframeHosts: readonly string[];
|
|
73
75
|
readonly appOrigins: readonly string[];
|
|
74
76
|
readonly mediaDataPath: string | null;
|
package/dist/core/config.d.ts
CHANGED
|
@@ -32,6 +32,7 @@ export type ExplorerConfigInput = {
|
|
|
32
32
|
readonly documentStyles?: readonly ExplorerDocumentStyle[];
|
|
33
33
|
readonly defaultDocumentStyle?: string;
|
|
34
34
|
readonly mermaidModifier?: PanZoomModifier;
|
|
35
|
+
readonly documentFontFamily?: string;
|
|
35
36
|
readonly iframeHosts?: readonly string[];
|
|
36
37
|
readonly appOrigins?: readonly string[];
|
|
37
38
|
readonly mediaDataPath?: string;
|
|
@@ -69,6 +70,7 @@ export type ExplorerConfig = {
|
|
|
69
70
|
readonly documentStyles: readonly ExplorerDocumentStyle[];
|
|
70
71
|
readonly defaultDocumentStyle: string;
|
|
71
72
|
readonly mermaidModifier: PanZoomModifier | undefined;
|
|
73
|
+
readonly documentFontFamily: string | undefined;
|
|
72
74
|
readonly iframeHosts: readonly string[];
|
|
73
75
|
readonly appOrigins: readonly string[];
|
|
74
76
|
readonly mediaDataPath: string | null;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { accessFailureResponse as rt } from "@aiquants/auth-core";
|
|
2
2
|
import { crossOriginRefusal as ke, NO_CROSS_ORIGIN_NAVIGATION as Te } from "@aiquants/request-isolation";
|
|
3
3
|
import { redirect as Fe, data as Ue } from "react-router";
|
|
4
|
-
import { t as cr, b as tt, w as nt, o as st, f as ot, g as at, i as it, h as ct, e as dt, j as ut, p as lt, k as dr } from "./location-
|
|
4
|
+
import { t as cr, b as tt, w as nt, o as st, f as ot, g as at, i as it, h as ct, e as dt, j as ut, p as lt, k as dr } from "./location-DFfbnUZ9.js";
|
|
5
5
|
import { h as ur, j as ft, k as se, s as pt, b as ht, m as wt, n as mt, o as yt, p as gt, E as lr, q as ee, t as bt, u as Et, i as F, v as kt, w as Tt, x as Rt, y as Ot, z as vt, f as xt, A as fr, B as At, C as ce, F as St, G as It, H as Pt, I as _t, J as M, K as pr, L as Dt, g as V, e as He, N as $t, O as Nt } from "./ownUrls-DD0cSCsF.js";
|
|
6
6
|
import { d as x, i as Lt } from "./describeValue-CLlVRO8d.js";
|
|
7
7
|
import { c as jt, i as Mt, M as Ct } from "./lru-DC8GBmkX.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const Xr=require("@aiquants/auth-core"),J=require("@aiquants/request-isolation"),ee=require("react-router"),$=require("./location-DFXJSMit.cjs"),m=require("./ownUrls-BTPGNhBt.cjs"),x=require("./describeValue-Ccvhbt36.cjs"),Ee=require("./lru-SGmUyBQU.cjs"),tr="application/octet-stream",nr="application/pdf",Hr=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",nr]),Ce="default-src 'none'; media-src 'self'; style-src 'unsafe-inline'",se=Object.freeze({sandboxed:`${Ce}; sandbox`,mediaDocument:`${Ce}; sandbox allow-same-origin`}),Me=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,Br=/^[\t\n\r ]+|[\t\n\r ]+$/gu,me=/^[\t ]+|[\t ]+$/gu,Yr=e=>{const r=[];let t="",o=0;for(;;){for(;o<e.length&&e[o]!=='"'&&e[o]!==",";)t+=e[o],o+=1;if(o<e.length&&e[o]==='"'){const c=o;for(o+=1;o<e.length&&e[o]!=='"';)o+=e[o]==="\\"?2:1;if(o=Math.min(o+1,e.length),t+=e.slice(c,o),o<e.length)continue}if(r.push(t.replace(me,"")),t="",o>=e.length)return r;o+=1}},Gr=e=>{const r=e.replace(Br,""),t=r.indexOf("/");if(t<0)return null;const o=r.slice(0,t),c=r.indexOf(";",t+1),d=r.slice(t+1,c<0?r.length:c).replace(/[\t\n\r ]+$/u,"");return Me.test(o)&&Me.test(d)?`${o}/${d}`.toLowerCase():null},Wr=e=>{let r=null;for(const t of Yr(e)){const o=Gr(t);o!==null&&o!=="*/*"&&(r=o)}return r},Jr=/['()*]/gu,sr=e=>encodeURIComponent(e).replace(Jr,r=>`%${r.charCodeAt(0).toString(16).toUpperCase()}`),be=Object.freeze({"Cache-Control":"private, max-age=60, stale-while-revalidate=600, no-transform",Vary:"Cookie"}),or=(e,r)=>{const t=Wr(e),o=t!==null&&Hr.has(t),c=o&&(t.startsWith("audio/")||t.startsWith("video/"));return{contentType:t===null?tr:t,inline:o,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`${o?"inline":"attachment"}; filename*=UTF-8''${sr(r)}`,...t===nr?{}:{"Content-Security-Policy":c?se.mediaDocument:se.sandboxed},"Cross-Origin-Resource-Policy":"same-origin"}}},ne=64*1024,ar=e=>`text/plain; charset=${e}`,Kr=e=>({"X-Content-Type-Options":"nosniff","Content-Disposition":`inline; filename*=UTF-8''${sr(e)}`,"Content-Security-Policy":se.sandboxed,"Cross-Origin-Resource-Policy":"same-origin"}),Qr=(e,r)=>`${r===null?"":r};${e}`,Zr=/^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu,re=Object.freeze({kind:"whole"}),ze=Object.freeze({kind:"unsatisfiable"}),ir=(e,r,t,o)=>{const c=e.get("Range");if(c===null)return re;const d=e.get("If-Range");if(d!==null&&d!==t)return re;const f=Zr.exec(c);if(f===null)return re;const[,p,h,k]=f;if(k!==void 0){const T=Number(k);if(T===0)return ze;const A=Math.max(0,r-T);return Ue(A,r-A,o)}const y=Number(p),b=h===""?Number.POSITIVE_INFINITY:Number(h);return b<y?re:y>=r?ze:Ue(y,Math.min(b,r-1)-y+1,o)},Ue=(e,r,t)=>({kind:"partial",range:{offset:e,length:t===null?r:Math.min(r,t)}}),Ve="W/",qr=e=>{const r=[];let t=0,o=!1;for(let c=0;c<e.length;c+=1)e[c]==='"'?o=!o:e[c]===","&&!o&&(r.push(e.slice(t,c).replace(me,"")),t=c+1);return r.push(e.slice(t).replace(me,"")),r},Fe=e=>e.startsWith(Ve)?e.slice(Ve.length):e,Te=(e,r)=>{if(e===null)return!1;const t=qr(e);if(t.length===1&&t[0]==="*")return!0;const o=Fe(r);return t.some(c=>Fe(c)===o)},et=(e,r)=>{let t=r;return e.pipeThrough(new TransformStream({transform:(o,c)=>{const d=o.byteLength>t?o.subarray(0,t):o;t-=d.byteLength,c.enqueue(d),t===0&&c.terminate()},flush:o=>{t>0&&o.error(new RangeError("[markdown-explorer] the asset ended before its declared length"))}}))},Y=(e,r,t,o,c)=>(c!==null&&t.set("Content-Length",String(c)),{head:e.method.toUpperCase()==="HEAD",status:r,headers:t,range:o,length:c}),q=({head:e,status:r,headers:t,range:o,length:c})=>e?{kind:"respond",response:new Response(null,{status:r,headers:t})}:{kind:"stream",status:r,headers:t,range:o,length:c},oe=async(e,r)=>{if(e.kind==="respond")return e.response;const t=await r(e.range);return new Response(e.length===null?t:et(t,e.length),{status:e.status,headers:e.headers})},cr=(e,r)=>{const t=new Headers(e);for(const[o,c]of Object.entries({"Accept-Ranges":"bytes","Content-Range":`bytes */${r}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff"}))t.set(o,c);return new Response(null,{status:416,headers:t})},ur=(e,r,t,o)=>{const c=`"${r.version}"`,d=or(r.contentType,r.name),f=new Headers(t);for(const[k,y]of Object.entries({...d.headers,...be,ETag:c}))f.set(k,y);if(Te(e.headers.get("If-None-Match"),c))return{kind:"respond",response:new Response(null,{status:304,headers:f})};if(f.set("Content-Type",d.contentType),r.size===null)return q(Y(e,200,f,null,null));if(r.size===0)return f.set("Content-Length","0"),{kind:"respond",response:new Response(null,{status:200,headers:f})};f.set("Accept-Ranges","bytes");const p=ir(e.headers,r.size,c,o);if(p.kind==="unsatisfiable")return{kind:"respond",response:cr(t,r.size)};if(p.kind==="whole")return q(Y(e,200,f,null,r.size));const{range:h}=p;return f.set("Content-Range",`bytes ${h.offset}-${h.offset+h.length-1}/${r.size}`),q(Y(e,206,f,h,h.length))},rt=async(e,r,t,o)=>oe(ur(e,r,t,o),c=>r.open(c)),tt=(e,r)=>{const t=new Uint8Array(r);let o=0;for(const c of e){if(o===r)break;const d=c.subarray(0,r-o);t.set(d,o),o+=d.byteLength}return t},nt=(e,r,t)=>new ReadableStream({start:o=>{for(const c of e)o.enqueue(c);r&&o.close()},pull:async o=>{const{done:c,value:d}=await t.read();c?o.close():o.enqueue(d)},cancel:o=>t.cancel(o)},{highWaterMark:0}),dr=async(e,r,t)=>{const o=e.getReader(),c=r===null?ne:Math.min(r,ne),d=r===null?c+1:c,f=[];let p=0,h=!1;try{for(;p<d;){const{done:b,value:T}=await o.read();if(b){h=!0;break}f.push(T),p+=T.byteLength}if(h&&r!==null&&p<c)throw new RangeError("[markdown-explorer] the asset ended before its declared length");const k=r===null?h:r<=ne;return{encoding:$.textEncodingOf(tt(f,Math.min(p,c)),k,t),body:nt(f,h,o)}}catch(k){throw o.cancel(k).catch(()=>{}),k}},lr=async(e,r)=>{const t=await dr(await e.open(e.size===null?null:{offset:0,length:Math.min(e.size,ne)}),e.size,r);return t.body.cancel().catch(()=>{}),t.encoding},fr=(e,r,t,o,c)=>{const d=`"${Qr(r.version,o)}"`,f=new Headers(t);for(const[k,y]of Object.entries({...Kr(r.name),...be,ETag:d}))f.set(k,y);if(Te(e.headers.get("If-None-Match"),d))return{kind:"respond",response:new Response(null,{status:304,headers:f})};if(r.size===0)return f.set("Content-Type",ar($.textEncodingOf(new Uint8Array(0),!0,o))),f.set("Content-Length","0"),{kind:"respond",response:new Response(null,{status:200,headers:f})};if(r.size===null)return{kind:"needs-encoding",selection:Y(e,200,f,null,null)};f.set("Accept-Ranges","bytes");const p=ir(e.headers,r.size,d,c);if(p.kind==="unsatisfiable")return{kind:"respond",response:cr(t,r.size)};if(p.kind==="whole")return{kind:"needs-encoding",selection:Y(e,200,f,null,r.size)};const{range:h}=p;return f.set("Content-Range",`bytes ${h.offset}-${h.offset+h.length-1}/${r.size}`),{kind:"needs-encoding",selection:Y(e,206,f,h,h.length)}},ye=(e,r)=>{const t=new Headers(e.headers);return t.set("Content-Type",ar(r)),q({...e,headers:t})},st=async(e,r,t,o,c)=>{const d=fr(e,r,t,o,c);if(d.kind==="respond")return d.response;const{selection:f}=d;if(f.head||f.range!==null)return oe(ye(f,await lr(r,o)),h=>r.open(h));const p=await dr(await r.open(null),r.size,o);return oe(ye(f,p.encoding),async()=>p.body)},ot=e=>`workbook;${e}`,at=async(e,r,t)=>{const o=`"${ot(r.version)}"`,c=or(tr,r.name),d=new Headers(t);for(const[f,p]of Object.entries({...c.headers,...be,ETag:o}))d.set(f,p);return Te(e.headers.get("If-None-Match"),o)?new Response(null,{status:304,headers:d}):(d.set("Content-Type",c.contentType),oe(q(Y(e,200,d,null,r.size)),f=>r.open(f)))},it=Object.freeze({"Cache-Control":"private, no-store","Referrer-Policy":"no-referrer"}),ct=(e,r)=>{const t=new Headers(r);for(const[o,c]of Object.entries(it))t.set(o,c);return t.set("Location",e),new Response(null,{status:302,headers:t})},fe=(e,r)=>{const t=new AbortController,o=r(AbortSignal.any([e.signal,t.signal]));return new Promise(c=>{let d;const f=setTimeout(()=>{c(e.late),d=setTimeout(()=>t.abort(),e.handOverMs)},e.timeoutMs),p=()=>{clearTimeout(f),clearTimeout(d)};o.then(h=>{p(),c(h)},()=>{p(),c(e.late)})})},ut=Object.freeze({error:(e,r)=>{console.error(e,r)}}),pr=Symbol.for("@aiquants/markdown-explorer:ExplorerError");class dt extends Error{reason;code;constructor(r,t={}){if(!m.isExplorerFailureReason(r))throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${x.describeValue(r)}`);if(t.code!==void 0&&!m.isExplorerFailureCode(t.code))throw new RangeError(`[markdown-explorer] an ExplorerError code must be 1 to 64 lowercase letters, digits or hyphens; got ${x.describeValue(t.code)}`);super(`[markdown-explorer] ${r}`,t.cause===void 0?void 0:{cause:t.cause}),this.name="ExplorerError",this.reason=r,this.code=t.code,Object.defineProperty(this,pr,{value:!0})}}const lt=e=>e instanceof Error&&Object.hasOwn(e,pr)&&m.isExplorerFailureReason(e.reason),ft=e=>typeof e=="object"&&e!==null&&e.name==="AbortError",Re=(e,r,t)=>{try{e.error(r,t)}catch(o){console.error("[markdown-explorer] the logger threw while reporting a failure",{operation:t.operation,error:o})}},N=(e,r)=>Re(e,`[markdown-explorer] ${r.operation} failed`,r),pt=(e,r)=>Re(e,`[markdown-explorer] ${r.operation} left out an entry`,r),Z=(e,r)=>Re(e,`[markdown-explorer] ${r.operation} refused a path the deny rules match`,{...r,error:new RangeError("[markdown-explorer] the path matches a deny rule")}),Xe=(e,r)=>{e===null||typeof e!="object"&&typeof e!="function"||Promise.resolve(e).then(void 0,r)},v=(e,r,t,o)=>lt(e)?m.failureOf(e.reason,e.code):(ft(e)||t.aborted||N(o,{...r,error:e}),{reason:"failed"}),He=2*1024*1024,Be=256*1024*1024,ht=async(e,r)=>{const t=e.getReader(),o=new Uint8Array(r);let c=0;for(;c<r;){const{done:d,value:f}=await t.read();if(d)return o.subarray(0,c);const p=f.subarray(0,r-c);o.set(p,c),c+=p.byteLength}return t.cancel().catch(()=>{}),o},wt=async(e,r,t)=>{if(e.size===0)return{text:"",truncated:!1};const o=e.size!==null&&e.size>r,c=e.size===null?r+1:Math.min(e.size,r),d=await ht(await e.open(o?{offset:0,length:r}:null),c);if(e.size!==null&&d.byteLength<c)throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");const f=o||d.byteLength>r,p=f?d.subarray(0,r):d,h=$.decodeTextLeniently(p,!f,t);return h.includes("\0")?null:{text:h,truncated:f}},ae=e=>({result:e,json:JSON.stringify(e)}),pe=Object.freeze(ae(Object.freeze({status:"error",failure:Object.freeze({reason:"failed"})}))),mt=e=>e.status==="ok"&&e.entries.length>0,yt=({ttlMs:e,maxEntries:r,maxBytes:t,now:o})=>{const c=Ee.createLruCache(r,{max:t,of:(y,b)=>2*b.tree.json.length}),d=new Map,f=new Map,p=(y,b)=>{const T=new AbortController,A={waiters:0,superseded:!1,started:!1,loadTree:b},I=f.get(y),V=(M,ce)=>{const K=ae(M);return!(A.superseded||T.signal.aborted)&&mt(M)&&c.set(y,{tree:K,loadedAt:ce}),K},U=(async()=>{if(I!==void 0&&await I,T.signal.aborted)return pe;const M=o();return A.started=!0,V(await A.loadTree(T.signal,M),M)})().finally(()=>{d.get(y)===X&&d.delete(y)}),X={promise:U,controller:T,state:A};d.set(y,X);const j=U.then(()=>{},()=>{});return f.set(y,j),j.then(()=>{f.get(y)===j&&f.delete(y)}),X},h=(y,b,T)=>{b.state.waiters+=1;const A=()=>{b.state.waiters-=1,!(b.state.waiters>0)&&(d.get(y)===b&&d.delete(y),b.controller.abort())};return T.addEventListener("abort",A,{once:!0}),b.promise.finally(()=>{T.removeEventListener("abort",A)})},k=y=>{c.delete(y);const b=d.get(y);b?.state.started&&(b.state.superseded=!0,d.delete(y))};return{load:(y,b,T)=>{if(b.aborted)return Promise.resolve(pe);const A=c.get(y);if(A!==void 0){if(o()-A.loadedAt<e)return Promise.resolve(A.tree);c.delete(y)}const I=d.get(y);return h(y,I===void 0?p(y,T):I,b)},refresh:(y,b,T)=>{if(b.aborted)return Promise.resolve(pe);k(y);const A=d.get(y);return A===void 0?h(y,p(y,T),b):(A.state.loadTree=T,h(y,A,b))},forget:k}},gt=e=>({load:(r,t,o)=>o(t,e()).then(ae),refresh:(r,t,o)=>o(t,e()).then(ae),forget:()=>{}}),E=e=>{throw new TypeError(`[markdown-explorer] ${e}`)},Et=e=>{if(e===null||typeof e!="object")return null;const{name:r,path:t}=e;return typeof r!="string"||typeof t!="string"?null:r===""?{path:t,reason:"an empty name"}:m.isAcceptableDocumentPath(t)?null:{path:t,reason:"a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)"}},bt=(e,r,t,o)=>{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 ${x.describeValue(e)}`);const c=new Set;for(const d of e){if(typeof d!="string"||!m.isAcceptableDocumentPath(d))throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");if(t.deniesPath(d))throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");if(!o(d))throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");if(d===r)throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");if(c.has(d))throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");c.add(d)}return Object.freeze([...c])},Tt=(e,r,t,o,c)=>{const d=new Set,f=h=>{if(!Array.isArray(h))return E("a source returned entries that are not an array");const k=[];for(const y of h){const b=p(y);b!==null&&k.push(b)}return k},p=h=>{const k=Et(h);if(k!==null)return o(k),null;const y=m.entryViolation(h);if(y!==null)return E(y);const b=h;if(d.has(b))return E("a source returned entries that contain themselves");const{name:T,path:A,type:I,mimeType:V,modifiedAt:F,children:U,lazy:X}=b;if(r.deniesName(T)||r.deniesPath(A))return null;if(!c(A))return o({path:A,reason:"a path outside the source's boundary"}),null;const j={name:T,path:A,...V===void 0?{}:{mimeType:V},...F===void 0?{}:{modifiedAt:F}};if(I==="file")return{...j,type:I};if(X===!0)return t?{...j,type:I,lazy:!0,children:[]}:E("a lazy directory came from a source without a children function");if(U===void 0)return{...j,type:I};d.add(b);const M=f(U);return d.delete(b),{...j,type:I,children:M}};return f(e)},Rt=/^[\x21\x23-\x7E]{1,256}$/u,hr=e=>typeof e=="string"&&Rt.test(e),kt=new Set(["text","image","media","spreadsheet","file"]),Ot=e=>typeof e=="string"&&kt.has(e),At=(e,r,t)=>{if(e!==null&&typeof e=="object"){const d=e,{kind:f}=d;if(Ot(f)){if(Object.hasOwn(d,"url"))return E(`a ${f} document carries its version, not a url`);if(typeof d.name!="string")return E("a document needs a name string");if(!hr(d.version))return E(`a ${f} document needs a version of 1 to 256 visible ASCII characters other than '"'`);const p=r(d.version);switch(f){case"image":{const{imageType:h}=d;return m.isExplorerImageType(h)?{kind:f,name:d.name,url:p,imageType:h}:E(`unknown image type ${x.describeValue(h)}`)}case"file":return{kind:f,name:d.name,url:p};case"media":{const{mediaType:h}=d;return m.isExplorerMediaType(h)?{kind:f,name:d.name,url:p,mediaType:h}:E(`unknown media type ${x.describeValue(h)}`)}case"text":{const{text:h,truncated:k,lang:y}=d;return typeof h!="string"||typeof k!="boolean"?E("a text document needs text and truncated"):m.isExplorerDocumentLang(y)?{kind:f,name:d.name,text:h,truncated:k,lang:y,url:p}:E(m.documentLangRefusal(f,y))}case"spreadsheet":{const h=m.spreadsheetFieldsViolation(d);if(h!==null)return E(h);const{format:k,firstSheetText:y,edit:b}=d;return{kind:f,name:d.name,url:p,format:k,firstSheetText:y,edit:vt(b)}}}}}const o=m.documentViolation(e);if(o!==null)return E(o);const c=e;switch(c.kind){case"failure":{const{reason:d,code:f}=c.failure;return{kind:"failure",failure:m.failureOf(d,f)}}case"markdown":return c.headings.length>m.EXPLORER_MAX_HEADINGS?{kind:"failure",failure:m.failureOf("too-large")}:(c.edit?.kind==="inline"||c.edit?.kind==="draft")&&!t?E(`a markdown document offers ${c.edit.kind} editing, but the server has no edit ports`):{kind:"unsanitized-markdown",name:c.name,html:c.htmlContent,headings:c.headings.map(({text:d,depth:f,id:p})=>({text:d,depth:f,id:p})),lang:c.lang,edit:xt(c.edit)}}},xt=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}}},vt=e=>e===null?null:{kind:"external",href:e.href},ie=(e,r,t)=>typeof e!="string"?E(`${t} needs a text string`):e.includes("\0")?E(`${t} holds NUL, which no text editor can keep`):new TextEncoder().encode(e).byteLength>r?E(`${t} is over editMaxBytes (${r} bytes); refuse a longer source with ExplorerError "too-large"`):e,wr=e=>m.isRootRelativeUrl(e.href)?{kind:"grant",href:e.href}:E("a grant needs a root-relative href"),_t=(e,r)=>{if(e===null||typeof e!="object")return E("an edit source must be an object");const t=e;return t.kind==="grant"?wr(t):t.kind==="draft"?{kind:"draft",text:ie(t.text,r,"a draft source")}:t.kind!=="edit"?E(`an edit source's kind must be "edit", "draft" or "grant"`):m.isExplorerEditToken(t.version)?typeof t.history!="boolean"?E("an edit source needs history"):{kind:"edit",text:ie(t.text,r,"an edit source"),version:t.version,history:t.history}:E("an edit source needs a version of 1 to 1024 characters")},St=(e,r)=>{if(e===null||typeof e!="object")return E("a save result must be an object");const t=e;switch(t.kind){case"grant":return wr(t);case"saved":return m.isExplorerEditToken(t.version)?{kind:"saved",version:t.version}:E("a saved result needs a version of 1 to 1024 characters");case"conflict":return m.isExplorerEditToken(t.version)?{kind:"conflict",version:t.version,text:ie(t.text,r,"a conflict's current text")}:E("a conflict needs the current version of 1 to 1024 characters");default:return E(`a save result's kind must be "saved", "conflict" or "grant"`)}},Pt=e=>{if(e===null||typeof e!="object")return E("a preview must be an object");const{htmlContent:r,headings:t}=e;if(typeof r!="string"||!Array.isArray(t))return E("a preview needs htmlContent and headings");if(t.length>m.EXPLORER_MAX_HEADINGS)return{kind:"failure",failure:m.failureOf("too-large")};for(const o of t){const c=m.headingViolation(o);if(c!==null)return E(c)}return{html:r,headings:t.map(({text:o,depth:c,id:d})=>({text:o,depth:c,id:d}))}},It=e=>{if(!Array.isArray(e))return E("revisions must be an array");const r=new Set;return e.map(t=>{const o=m.revisionViolation(t);if(o!==null)return E(o);const{id:c,modifiedAt:d,size:f,author:p,kept:h,current:k}=t;return r.has(c)?E(`two revisions share the id ${x.describeValue(c)}`):(r.add(c),{id:c,modifiedAt:d,size:f,author:p,kept:h,current:k})})},Dt=(e,r)=>ie(e,r,"a revision"),ge=e=>{if(e===null||typeof e!="object")return E("an asset file must be an object");const{name:r,contentType:t,size:o,version:c,open:d,kind:f,bridge:p}=e;if(f!==void 0)return E(f==="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")');if(typeof r!="string"||r==="")return E("an asset file needs a non-empty name");if(typeof t!="string")return E("an asset file needs a contentType string ('' when unknown)");if(o!==null&&!(typeof o=="number"&&Number.isSafeInteger(o)&&o>=0))return E("an asset file's size must be null or a non-negative safe integer");if(!hr(c))return E(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`);if(typeof d!="function")return E("an asset file needs an open function");const h={name:r,contentType:t,size:o,version:c,open:d};return Object.freeze(p===void 0?h:{...h,bridge:Lt(p)})},Lt=e=>{if(e===null||typeof e!="object")return E("an asset file's bridge must be an object when present");const{uri:r,storageVersion:t,readFailure:o}=e;return typeof r!="string"||r===""?E("an asset file's bridge needs a non-empty uri"):t!==null&&(typeof t!="string"||t==="")?E("an asset file's bridge needs a storageVersion that is a non-empty string, or null when the storage keeps none"):typeof o!="function"?E("an asset file's bridge needs a readFailure function"):Object.freeze({uri:r,storageVersion:t,readFailure:o})},Ye=e=>{if(e===null||typeof e!="object"||e.kind!=="redirect")return ge(e);const{url:r}=e;if(typeof r!="string"||!URL.canParse(r))return E("an asset redirect needs an absolute https URL");const t=new URL(r);return t.protocol!=="https:"||t.username!==""||t.password!==""?E("an asset redirect's URL must be https and carry no credentials"):Object.freeze({kind:"redirect",url:t.href})},Nt=e=>Array.isArray(e)?e.map(r=>{if(r===null||typeof r!="object")return E("a notice must be an object");const{id:t,tone:o,title:c,body:d,action:f}=r;if(typeof t!="string"||t===""||typeof c!="string")return E("a notice needs an id and a title");if(!m.isExplorerNoticeTone(o))return E(`unknown notice tone ${x.describeValue(o)}`);if(d!==void 0&&typeof d!="string")return E("a notice body must be a string");const h={id:t,tone:o,title:c,...d===void 0?{}:{body:d}};if(f===void 0)return h;if(f===null||typeof f!="object")return E("a notice action must be an object");const{label:k,href:y}=f;return typeof k!="string"||!m.isAcceptableUrl(y,m.EXPLORER_LINK_PROTOCOLS)?E("a notice action needs a label and an http(s), mailto or relative href"):{...h,action:{label:k,href:y}}}):E("notices must be an array"),$t=4e3,te=Object.freeze({ttlMs:3e5,maxEntries:64,maxBytes:64*1024*1024}),mr="private, no-store",jt=Object.freeze({"Content-Type":"application/json; charset=utf-8","Cache-Control":mr,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; frame-ancestors 'none'; sandbox","Cross-Origin-Resource-Policy":"same-origin"}),he=Object.freeze([]),Ct=Object.freeze({status:"ok",source:null,ancestors:null}),Ge=Object.freeze(["contains","confirm"]),We=Object.freeze({readOnly:!1}),Mt=Object.freeze({readOnly:!0}),zt=new Set(["file","text","workbook"]),Ut=new Set(["file","text"]),Vt=Object.freeze({status:"error",failure:Object.freeze({reason:"invalid"})}),P=(e,r,t)=>{if(!(t&&r===void 0)&&typeof r!="function")throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${x.describeValue(r)}`)},B=(e,r,t)=>{if(typeof r!="number")throw new TypeError(`[markdown-explorer] ${e} must be a number; got ${x.describeValue(r)}`);if(!Number.isSafeInteger(r)||r<=0||r>t)throw new RangeError(`[markdown-explorer] ${e} must be an integer in 1..${String(t)}; got ${x.describeValue(r)}`);return r},Ft=e=>{if(e===null||typeof e!="object"||!Object.isFrozen(e))throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");return $.revalidateExplorerConfig(e)},we=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)")}},Je=e=>e instanceof Response?new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`):e,Xt=(e,r)=>{if(!x.isPlainObject(r))throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);for(const t of Object.keys(r))if(!Ge.includes(t))throw new RangeError(`[markdown-explorer] ${e}.boundary.${t} is not an option; expected ${Ge.join(", ")}`);P(`${e}.boundary.contains`,r.contains,!1),P(`${e}.boundary.confirm`,r.confirm,!0)},Ht=e=>{if(!Array.isArray(e))throw new TypeError("[markdown-explorer] sources must be an array");const r=e;if(r.length===0)throw new RangeError("[markdown-explorer] sources must hold at least one source");const t=new Set;for(const[o,c]of r.entries()){if(c===null||typeof c!="object")throw new TypeError(`[markdown-explorer] sources[${String(o)}] must be an object`);const{id:d,label:f,boundary:p,tree:h,children:k,ancestors:y,cacheScope:b}=c;if(!$.isExplorerSourceId(d))throw new RangeError(`[markdown-explorer] sources[${String(o)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${x.describeValue(d)}`);const T=`source ${x.describeValue(d)}`;if(t.has(d))throw new RangeError(`[markdown-explorer] source ids must be unique; ${x.describeValue(d)} repeats at sources[${String(o)}]`);if(t.add(d),typeof f!="string"&&typeof f!="function")throw new TypeError(`[markdown-explorer] ${T}.label must be a string or a function`);if(typeof f=="string"&&f.trim()==="")throw new RangeError(`[markdown-explorer] ${T}.label must not be blank`);if(Xt(T,p),P(`${T}.tree`,h,!1),P(`${T}.children`,k,!0),P(`${T}.ancestors`,y,!0),b!==void 0&&b!=="principal"&&b!=="shared")throw new RangeError(`[markdown-explorer] ${T}.cacheScope must be "principal" or "shared"; got ${x.describeValue(b)}`)}return r},Bt=e=>{if(e===!1)return!1;if(e===void 0)return te;if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] treeCache must be { ttlMs, maxEntries, maxBytes } or false");const{ttlMs:r,maxEntries:t,maxBytes:o}=e;return{ttlMs:r===void 0?te.ttlMs:B("treeCache.ttlMs",r,Number.MAX_SAFE_INTEGER),maxEntries:t===void 0?te.maxEntries:B("treeCache.maxEntries",t,Number.MAX_SAFE_INTEGER),maxBytes:o===void 0?te.maxBytes:B("treeCache.maxBytes",o,Number.MAX_SAFE_INTEGER)}},Ke=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] authenticate must resolve to { status, ... }");const{status:r}=e;if(r!=="signed-in"&&r!=="signed-out"&&r!=="forbidden")throw new TypeError(`[markdown-explorer] authenticate resolved to an unknown status ${x.describeValue(r)}`);return e},Yt=(e,r)=>{if(!(r instanceof Response))throw new TypeError(`[markdown-explorer] ${e} must return a Response`);return r},Qe=(e,r)=>{if(typeof r!="string"||r==="")throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");const t=e(r);if(!Ee.isExplorerScope(t))throw new TypeError("[markdown-explorer] the platform's scope must be 22 base64url characters");return t},Gt=(e,r)=>{try{return e(r)}catch(t){return t}},Wt=(e,r)=>{const t=e(r);if(t!==void 0&&typeof t!="string")throw new TypeError(`[markdown-explorer] readSettings must return a string or undefined; got ${t===null?"null":typeof t}`);return t},Jt=e=>e.view==="multi"?e.docs:e.doc===null?[]:[e.doc],z=(e,r)=>{const t=e.getAll(r),[o]=t;return t.length===1&&o!==void 0&&o!==""?o:null},S=(e,r,t,o={})=>{const c=new Headers(t);for(const[d,f]of Object.entries({...jt,...o}))c.set(d,f);return new Response(r,{status:e,headers:c})},O=(e,r,t)=>S(m.EXPLORER_FAILURE_STATUS[e.reason],JSON.stringify({failure:e}),r,t),Kt=new Set(["refresh","save","preview","issue-id"]),Qt=new Set(["issue-id","resolve-id"]),Ze=4,Zt=new Set(["edit","save","preview","revisions","revision"]),qe=(e,r)=>{const t=Kt.has(r)?["POST"]:["GET","HEAD"];return t.includes(e.method.toUpperCase())?null:S(405,JSON.stringify({failure:{reason:"invalid"}}),void 0,{Allow:t.join(", ")})},er=e=>e.headers.get(m.EXPLORER_PROOF_HEADER)===m.EXPLORER_REFRESH_PROOF&&J.crossOriginRefusal(e,J.NO_CROSS_ORIGIN_NAVIGATION)===void 0,qt=e=>e.headers.get(m.EXPLORER_PROOF_HEADER)===m.EXPLORER_EDIT_PROOF&&J.crossOriginRefusal(e,J.NO_CROSS_ORIGIN_NAVIGATION)===void 0,en=e=>e.headers.get(m.EXPLORER_PROOF_HEADER)===m.EXPLORER_DOCUMENT_ID_PROOF&&J.crossOriginRefusal(e,J.NO_CROSS_ORIGIN_NAVIGATION)===void 0,rn=async(e,r)=>{const[t,...o]=(e.headers.get("Content-Type")??"").split(";").map(T=>T.trim().toLowerCase()),c=o.find(T=>T.startsWith("charset="));if(t!==m.EXPLORER_DRAFT_MEDIA_TYPE||c!==void 0&&c!=="charset=utf-8")return{status:"error",failure:{reason:"invalid"}};const d=Number(e.headers.get("Content-Length")??"0");if(Number.isFinite(d)&&d>r)return{status:"error",failure:{reason:"too-large"}};if(e.body===null)return{status:"ok",text:""};const f=e.body.getReader(),p=[];let h=0;for(;;){const{done:T,value:A}=await f.read();if(T)break;if(h+=A.byteLength,h>r)return await f.cancel(),{status:"error",failure:{reason:"too-large"}};p.push(A)}const k=new Uint8Array(h);let y=0;for(const T of p)k.set(T,y),y+=T.byteLength;let b;try{b=new TextDecoder("utf-8",{fatal:!0}).decode(k)}catch{return{status:"error",failure:{reason:"invalid"}}}return b.includes("\0")?{status:"error",failure:{reason:"invalid"}}:{status:"ok",text:b}},tn=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 r=e;for(const t of["source","save","preview","revisions","revision"])P(`edit.${t}`,r[t],!1);return e},nn=(e,r)=>{if(e.documentIds===null!=(r===void 0))throw new TypeError("[markdown-explorer] documentIds in defineExplorerConfig and the server's documentIds ports go together; give both or neither");if(r===void 0)return;if(r===null||typeof r!="object")throw new TypeError("[markdown-explorer] documentIds must be an object of the registry's ports");const t=r;for(const o of["issue","resolve"])P(`documentIds.${o}`,t[o],!1);return r},sn=e=>{if(e===null||typeof e!="object")return null;const{kind:r,id:t}=e;return r==="issued"||r==="taken"?{kind:r}:r==="existing"&&m.isCanonicalDocumentId(t)?{kind:r,id:t}:null},on=e=>{if(e===null||typeof e!="object")return;const{kind:r,path:t}=e;return r==="unbound"?null:r==="bound"&&typeof t=="string"&&$.hasDocumentUrl(t)?t:void 0},rr=(e,r)=>e.status==="ok"?S(200,JSON.stringify(e),r):O(e.failure,r),an=({parentHeaders:e,loaderHeaders:r,errorHeaders:t})=>{const o=new Headers,c=t===void 0?[e,r]:[e,r,t];for(const d of c)for(const[f,p]of d)f!=="set-cookie"&&o.set(f,p);return o},cn=(e,r)=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the server configuration must be an object");const t=Ft(e.config),o=r.prepareScope();P("authenticate",e.authenticate,!1),P("principalKey",e.principalKey,!1),P("document",e.document,!1),P("asset",e.asset,!1),P("signedOutPage",e.signedOutPage,!1),P("notices",e.notices,!0),P("onTreeRefreshed",e.onTreeRefreshed,!0),P("readSettings",e.readSettings,!1);const c=Ht(e.sources),d=$.withExplorerSources(t,c.map(n=>n.id)),f=e.logger;if(f!==void 0&&(f===null||typeof f!="object"||typeof f.error!="function"))throw new TypeError("[markdown-explorer] logger must be an object with an error function");const p=e.logger===void 0?ut:e.logger,h=m.resolvePathRules(e.deny),k=e.deferredTimeoutMs===void 0?$t:B("deferredTimeoutMs",e.deferredTimeoutMs,Ee.MAX_TIMER_MILLISECONDS),y=e.textMaxBytes===void 0?He:B("textMaxBytes",e.textMaxBytes,Be),b=tn(e.edit);if(b===void 0&&e.editMaxBytes!==void 0)throw new TypeError("[markdown-explorer] editMaxBytes needs the edit ports");const T=e.editMaxBytes===void 0?He:B("editMaxBytes",e.editMaxBytes,Be),A=nn(t,e.documentIds),I=Bt(e.treeCache),V=()=>Date.now(),F=I===!1?gt(V):yt({...I,now:V}),U=r.createSanitizer({options:e.sanitizer,maxPanels:t.multiView.maxPanels,iframeHosts:t.iframeHosts,dataPath:t.dataPath,ownUrls:$.ownUrlsOf(t)}),X=e.readSettings,j=e.assetMaxRangeBytes===null?null:B("assetMaxRangeBytes",e.assetMaxRangeBytes,Number.MAX_SAFE_INTEGER),M=new Map(c.map(n=>[n.id,n])),ce=$.documentStyleNames(t),{authenticate:K,principalKey:ke,signedOutPage:yr,onTreeRefreshed:Oe}=e,gr=(n,a)=>{if(typeof n.label=="string")return n.label;const s=n.label(a);if(typeof s!="string"||s.trim()==="")throw new TypeError(`[markdown-explorer] the label of source ${x.describeValue(n.id)} must be a non-blank string`);return s},ue=(n,a)=>n.cacheScope==="shared"?n.id:`${n.id}\0${a}`,G=(n,a)=>{const s=u=>N(p,{operation:"boundary",sourceId:n.id,path:a,error:u});let i;try{i=n.boundary.contains(a)}catch(u){return s(u),!1}return typeof i=="boolean"?i:(Xe(i,s),s(new TypeError(`[markdown-explorer] boundary.contains of source ${x.describeValue(n.id)} must return a boolean; got ${x.describeValue(i)}`)),!1)},de=async(n,a,s)=>{const{confirm:i}=n.boundary;if(i===void 0)return{status:"inside",readPath:s};let u;try{u=await i(a,s)}catch(R){return{status:"error",failure:v(R,{operation:"boundary",sourceId:n.id,path:s},a.signal,p)}}const l=R=>(N(p,{operation:"boundary",sourceId:n.id,path:s,error:new TypeError(`[markdown-explorer] boundary.confirm of source ${x.describeValue(n.id)} ${R}`)}),{status:"outside"});if(u===null||typeof u!="object")return l(`must resolve to { inside, readPath? }; got ${u===null?"null":typeof u}`);const{inside:w,readPath:g}=u;return w===!1?{status:"outside"}:w!==!0||typeof g!="string"?l("must resolve to { inside: false } or { inside: true, readPath: string }"):!m.isAcceptableDocumentPath(g)||h.deniesPath(g)?(N(p,{operation:"boundary",sourceId:n.id,path:s,error:new RangeError(`[markdown-explorer] boundary.confirm of source ${x.describeValue(n.id)} answered a readPath the explorer does not serve (unacceptable or denied)`)}),{status:"error",failure:{reason:"failed"}}):{status:"inside",readPath:g}},W=async(n,a)=>{const s=c.filter(l=>G(l,a));if(s.length===0)return{status:"error",failure:{reason:"forbidden"}};const i=s.find(l=>l.boundary.confirm===void 0);if(i!==void 0)return{status:"inside",readPath:a,sourceId:i.id};let u=null;for(const l of s){const w=await de(l,n,a);if(w.status==="inside")return{status:"inside",readPath:w.readPath,sourceId:l.id};w.status==="error"&&u===null&&(u=w.failure)}return{status:"error",failure:u===null?{reason:"forbidden"}:u}},Ae=async(n,a,s)=>{try{return Ye(await e.asset(n,a,s,{delivery:"file"})),null}catch(i){return v(i,{operation:"asset",path:a},n.signal,p)}},xe=async(n,a,s)=>{let i;try{i=await n.resolve(a,s)}catch(g){return{status:"error",failure:v(g,{operation:"resolve-id"},a.signal,p)}}const u=on(i);if(u===void 0)return N(p,{operation:"resolve-id",error:new TypeError('[markdown-explorer] documentIds.resolve must resolve to { kind: "unbound" } or { kind: "bound", path } with a document path that has a URL')}),{status:"error",failure:{reason:"failed"}};if(u===null)return{status:"error",failure:{reason:"not-found"}};if(h.deniesPath(u))return Z(p,{operation:"resolve-id",path:u}),{status:"error",failure:{reason:"forbidden"}};const l=await W(a,u);if(l.status==="error")return l;const w=await Ae(a,u,l.readPath);return w!==null?{status:"error",failure:w}:{status:"resolved",path:u,sourceId:l.sourceId}},Er=async(n,a,s)=>{if(h.deniesPath(s))return Z(p,{operation:"issue-id",path:s}),{status:"error",failure:{reason:"forbidden"}};const i=await W(a,s);if(i.status==="error")return i;const u=await Ae(a,s,i.readPath);if(u!==null)return{status:"error",failure:u};for(let l=0;l<Ze;l+=1){const w=m.createDocumentId(D=>crypto.getRandomValues(D));let g;try{g=await n.issue(a,s,w)}catch(D){return{status:"error",failure:v(D,{operation:"issue-id",path:s},a.signal,p)}}const R=sn(g);if(R===null)return N(p,{operation:"issue-id",path:s,error:new TypeError('[markdown-explorer] documentIds.issue must resolve to { kind: "issued" }, { kind: "existing", id } with an ID in its canonical form, or { kind: "taken" }')}),{status:"error",failure:{reason:"failed"}};if(R.kind==="issued")return{status:"ok",id:w};if(R.kind==="existing")return{status:"ok",id:R.id}}return N(p,{operation:"issue-id",path:s,error:new Error(`[markdown-explorer] documentIds.issue answered taken for ${String(Ze)} candidates in a row`)}),{status:"error",failure:{reason:"failed"}}},ve=(n,a,s)=>{const i=({path:u,reason:l})=>pt(p,{operation:s.operation,sourceId:s.sourceId,path:u,error:new TypeError(`[markdown-explorer] an entry with ${l} was left out`)});try{return{status:"ok",entries:Tt(n,h,a.children!==void 0,i,u=>G(a,u))}}catch(u){return N(p,{...s,error:u}),{status:"error",failure:{reason:"failed"}}}},br=async(n,a,s)=>{let i;try{i=await n.tree(a)}catch(l){return{status:"error",failure:v(l,{operation:"tree",sourceId:n.id},a.signal,p)}}const u=ve(i,n,{operation:"tree",sourceId:n.id});return u.status==="ok"?{status:"ok",entries:u.entries,loadedAt:s}:u},_e=(n,a,s,i)=>(u,l)=>br(n,{principal:a,request:s,signal:u,refresh:i},l),Se=(n,a,s,i,u)=>F.load(ue(n,s),u,_e(n,a,i,!1)),Tr=(n,a,s,i)=>F.refresh(ue(n,s),i.signal,_e(n,a,i,!0)),Rr=(n,a)=>{if(Oe===void 0)return;const s=i=>N(p,{operation:"refresh",sourceId:n.id,error:i});try{Xe(Oe(a),s)}catch(i){s(i)}},kr=async(n,a,s,i)=>{if(h.deniesPath(i)||!G(n,i))return{status:"error",failure:{reason:"forbidden"}};const u=await de(n,s,i);if(u.status==="outside")return{status:"error",failure:{reason:"forbidden"}};if(u.status==="error")return{status:"error",failure:u.failure};let l;try{l=await a(s,i,u.readPath)}catch(w){return{status:"error",failure:v(w,{operation:"children",sourceId:n.id,path:i},s.signal,p)}}return ve(l,n,{operation:"children",sourceId:n.id,path:i})},Pe=async(n,a,s,i)=>{const u=await de(n,s,i);if(u.status==="outside")return{status:"ok",ancestors:null};if(u.status==="error")return{status:"error",failure:u.failure};let l;try{l=await a(s,i,u.readPath,{maxDepth:t.revealDocument.maxDepth})}catch(w){return{status:"error",failure:v(w,{operation:"ancestors",sourceId:n.id,path:i},s.signal,p)}}if(Array.isArray(l)&&l.length>t.revealDocument.maxDepth)return{status:"ok",ancestors:null};try{return{status:"ok",ancestors:bt(l,i,h,w=>G(n,w))}}catch(w){return N(p,{operation:"ancestors",sourceId:n.id,path:i,error:w}),{status:"error",failure:{reason:"failed"}}}},Or=async(n,a,s,i)=>h.deniesPath(i)?{status:"error",failure:{reason:"forbidden"}}:G(n,i)?Pe(n,a,s,i):{status:"ok",ancestors:null},Ar=async(n,a,s)=>{if(h.deniesPath(s))return{status:"error",failure:{reason:"forbidden"}};for(const i of[n,...c.filter(u=>u!==n)]){if(a.signal.aborted)break;const u=i.ancestors;if(u===void 0||!G(i,s))continue;const l=await Pe(i,u,a,s);if(l.status==="ok"&&l.ancestors!==null)return{status:"ok",source:i.id,ancestors:l.ancestors}}return Ct},Ie=async(n,a,s)=>{if(h.deniesPath(s))return m.failureDocument("forbidden");const i=await W(n,s);if(i.status==="error")return{kind:"failure",failure:i.failure};let u;try{u=await e.document(n,s,i.readPath)}catch(g){return{kind:"failure",failure:v(g,{operation:"document",path:s},n.signal,p)}}let l;try{l=At(u,g=>m.explorerAssetHref(t.dataPath,s,g),b!==void 0)}catch(g){return N(p,{operation:"document",path:s,error:g}),m.failureDocument("failed")}if(l.kind!=="unsanitized-markdown")return l;const w=await U(l.html,{scope:a,signal:n.signal});return w.status==="sanitized"?{kind:"markdown",name:l.name,htmlContent:w.html,headings:l.headings,lang:l.lang,edit:l.edit}:(w.cause!==null&&N(p,{operation:"document",path:s,error:w.cause}),m.failureDocument(w.reason))},xr=async n=>{if(e.notices===void 0)return he;try{return Nt(await e.notices(n))}catch(a){return v(a,{operation:"notices"},n.signal,p),he}},De=async(n,a,s,i)=>{const u=z(a,m.EXPLORER_DATA_QUERY.path);if(u===null||!m.isAcceptableDocumentPath(u))return{status:"answered",response:O({reason:"invalid"},s)};const l=m.readExplorerAssetDisplay(a);if(l===null||!i.has(l))return{status:"answered",response:O({reason:"invalid"},s)};if(h.deniesPath(u))return Z(p,{operation:"asset",path:u}),{status:"answered",response:O({reason:"forbidden"},s)};const w=await W(n,u);if(w.status==="error")return{status:"answered",response:O(w.failure,s)};try{const g=await e.asset(n,u,w.readPath,{delivery:l}),R=l==="file"?Ye(g):ge(g);return"kind"in R?{status:"answered",response:ct(R.url,s)}:{status:"admitted",path:u,display:l,file:R}}catch(g){return{status:"answered",response:O(v(g,{operation:"asset",path:u},n.signal,p),s)}}},vr=async(n,a,s)=>{const i=await De(n,a,s,zt);if(i.status==="answered")return i.response;const{path:u,display:l,file:w}=i;try{return l==="text"?await st(n.request,w,s,t.legacyTextEncoding,j):l==="workbook"?await at(n.request,w,s):await rt(n.request,w,s,j)}catch(g){return O(v(g,{operation:"asset",path:u},n.signal,p),s)}},_r=async(n,a,s)=>{const i=fr(n,a,s,t.legacyTextEncoding,j);return i.kind==="respond"?i:ye(i.selection,await lr(a,t.legacyTextEncoding))},Sr=async(n,a,s)=>{const i=await De(n,a,s,Ut);if(i.status==="answered")return{kind:"response",response:i.response};const{path:u,display:l,file:w}=i,g=L=>O(v(L,{operation:"asset",path:u},n.signal,p),s);let R;try{R=l==="text"?await _r(n.request,w,s):ur(n.request,w,s,j)}catch(L){return{kind:"response",response:g(L)}}if(R.kind==="respond")return{kind:"response",response:R.response};const{bridge:D}=w;return D===void 0?(N(p,{operation:"asset",path:u,error:new TypeError("[markdown-explorer] the asset port must attach a bridge to a file the host streams itself")}),{kind:"response",response:O({reason:"failed"},s)}):{kind:"file",status:R.status,headers:R.headers,bridge:{uri:D.uri,storageVersion:D.storageVersion},range:R.range,length:R.length,fail:L=>g(Gt(D.readFailure,L))}},Pr=async(n,a)=>{if(h.deniesPath(a))return Z(p,{operation:"text",path:a}),m.failureDocument("forbidden");const s=await W(n,a);if(s.status==="error")return{kind:"failure",failure:s.failure};try{const i=ge(await e.asset(n,a,s.readPath,{delivery:"text"})),u=await wt(i,y,t.legacyTextEncoding);return u===null?m.failureDocument("unsupported"):{kind:"text",name:i.name,text:u.text,truncated:u.truncated,url:m.explorerAssetHref(t.dataPath,a,i.version)}}catch(i){return{kind:"failure",failure:v(i,{operation:"text",path:a},n.signal,p)}}},Q=async(n,a,s)=>h.deniesPath(s)?(Z(p,{operation:a,path:s}),{status:"error",failure:{reason:"forbidden"}}):W(n,s),Ir=async(n,a,s)=>{const i=await Q(a,"edit",s);if(i.status==="error")return{kind:"failure",failure:i.failure};try{return _t(await n.source(a,s,i.readPath),T)}catch(u){return{kind:"failure",failure:v(u,{operation:"edit",path:s},a.signal,p)}}},Dr=async(n,a,s,i,u)=>{const l=await Q(a,"save",s);if(l.status==="error")return{kind:"failure",failure:l.failure};try{return St(await n.save(a,s,l.readPath,{text:u,baseVersion:i}),T)}catch(w){return{kind:"failure",failure:v(w,{operation:"save",path:s},a.signal,p)}}},Lr=async(n,a,s,i,u)=>{const l=await Q(a,"preview",i);if(l.status==="error")return{kind:"failure",failure:l.failure};let w;try{w=Pt(await n.preview(a,i,l.readPath,u))}catch(R){return{kind:"failure",failure:v(R,{operation:"preview",path:i},a.signal,p)}}if("kind"in w)return w.kind==="failure"?w:m.failureDocument("failed");const g=await U(w.html,{scope:s,signal:a.signal});return g.status==="sanitized"?{kind:"preview",htmlContent:g.html,headings:w.headings}:(g.cause!==null&&N(p,{operation:"preview",path:i,error:g.cause}),m.failureDocument(g.reason))},Nr=async(n,a,s)=>{const i=await Q(a,"revisions",s);if(i.status==="error")return{kind:"failure",failure:i.failure};try{return{kind:"revisions",revisions:It(await n.revisions(a,s,i.readPath))}}catch(u){return{kind:"failure",failure:v(u,{operation:"revisions",path:s},a.signal,p)}}},$r=async(n,a,s,i)=>{const u=await Q(a,"revision",s);if(u.status==="error")return{kind:"failure",failure:u.failure};try{return{kind:"revision",id:i,text:Dt(await n.revision(a,s,u.readPath,i),T)}}catch(l){return{kind:"failure",failure:v(l,{operation:"revision",path:s},a.signal,p)}}},jr=async(n,a,s,i,u,l)=>{const w=z(u,m.EXPLORER_DATA_QUERY.path);if(w===null||!m.isAcceptableDocumentPath(w))return O({reason:"invalid"},l);if(a==="edit")return S(200,JSON.stringify(await Ir(n,s,w)),l);if(a==="revisions")return S(200,JSON.stringify(await Nr(n,s,w)),l);if(a==="revision"){const D=z(u,m.EXPLORER_DATA_QUERY.revision);return m.isExplorerEditToken(D)?S(200,JSON.stringify(await $r(n,s,w,D)),l):O({reason:"invalid"},l)}const g=z(u,m.EXPLORER_DATA_QUERY.base);if(a==="save"&&!m.isExplorerEditToken(g))return O({reason:"invalid"},l);const R=await rn(s.request,T);return R.status==="error"?O(R.failure,l):a==="preview"?S(200,JSON.stringify(await Lr(n,s,i,w,R.text)),l):S(200,JSON.stringify(await Dr(n,s,w,g,R.text)),l)},Cr=async({request:n,url:a,params:s})=>{const i=Ke(await K(n,We));if(i.status==="forbidden")throw Xr.accessFailureResponse("forbidden",{headers:we(i.headers)});const u=we(i.headers);if(u.set("Cache-Control",mr),i.status==="signed-out")throw Yt("signedOutPage",yr({request:n,url:a},u));const l=$.resolveExplorerLocation(d,s["*"],a.searchParams);if(l.kind==="redirect")throw ee.redirect(l.href,{headers:u});const{principal:w}=i,g=Qe(o,ke(w));if(l.kind==="document-id"){if(A===void 0)throw new TypeError("[markdown-explorer] an ID URL was resolved without the documentIds ports");const R=l.id===null?Vt:await xe(A,{principal:w,request:n,signal:n.signal,refresh:!1},l.id);if(R.status==="resolved")throw ee.redirect(Mr(l.opens,R),{headers:u});return ee.data(Le(w,g,n,l.location,{id:l.id,failure:R.failure}),{status:m.EXPLORER_FAILURE_STATUS[R.failure.reason],headers:u})}return ee.data(Le(w,g,n,l.location,null),{headers:u})},Mr=(n,a)=>$.explorerHref(d,$.documentIdOpeningTarget(n,a.path,a.sourceId)),Le=(n,a,s,i,u)=>{const l=M.get(i.source);if(l===void 0)throw new RangeError(`[markdown-explorer] no source for ${x.describeValue(i.source)}`);const w={signal:s.signal,timeoutMs:k,late:null,handOverMs:k};return{scope:a,sources:c.map(g=>({id:g.id,label:gr(g,n)})),settings:$.parseViewSettings(Wt(X,s),ce),tree:i.view==="single"?null:{sourceId:i.source,result:fe(w,g=>Se(l,n,a,s,g).then(R=>R.result))},documents:Jt(i).map(g=>({path:g,document:fe(w,R=>Ie({principal:n,request:s,signal:R,refresh:!1},a,g))})),notices:fe({signal:s.signal,timeoutMs:k,late:he,handOverMs:0},g=>xr({principal:n,request:s,signal:g,refresh:!1})),documentId:u}},Ne=async(n,a)=>{const s=Ke(await K(n,a));return{authentication:s,headers:we(s.headers)}},$e=async n=>{let a;try{a=await Ne(n,We)}catch(u){return{status:"answered",response:O(v(Je(u),{operation:"authenticate"},n.signal,p))}}const{authentication:s,headers:i}=a;return s.status==="signed-out"?{status:"answered",response:O({reason:"unauthorized"},i)}:s.status==="forbidden"?{status:"answered",response:O({reason:"forbidden"},i)}:{status:"signed-in",principal:s.principal,headers:i}},zr=async(n,a,s)=>{const i=await $e(a);if(i.status==="answered")return i.response;const{principal:u,headers:l}=i;if(n==="asset")return vr({principal:u,request:a,signal:a.signal,refresh:!1},s,l);const w=Qe(o,ke(u));l.set(m.EXPLORER_SCOPE_HEADER,w);const g={principal:u,request:a,signal:a.signal,refresh:!1},R=()=>O({reason:"invalid"},l);if(n==="document"){const _=z(s,m.EXPLORER_DATA_QUERY.path);if(_===null||!m.isAcceptableDocumentPath(_))return R();const H=a.headers.has(m.EXPLORER_PROOF_HEADER);return H&&!er(a)?O({reason:"forbidden"},l):S(200,JSON.stringify(await Ie({...g,refresh:H},w,_)),l)}if(n==="text"){const _=z(s,m.EXPLORER_DATA_QUERY.path);return _===null||!m.isAcceptableDocumentPath(_)?R():S(200,JSON.stringify(await Pr(g,_)),l)}if(n==="edit"||n==="save"||n==="preview"||n==="revisions"||n==="revision")return b===void 0?O({reason:"not-found"},l):jr(b,n,g,w,s,l);if(n==="issue-id"){if(A===void 0)return O({reason:"not-found"},l);const _=z(s,m.EXPLORER_DATA_QUERY.path);return _===null||!$.hasDocumentUrl(_)?R():rr(await Er(A,g,_),l)}if(n==="resolve-id"){if(A===void 0)return O({reason:"not-found"},l);const _=z(s,m.EXPLORER_DATA_QUERY.id);if(_===null||!m.isCanonicalDocumentId(_))return R();const H=await xe(A,g,_);return rr(H.status==="resolved"?{status:"ok",path:H.path,source:H.sourceId}:H,l)}const D=z(s,m.EXPLORER_DATA_QUERY.source),L=z(s,m.EXPLORER_DATA_QUERY.path);if(D===null||(n==="children"||n==="ancestors"||n==="reveal")&&(L===null||!m.isAcceptableDocumentPath(L)))return R();const C=M.get(D);if(C===void 0)return O({reason:"not-found"},l);if(n==="tree")return S(200,(await Se(C,u,w,a,a.signal)).json,l);if(n==="refresh"){const _=await Tr(C,u,w,a);return a.signal.aborted||Rr(C,ue(C,w)),S(200,_.json,l)}return n==="ancestors"?C.ancestors===void 0||L===null?O({reason:"not-found"},l):S(200,JSON.stringify(await Or(C,C.ancestors,g,L)),l):n==="reveal"?L===null?R():S(200,JSON.stringify(await Ar(C,g,L)),l):C.children===void 0||L===null?O({reason:"not-found"},l):S(200,JSON.stringify(await kr(C,C.children,g,L)),l)},Ur=async n=>{const{authentication:a,headers:s}=await Ne(n,Mt);if(!s.keys().next().done)throw new TypeError("[markdown-explorer] authenticate returned headers in read-only mode; a read-only authentication must only read the session (none was forwarded)");return a.status==="signed-in"},je=t.embeds.linkCardEndpoint===null?null:r.createLinkCardHandler({authorize:Ur}),Vr=async(n,a)=>{try{return await n(a)}catch(s){return O(v(Je(s),{operation:"authenticate"},a.signal,p))}},le=async(n,a,s)=>{if(new URL(n.url).pathname.endsWith(".data"))return O({reason:"not-found"});if(!m.isExplorerDataOperation(s))return O({reason:"not-found"});if(s==="link-card"){if(je===null)return O({reason:"not-found"});const u=qe(n,s);return u!==null?u:Vr(je,n)}if(Zt.has(s)&&b===void 0)return O({reason:"not-found"});if(Qt.has(s)&&A===void 0)return O({reason:"not-found"});const i=qe(n,s);if(i!==null)return i;if(s==="refresh"&&!er(n))return O({reason:"forbidden"});if((s==="save"||s==="preview")&&!qt(n))return O({reason:"forbidden"});if(s==="issue-id"&&!en(n))return O({reason:"forbidden"});try{return await zr(s,n,a.searchParams)}catch(u){return O(v(u,{operation:s},n.signal,p))}},Fr=async(n,a,s)=>{if(s!=="asset"||n.method.toUpperCase()!=="GET"||new URL(n.url).pathname.endsWith(".data"))return{kind:"response",response:await le(n,a,s)};try{const i=await $e(n);return i.status==="answered"?{kind:"response",response:i.response}:await Sr({principal:i.principal,request:n,signal:n.signal,refresh:!1},a.searchParams,i.headers)}catch(i){return{kind:"response",response:O(v(i,{operation:"asset"},n.signal,p))}}};return Object.freeze({loader:Cr,headers:an,dataLoader:({request:n,url:a,params:s})=>le(n,a,s["*"]),dataAction:({request:n,url:a,params:s})=>le(n,a,s["*"]),planData:({request:n,url:a,params:s})=>Fr(n,a,s["*"]),forgetTree:n=>{if(typeof n!="string")throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${x.describeValue(n)}`);F.forget(n)}})};exports.ASSET_CONTENT_SECURITY_POLICIES=se;exports.ExplorerError=dt;exports.createExplorerServer=cn;
|
|
1
|
+
"use strict";const Xr=require("@aiquants/auth-core"),J=require("@aiquants/request-isolation"),ee=require("react-router"),$=require("./location-Csj3eAm_.cjs"),m=require("./ownUrls-BTPGNhBt.cjs"),x=require("./describeValue-Ccvhbt36.cjs"),Ee=require("./lru-SGmUyBQU.cjs"),tr="application/octet-stream",nr="application/pdf",Hr=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",nr]),Ce="default-src 'none'; media-src 'self'; style-src 'unsafe-inline'",se=Object.freeze({sandboxed:`${Ce}; sandbox`,mediaDocument:`${Ce}; sandbox allow-same-origin`}),Me=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,Br=/^[\t\n\r ]+|[\t\n\r ]+$/gu,me=/^[\t ]+|[\t ]+$/gu,Yr=e=>{const r=[];let t="",o=0;for(;;){for(;o<e.length&&e[o]!=='"'&&e[o]!==",";)t+=e[o],o+=1;if(o<e.length&&e[o]==='"'){const c=o;for(o+=1;o<e.length&&e[o]!=='"';)o+=e[o]==="\\"?2:1;if(o=Math.min(o+1,e.length),t+=e.slice(c,o),o<e.length)continue}if(r.push(t.replace(me,"")),t="",o>=e.length)return r;o+=1}},Gr=e=>{const r=e.replace(Br,""),t=r.indexOf("/");if(t<0)return null;const o=r.slice(0,t),c=r.indexOf(";",t+1),d=r.slice(t+1,c<0?r.length:c).replace(/[\t\n\r ]+$/u,"");return Me.test(o)&&Me.test(d)?`${o}/${d}`.toLowerCase():null},Wr=e=>{let r=null;for(const t of Yr(e)){const o=Gr(t);o!==null&&o!=="*/*"&&(r=o)}return r},Jr=/['()*]/gu,sr=e=>encodeURIComponent(e).replace(Jr,r=>`%${r.charCodeAt(0).toString(16).toUpperCase()}`),be=Object.freeze({"Cache-Control":"private, max-age=60, stale-while-revalidate=600, no-transform",Vary:"Cookie"}),or=(e,r)=>{const t=Wr(e),o=t!==null&&Hr.has(t),c=o&&(t.startsWith("audio/")||t.startsWith("video/"));return{contentType:t===null?tr:t,inline:o,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`${o?"inline":"attachment"}; filename*=UTF-8''${sr(r)}`,...t===nr?{}:{"Content-Security-Policy":c?se.mediaDocument:se.sandboxed},"Cross-Origin-Resource-Policy":"same-origin"}}},ne=64*1024,ar=e=>`text/plain; charset=${e}`,Kr=e=>({"X-Content-Type-Options":"nosniff","Content-Disposition":`inline; filename*=UTF-8''${sr(e)}`,"Content-Security-Policy":se.sandboxed,"Cross-Origin-Resource-Policy":"same-origin"}),Qr=(e,r)=>`${r===null?"":r};${e}`,Zr=/^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu,re=Object.freeze({kind:"whole"}),ze=Object.freeze({kind:"unsatisfiable"}),ir=(e,r,t,o)=>{const c=e.get("Range");if(c===null)return re;const d=e.get("If-Range");if(d!==null&&d!==t)return re;const f=Zr.exec(c);if(f===null)return re;const[,p,h,k]=f;if(k!==void 0){const T=Number(k);if(T===0)return ze;const A=Math.max(0,r-T);return Ue(A,r-A,o)}const y=Number(p),b=h===""?Number.POSITIVE_INFINITY:Number(h);return b<y?re:y>=r?ze:Ue(y,Math.min(b,r-1)-y+1,o)},Ue=(e,r,t)=>({kind:"partial",range:{offset:e,length:t===null?r:Math.min(r,t)}}),Ve="W/",qr=e=>{const r=[];let t=0,o=!1;for(let c=0;c<e.length;c+=1)e[c]==='"'?o=!o:e[c]===","&&!o&&(r.push(e.slice(t,c).replace(me,"")),t=c+1);return r.push(e.slice(t).replace(me,"")),r},Fe=e=>e.startsWith(Ve)?e.slice(Ve.length):e,Te=(e,r)=>{if(e===null)return!1;const t=qr(e);if(t.length===1&&t[0]==="*")return!0;const o=Fe(r);return t.some(c=>Fe(c)===o)},et=(e,r)=>{let t=r;return e.pipeThrough(new TransformStream({transform:(o,c)=>{const d=o.byteLength>t?o.subarray(0,t):o;t-=d.byteLength,c.enqueue(d),t===0&&c.terminate()},flush:o=>{t>0&&o.error(new RangeError("[markdown-explorer] the asset ended before its declared length"))}}))},Y=(e,r,t,o,c)=>(c!==null&&t.set("Content-Length",String(c)),{head:e.method.toUpperCase()==="HEAD",status:r,headers:t,range:o,length:c}),q=({head:e,status:r,headers:t,range:o,length:c})=>e?{kind:"respond",response:new Response(null,{status:r,headers:t})}:{kind:"stream",status:r,headers:t,range:o,length:c},oe=async(e,r)=>{if(e.kind==="respond")return e.response;const t=await r(e.range);return new Response(e.length===null?t:et(t,e.length),{status:e.status,headers:e.headers})},cr=(e,r)=>{const t=new Headers(e);for(const[o,c]of Object.entries({"Accept-Ranges":"bytes","Content-Range":`bytes */${r}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff"}))t.set(o,c);return new Response(null,{status:416,headers:t})},ur=(e,r,t,o)=>{const c=`"${r.version}"`,d=or(r.contentType,r.name),f=new Headers(t);for(const[k,y]of Object.entries({...d.headers,...be,ETag:c}))f.set(k,y);if(Te(e.headers.get("If-None-Match"),c))return{kind:"respond",response:new Response(null,{status:304,headers:f})};if(f.set("Content-Type",d.contentType),r.size===null)return q(Y(e,200,f,null,null));if(r.size===0)return f.set("Content-Length","0"),{kind:"respond",response:new Response(null,{status:200,headers:f})};f.set("Accept-Ranges","bytes");const p=ir(e.headers,r.size,c,o);if(p.kind==="unsatisfiable")return{kind:"respond",response:cr(t,r.size)};if(p.kind==="whole")return q(Y(e,200,f,null,r.size));const{range:h}=p;return f.set("Content-Range",`bytes ${h.offset}-${h.offset+h.length-1}/${r.size}`),q(Y(e,206,f,h,h.length))},rt=async(e,r,t,o)=>oe(ur(e,r,t,o),c=>r.open(c)),tt=(e,r)=>{const t=new Uint8Array(r);let o=0;for(const c of e){if(o===r)break;const d=c.subarray(0,r-o);t.set(d,o),o+=d.byteLength}return t},nt=(e,r,t)=>new ReadableStream({start:o=>{for(const c of e)o.enqueue(c);r&&o.close()},pull:async o=>{const{done:c,value:d}=await t.read();c?o.close():o.enqueue(d)},cancel:o=>t.cancel(o)},{highWaterMark:0}),dr=async(e,r,t)=>{const o=e.getReader(),c=r===null?ne:Math.min(r,ne),d=r===null?c+1:c,f=[];let p=0,h=!1;try{for(;p<d;){const{done:b,value:T}=await o.read();if(b){h=!0;break}f.push(T),p+=T.byteLength}if(h&&r!==null&&p<c)throw new RangeError("[markdown-explorer] the asset ended before its declared length");const k=r===null?h:r<=ne;return{encoding:$.textEncodingOf(tt(f,Math.min(p,c)),k,t),body:nt(f,h,o)}}catch(k){throw o.cancel(k).catch(()=>{}),k}},lr=async(e,r)=>{const t=await dr(await e.open(e.size===null?null:{offset:0,length:Math.min(e.size,ne)}),e.size,r);return t.body.cancel().catch(()=>{}),t.encoding},fr=(e,r,t,o,c)=>{const d=`"${Qr(r.version,o)}"`,f=new Headers(t);for(const[k,y]of Object.entries({...Kr(r.name),...be,ETag:d}))f.set(k,y);if(Te(e.headers.get("If-None-Match"),d))return{kind:"respond",response:new Response(null,{status:304,headers:f})};if(r.size===0)return f.set("Content-Type",ar($.textEncodingOf(new Uint8Array(0),!0,o))),f.set("Content-Length","0"),{kind:"respond",response:new Response(null,{status:200,headers:f})};if(r.size===null)return{kind:"needs-encoding",selection:Y(e,200,f,null,null)};f.set("Accept-Ranges","bytes");const p=ir(e.headers,r.size,d,c);if(p.kind==="unsatisfiable")return{kind:"respond",response:cr(t,r.size)};if(p.kind==="whole")return{kind:"needs-encoding",selection:Y(e,200,f,null,r.size)};const{range:h}=p;return f.set("Content-Range",`bytes ${h.offset}-${h.offset+h.length-1}/${r.size}`),{kind:"needs-encoding",selection:Y(e,206,f,h,h.length)}},ye=(e,r)=>{const t=new Headers(e.headers);return t.set("Content-Type",ar(r)),q({...e,headers:t})},st=async(e,r,t,o,c)=>{const d=fr(e,r,t,o,c);if(d.kind==="respond")return d.response;const{selection:f}=d;if(f.head||f.range!==null)return oe(ye(f,await lr(r,o)),h=>r.open(h));const p=await dr(await r.open(null),r.size,o);return oe(ye(f,p.encoding),async()=>p.body)},ot=e=>`workbook;${e}`,at=async(e,r,t)=>{const o=`"${ot(r.version)}"`,c=or(tr,r.name),d=new Headers(t);for(const[f,p]of Object.entries({...c.headers,...be,ETag:o}))d.set(f,p);return Te(e.headers.get("If-None-Match"),o)?new Response(null,{status:304,headers:d}):(d.set("Content-Type",c.contentType),oe(q(Y(e,200,d,null,r.size)),f=>r.open(f)))},it=Object.freeze({"Cache-Control":"private, no-store","Referrer-Policy":"no-referrer"}),ct=(e,r)=>{const t=new Headers(r);for(const[o,c]of Object.entries(it))t.set(o,c);return t.set("Location",e),new Response(null,{status:302,headers:t})},fe=(e,r)=>{const t=new AbortController,o=r(AbortSignal.any([e.signal,t.signal]));return new Promise(c=>{let d;const f=setTimeout(()=>{c(e.late),d=setTimeout(()=>t.abort(),e.handOverMs)},e.timeoutMs),p=()=>{clearTimeout(f),clearTimeout(d)};o.then(h=>{p(),c(h)},()=>{p(),c(e.late)})})},ut=Object.freeze({error:(e,r)=>{console.error(e,r)}}),pr=Symbol.for("@aiquants/markdown-explorer:ExplorerError");class dt extends Error{reason;code;constructor(r,t={}){if(!m.isExplorerFailureReason(r))throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${x.describeValue(r)}`);if(t.code!==void 0&&!m.isExplorerFailureCode(t.code))throw new RangeError(`[markdown-explorer] an ExplorerError code must be 1 to 64 lowercase letters, digits or hyphens; got ${x.describeValue(t.code)}`);super(`[markdown-explorer] ${r}`,t.cause===void 0?void 0:{cause:t.cause}),this.name="ExplorerError",this.reason=r,this.code=t.code,Object.defineProperty(this,pr,{value:!0})}}const lt=e=>e instanceof Error&&Object.hasOwn(e,pr)&&m.isExplorerFailureReason(e.reason),ft=e=>typeof e=="object"&&e!==null&&e.name==="AbortError",Re=(e,r,t)=>{try{e.error(r,t)}catch(o){console.error("[markdown-explorer] the logger threw while reporting a failure",{operation:t.operation,error:o})}},N=(e,r)=>Re(e,`[markdown-explorer] ${r.operation} failed`,r),pt=(e,r)=>Re(e,`[markdown-explorer] ${r.operation} left out an entry`,r),Z=(e,r)=>Re(e,`[markdown-explorer] ${r.operation} refused a path the deny rules match`,{...r,error:new RangeError("[markdown-explorer] the path matches a deny rule")}),Xe=(e,r)=>{e===null||typeof e!="object"&&typeof e!="function"||Promise.resolve(e).then(void 0,r)},v=(e,r,t,o)=>lt(e)?m.failureOf(e.reason,e.code):(ft(e)||t.aborted||N(o,{...r,error:e}),{reason:"failed"}),He=2*1024*1024,Be=256*1024*1024,ht=async(e,r)=>{const t=e.getReader(),o=new Uint8Array(r);let c=0;for(;c<r;){const{done:d,value:f}=await t.read();if(d)return o.subarray(0,c);const p=f.subarray(0,r-c);o.set(p,c),c+=p.byteLength}return t.cancel().catch(()=>{}),o},wt=async(e,r,t)=>{if(e.size===0)return{text:"",truncated:!1};const o=e.size!==null&&e.size>r,c=e.size===null?r+1:Math.min(e.size,r),d=await ht(await e.open(o?{offset:0,length:r}:null),c);if(e.size!==null&&d.byteLength<c)throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");const f=o||d.byteLength>r,p=f?d.subarray(0,r):d,h=$.decodeTextLeniently(p,!f,t);return h.includes("\0")?null:{text:h,truncated:f}},ae=e=>({result:e,json:JSON.stringify(e)}),pe=Object.freeze(ae(Object.freeze({status:"error",failure:Object.freeze({reason:"failed"})}))),mt=e=>e.status==="ok"&&e.entries.length>0,yt=({ttlMs:e,maxEntries:r,maxBytes:t,now:o})=>{const c=Ee.createLruCache(r,{max:t,of:(y,b)=>2*b.tree.json.length}),d=new Map,f=new Map,p=(y,b)=>{const T=new AbortController,A={waiters:0,superseded:!1,started:!1,loadTree:b},I=f.get(y),V=(M,ce)=>{const K=ae(M);return!(A.superseded||T.signal.aborted)&&mt(M)&&c.set(y,{tree:K,loadedAt:ce}),K},U=(async()=>{if(I!==void 0&&await I,T.signal.aborted)return pe;const M=o();return A.started=!0,V(await A.loadTree(T.signal,M),M)})().finally(()=>{d.get(y)===X&&d.delete(y)}),X={promise:U,controller:T,state:A};d.set(y,X);const j=U.then(()=>{},()=>{});return f.set(y,j),j.then(()=>{f.get(y)===j&&f.delete(y)}),X},h=(y,b,T)=>{b.state.waiters+=1;const A=()=>{b.state.waiters-=1,!(b.state.waiters>0)&&(d.get(y)===b&&d.delete(y),b.controller.abort())};return T.addEventListener("abort",A,{once:!0}),b.promise.finally(()=>{T.removeEventListener("abort",A)})},k=y=>{c.delete(y);const b=d.get(y);b?.state.started&&(b.state.superseded=!0,d.delete(y))};return{load:(y,b,T)=>{if(b.aborted)return Promise.resolve(pe);const A=c.get(y);if(A!==void 0){if(o()-A.loadedAt<e)return Promise.resolve(A.tree);c.delete(y)}const I=d.get(y);return h(y,I===void 0?p(y,T):I,b)},refresh:(y,b,T)=>{if(b.aborted)return Promise.resolve(pe);k(y);const A=d.get(y);return A===void 0?h(y,p(y,T),b):(A.state.loadTree=T,h(y,A,b))},forget:k}},gt=e=>({load:(r,t,o)=>o(t,e()).then(ae),refresh:(r,t,o)=>o(t,e()).then(ae),forget:()=>{}}),E=e=>{throw new TypeError(`[markdown-explorer] ${e}`)},Et=e=>{if(e===null||typeof e!="object")return null;const{name:r,path:t}=e;return typeof r!="string"||typeof t!="string"?null:r===""?{path:t,reason:"an empty name"}:m.isAcceptableDocumentPath(t)?null:{path:t,reason:"a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)"}},bt=(e,r,t,o)=>{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 ${x.describeValue(e)}`);const c=new Set;for(const d of e){if(typeof d!="string"||!m.isAcceptableDocumentPath(d))throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");if(t.deniesPath(d))throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");if(!o(d))throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");if(d===r)throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");if(c.has(d))throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");c.add(d)}return Object.freeze([...c])},Tt=(e,r,t,o,c)=>{const d=new Set,f=h=>{if(!Array.isArray(h))return E("a source returned entries that are not an array");const k=[];for(const y of h){const b=p(y);b!==null&&k.push(b)}return k},p=h=>{const k=Et(h);if(k!==null)return o(k),null;const y=m.entryViolation(h);if(y!==null)return E(y);const b=h;if(d.has(b))return E("a source returned entries that contain themselves");const{name:T,path:A,type:I,mimeType:V,modifiedAt:F,children:U,lazy:X}=b;if(r.deniesName(T)||r.deniesPath(A))return null;if(!c(A))return o({path:A,reason:"a path outside the source's boundary"}),null;const j={name:T,path:A,...V===void 0?{}:{mimeType:V},...F===void 0?{}:{modifiedAt:F}};if(I==="file")return{...j,type:I};if(X===!0)return t?{...j,type:I,lazy:!0,children:[]}:E("a lazy directory came from a source without a children function");if(U===void 0)return{...j,type:I};d.add(b);const M=f(U);return d.delete(b),{...j,type:I,children:M}};return f(e)},Rt=/^[\x21\x23-\x7E]{1,256}$/u,hr=e=>typeof e=="string"&&Rt.test(e),kt=new Set(["text","image","media","spreadsheet","file"]),Ot=e=>typeof e=="string"&&kt.has(e),At=(e,r,t)=>{if(e!==null&&typeof e=="object"){const d=e,{kind:f}=d;if(Ot(f)){if(Object.hasOwn(d,"url"))return E(`a ${f} document carries its version, not a url`);if(typeof d.name!="string")return E("a document needs a name string");if(!hr(d.version))return E(`a ${f} document needs a version of 1 to 256 visible ASCII characters other than '"'`);const p=r(d.version);switch(f){case"image":{const{imageType:h}=d;return m.isExplorerImageType(h)?{kind:f,name:d.name,url:p,imageType:h}:E(`unknown image type ${x.describeValue(h)}`)}case"file":return{kind:f,name:d.name,url:p};case"media":{const{mediaType:h}=d;return m.isExplorerMediaType(h)?{kind:f,name:d.name,url:p,mediaType:h}:E(`unknown media type ${x.describeValue(h)}`)}case"text":{const{text:h,truncated:k,lang:y}=d;return typeof h!="string"||typeof k!="boolean"?E("a text document needs text and truncated"):m.isExplorerDocumentLang(y)?{kind:f,name:d.name,text:h,truncated:k,lang:y,url:p}:E(m.documentLangRefusal(f,y))}case"spreadsheet":{const h=m.spreadsheetFieldsViolation(d);if(h!==null)return E(h);const{format:k,firstSheetText:y,edit:b}=d;return{kind:f,name:d.name,url:p,format:k,firstSheetText:y,edit:vt(b)}}}}}const o=m.documentViolation(e);if(o!==null)return E(o);const c=e;switch(c.kind){case"failure":{const{reason:d,code:f}=c.failure;return{kind:"failure",failure:m.failureOf(d,f)}}case"markdown":return c.headings.length>m.EXPLORER_MAX_HEADINGS?{kind:"failure",failure:m.failureOf("too-large")}:(c.edit?.kind==="inline"||c.edit?.kind==="draft")&&!t?E(`a markdown document offers ${c.edit.kind} editing, but the server has no edit ports`):{kind:"unsanitized-markdown",name:c.name,html:c.htmlContent,headings:c.headings.map(({text:d,depth:f,id:p})=>({text:d,depth:f,id:p})),lang:c.lang,edit:xt(c.edit)}}},xt=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}}},vt=e=>e===null?null:{kind:"external",href:e.href},ie=(e,r,t)=>typeof e!="string"?E(`${t} needs a text string`):e.includes("\0")?E(`${t} holds NUL, which no text editor can keep`):new TextEncoder().encode(e).byteLength>r?E(`${t} is over editMaxBytes (${r} bytes); refuse a longer source with ExplorerError "too-large"`):e,wr=e=>m.isRootRelativeUrl(e.href)?{kind:"grant",href:e.href}:E("a grant needs a root-relative href"),_t=(e,r)=>{if(e===null||typeof e!="object")return E("an edit source must be an object");const t=e;return t.kind==="grant"?wr(t):t.kind==="draft"?{kind:"draft",text:ie(t.text,r,"a draft source")}:t.kind!=="edit"?E(`an edit source's kind must be "edit", "draft" or "grant"`):m.isExplorerEditToken(t.version)?typeof t.history!="boolean"?E("an edit source needs history"):{kind:"edit",text:ie(t.text,r,"an edit source"),version:t.version,history:t.history}:E("an edit source needs a version of 1 to 1024 characters")},St=(e,r)=>{if(e===null||typeof e!="object")return E("a save result must be an object");const t=e;switch(t.kind){case"grant":return wr(t);case"saved":return m.isExplorerEditToken(t.version)?{kind:"saved",version:t.version}:E("a saved result needs a version of 1 to 1024 characters");case"conflict":return m.isExplorerEditToken(t.version)?{kind:"conflict",version:t.version,text:ie(t.text,r,"a conflict's current text")}:E("a conflict needs the current version of 1 to 1024 characters");default:return E(`a save result's kind must be "saved", "conflict" or "grant"`)}},Pt=e=>{if(e===null||typeof e!="object")return E("a preview must be an object");const{htmlContent:r,headings:t}=e;if(typeof r!="string"||!Array.isArray(t))return E("a preview needs htmlContent and headings");if(t.length>m.EXPLORER_MAX_HEADINGS)return{kind:"failure",failure:m.failureOf("too-large")};for(const o of t){const c=m.headingViolation(o);if(c!==null)return E(c)}return{html:r,headings:t.map(({text:o,depth:c,id:d})=>({text:o,depth:c,id:d}))}},It=e=>{if(!Array.isArray(e))return E("revisions must be an array");const r=new Set;return e.map(t=>{const o=m.revisionViolation(t);if(o!==null)return E(o);const{id:c,modifiedAt:d,size:f,author:p,kept:h,current:k}=t;return r.has(c)?E(`two revisions share the id ${x.describeValue(c)}`):(r.add(c),{id:c,modifiedAt:d,size:f,author:p,kept:h,current:k})})},Dt=(e,r)=>ie(e,r,"a revision"),ge=e=>{if(e===null||typeof e!="object")return E("an asset file must be an object");const{name:r,contentType:t,size:o,version:c,open:d,kind:f,bridge:p}=e;if(f!==void 0)return E(f==="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")');if(typeof r!="string"||r==="")return E("an asset file needs a non-empty name");if(typeof t!="string")return E("an asset file needs a contentType string ('' when unknown)");if(o!==null&&!(typeof o=="number"&&Number.isSafeInteger(o)&&o>=0))return E("an asset file's size must be null or a non-negative safe integer");if(!hr(c))return E(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`);if(typeof d!="function")return E("an asset file needs an open function");const h={name:r,contentType:t,size:o,version:c,open:d};return Object.freeze(p===void 0?h:{...h,bridge:Lt(p)})},Lt=e=>{if(e===null||typeof e!="object")return E("an asset file's bridge must be an object when present");const{uri:r,storageVersion:t,readFailure:o}=e;return typeof r!="string"||r===""?E("an asset file's bridge needs a non-empty uri"):t!==null&&(typeof t!="string"||t==="")?E("an asset file's bridge needs a storageVersion that is a non-empty string, or null when the storage keeps none"):typeof o!="function"?E("an asset file's bridge needs a readFailure function"):Object.freeze({uri:r,storageVersion:t,readFailure:o})},Ye=e=>{if(e===null||typeof e!="object"||e.kind!=="redirect")return ge(e);const{url:r}=e;if(typeof r!="string"||!URL.canParse(r))return E("an asset redirect needs an absolute https URL");const t=new URL(r);return t.protocol!=="https:"||t.username!==""||t.password!==""?E("an asset redirect's URL must be https and carry no credentials"):Object.freeze({kind:"redirect",url:t.href})},Nt=e=>Array.isArray(e)?e.map(r=>{if(r===null||typeof r!="object")return E("a notice must be an object");const{id:t,tone:o,title:c,body:d,action:f}=r;if(typeof t!="string"||t===""||typeof c!="string")return E("a notice needs an id and a title");if(!m.isExplorerNoticeTone(o))return E(`unknown notice tone ${x.describeValue(o)}`);if(d!==void 0&&typeof d!="string")return E("a notice body must be a string");const h={id:t,tone:o,title:c,...d===void 0?{}:{body:d}};if(f===void 0)return h;if(f===null||typeof f!="object")return E("a notice action must be an object");const{label:k,href:y}=f;return typeof k!="string"||!m.isAcceptableUrl(y,m.EXPLORER_LINK_PROTOCOLS)?E("a notice action needs a label and an http(s), mailto or relative href"):{...h,action:{label:k,href:y}}}):E("notices must be an array"),$t=4e3,te=Object.freeze({ttlMs:3e5,maxEntries:64,maxBytes:64*1024*1024}),mr="private, no-store",jt=Object.freeze({"Content-Type":"application/json; charset=utf-8","Cache-Control":mr,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; frame-ancestors 'none'; sandbox","Cross-Origin-Resource-Policy":"same-origin"}),he=Object.freeze([]),Ct=Object.freeze({status:"ok",source:null,ancestors:null}),Ge=Object.freeze(["contains","confirm"]),We=Object.freeze({readOnly:!1}),Mt=Object.freeze({readOnly:!0}),zt=new Set(["file","text","workbook"]),Ut=new Set(["file","text"]),Vt=Object.freeze({status:"error",failure:Object.freeze({reason:"invalid"})}),P=(e,r,t)=>{if(!(t&&r===void 0)&&typeof r!="function")throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${x.describeValue(r)}`)},B=(e,r,t)=>{if(typeof r!="number")throw new TypeError(`[markdown-explorer] ${e} must be a number; got ${x.describeValue(r)}`);if(!Number.isSafeInteger(r)||r<=0||r>t)throw new RangeError(`[markdown-explorer] ${e} must be an integer in 1..${String(t)}; got ${x.describeValue(r)}`);return r},Ft=e=>{if(e===null||typeof e!="object"||!Object.isFrozen(e))throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");return $.revalidateExplorerConfig(e)},we=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)")}},Je=e=>e instanceof Response?new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`):e,Xt=(e,r)=>{if(!x.isPlainObject(r))throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);for(const t of Object.keys(r))if(!Ge.includes(t))throw new RangeError(`[markdown-explorer] ${e}.boundary.${t} is not an option; expected ${Ge.join(", ")}`);P(`${e}.boundary.contains`,r.contains,!1),P(`${e}.boundary.confirm`,r.confirm,!0)},Ht=e=>{if(!Array.isArray(e))throw new TypeError("[markdown-explorer] sources must be an array");const r=e;if(r.length===0)throw new RangeError("[markdown-explorer] sources must hold at least one source");const t=new Set;for(const[o,c]of r.entries()){if(c===null||typeof c!="object")throw new TypeError(`[markdown-explorer] sources[${String(o)}] must be an object`);const{id:d,label:f,boundary:p,tree:h,children:k,ancestors:y,cacheScope:b}=c;if(!$.isExplorerSourceId(d))throw new RangeError(`[markdown-explorer] sources[${String(o)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${x.describeValue(d)}`);const T=`source ${x.describeValue(d)}`;if(t.has(d))throw new RangeError(`[markdown-explorer] source ids must be unique; ${x.describeValue(d)} repeats at sources[${String(o)}]`);if(t.add(d),typeof f!="string"&&typeof f!="function")throw new TypeError(`[markdown-explorer] ${T}.label must be a string or a function`);if(typeof f=="string"&&f.trim()==="")throw new RangeError(`[markdown-explorer] ${T}.label must not be blank`);if(Xt(T,p),P(`${T}.tree`,h,!1),P(`${T}.children`,k,!0),P(`${T}.ancestors`,y,!0),b!==void 0&&b!=="principal"&&b!=="shared")throw new RangeError(`[markdown-explorer] ${T}.cacheScope must be "principal" or "shared"; got ${x.describeValue(b)}`)}return r},Bt=e=>{if(e===!1)return!1;if(e===void 0)return te;if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] treeCache must be { ttlMs, maxEntries, maxBytes } or false");const{ttlMs:r,maxEntries:t,maxBytes:o}=e;return{ttlMs:r===void 0?te.ttlMs:B("treeCache.ttlMs",r,Number.MAX_SAFE_INTEGER),maxEntries:t===void 0?te.maxEntries:B("treeCache.maxEntries",t,Number.MAX_SAFE_INTEGER),maxBytes:o===void 0?te.maxBytes:B("treeCache.maxBytes",o,Number.MAX_SAFE_INTEGER)}},Ke=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] authenticate must resolve to { status, ... }");const{status:r}=e;if(r!=="signed-in"&&r!=="signed-out"&&r!=="forbidden")throw new TypeError(`[markdown-explorer] authenticate resolved to an unknown status ${x.describeValue(r)}`);return e},Yt=(e,r)=>{if(!(r instanceof Response))throw new TypeError(`[markdown-explorer] ${e} must return a Response`);return r},Qe=(e,r)=>{if(typeof r!="string"||r==="")throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");const t=e(r);if(!Ee.isExplorerScope(t))throw new TypeError("[markdown-explorer] the platform's scope must be 22 base64url characters");return t},Gt=(e,r)=>{try{return e(r)}catch(t){return t}},Wt=(e,r)=>{const t=e(r);if(t!==void 0&&typeof t!="string")throw new TypeError(`[markdown-explorer] readSettings must return a string or undefined; got ${t===null?"null":typeof t}`);return t},Jt=e=>e.view==="multi"?e.docs:e.doc===null?[]:[e.doc],z=(e,r)=>{const t=e.getAll(r),[o]=t;return t.length===1&&o!==void 0&&o!==""?o:null},S=(e,r,t,o={})=>{const c=new Headers(t);for(const[d,f]of Object.entries({...jt,...o}))c.set(d,f);return new Response(r,{status:e,headers:c})},O=(e,r,t)=>S(m.EXPLORER_FAILURE_STATUS[e.reason],JSON.stringify({failure:e}),r,t),Kt=new Set(["refresh","save","preview","issue-id"]),Qt=new Set(["issue-id","resolve-id"]),Ze=4,Zt=new Set(["edit","save","preview","revisions","revision"]),qe=(e,r)=>{const t=Kt.has(r)?["POST"]:["GET","HEAD"];return t.includes(e.method.toUpperCase())?null:S(405,JSON.stringify({failure:{reason:"invalid"}}),void 0,{Allow:t.join(", ")})},er=e=>e.headers.get(m.EXPLORER_PROOF_HEADER)===m.EXPLORER_REFRESH_PROOF&&J.crossOriginRefusal(e,J.NO_CROSS_ORIGIN_NAVIGATION)===void 0,qt=e=>e.headers.get(m.EXPLORER_PROOF_HEADER)===m.EXPLORER_EDIT_PROOF&&J.crossOriginRefusal(e,J.NO_CROSS_ORIGIN_NAVIGATION)===void 0,en=e=>e.headers.get(m.EXPLORER_PROOF_HEADER)===m.EXPLORER_DOCUMENT_ID_PROOF&&J.crossOriginRefusal(e,J.NO_CROSS_ORIGIN_NAVIGATION)===void 0,rn=async(e,r)=>{const[t,...o]=(e.headers.get("Content-Type")??"").split(";").map(T=>T.trim().toLowerCase()),c=o.find(T=>T.startsWith("charset="));if(t!==m.EXPLORER_DRAFT_MEDIA_TYPE||c!==void 0&&c!=="charset=utf-8")return{status:"error",failure:{reason:"invalid"}};const d=Number(e.headers.get("Content-Length")??"0");if(Number.isFinite(d)&&d>r)return{status:"error",failure:{reason:"too-large"}};if(e.body===null)return{status:"ok",text:""};const f=e.body.getReader(),p=[];let h=0;for(;;){const{done:T,value:A}=await f.read();if(T)break;if(h+=A.byteLength,h>r)return await f.cancel(),{status:"error",failure:{reason:"too-large"}};p.push(A)}const k=new Uint8Array(h);let y=0;for(const T of p)k.set(T,y),y+=T.byteLength;let b;try{b=new TextDecoder("utf-8",{fatal:!0}).decode(k)}catch{return{status:"error",failure:{reason:"invalid"}}}return b.includes("\0")?{status:"error",failure:{reason:"invalid"}}:{status:"ok",text:b}},tn=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 r=e;for(const t of["source","save","preview","revisions","revision"])P(`edit.${t}`,r[t],!1);return e},nn=(e,r)=>{if(e.documentIds===null!=(r===void 0))throw new TypeError("[markdown-explorer] documentIds in defineExplorerConfig and the server's documentIds ports go together; give both or neither");if(r===void 0)return;if(r===null||typeof r!="object")throw new TypeError("[markdown-explorer] documentIds must be an object of the registry's ports");const t=r;for(const o of["issue","resolve"])P(`documentIds.${o}`,t[o],!1);return r},sn=e=>{if(e===null||typeof e!="object")return null;const{kind:r,id:t}=e;return r==="issued"||r==="taken"?{kind:r}:r==="existing"&&m.isCanonicalDocumentId(t)?{kind:r,id:t}:null},on=e=>{if(e===null||typeof e!="object")return;const{kind:r,path:t}=e;return r==="unbound"?null:r==="bound"&&typeof t=="string"&&$.hasDocumentUrl(t)?t:void 0},rr=(e,r)=>e.status==="ok"?S(200,JSON.stringify(e),r):O(e.failure,r),an=({parentHeaders:e,loaderHeaders:r,errorHeaders:t})=>{const o=new Headers,c=t===void 0?[e,r]:[e,r,t];for(const d of c)for(const[f,p]of d)f!=="set-cookie"&&o.set(f,p);return o},cn=(e,r)=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the server configuration must be an object");const t=Ft(e.config),o=r.prepareScope();P("authenticate",e.authenticate,!1),P("principalKey",e.principalKey,!1),P("document",e.document,!1),P("asset",e.asset,!1),P("signedOutPage",e.signedOutPage,!1),P("notices",e.notices,!0),P("onTreeRefreshed",e.onTreeRefreshed,!0),P("readSettings",e.readSettings,!1);const c=Ht(e.sources),d=$.withExplorerSources(t,c.map(n=>n.id)),f=e.logger;if(f!==void 0&&(f===null||typeof f!="object"||typeof f.error!="function"))throw new TypeError("[markdown-explorer] logger must be an object with an error function");const p=e.logger===void 0?ut:e.logger,h=m.resolvePathRules(e.deny),k=e.deferredTimeoutMs===void 0?$t:B("deferredTimeoutMs",e.deferredTimeoutMs,Ee.MAX_TIMER_MILLISECONDS),y=e.textMaxBytes===void 0?He:B("textMaxBytes",e.textMaxBytes,Be),b=tn(e.edit);if(b===void 0&&e.editMaxBytes!==void 0)throw new TypeError("[markdown-explorer] editMaxBytes needs the edit ports");const T=e.editMaxBytes===void 0?He:B("editMaxBytes",e.editMaxBytes,Be),A=nn(t,e.documentIds),I=Bt(e.treeCache),V=()=>Date.now(),F=I===!1?gt(V):yt({...I,now:V}),U=r.createSanitizer({options:e.sanitizer,maxPanels:t.multiView.maxPanels,iframeHosts:t.iframeHosts,dataPath:t.dataPath,ownUrls:$.ownUrlsOf(t)}),X=e.readSettings,j=e.assetMaxRangeBytes===null?null:B("assetMaxRangeBytes",e.assetMaxRangeBytes,Number.MAX_SAFE_INTEGER),M=new Map(c.map(n=>[n.id,n])),ce=$.documentStyleNames(t),{authenticate:K,principalKey:ke,signedOutPage:yr,onTreeRefreshed:Oe}=e,gr=(n,a)=>{if(typeof n.label=="string")return n.label;const s=n.label(a);if(typeof s!="string"||s.trim()==="")throw new TypeError(`[markdown-explorer] the label of source ${x.describeValue(n.id)} must be a non-blank string`);return s},ue=(n,a)=>n.cacheScope==="shared"?n.id:`${n.id}\0${a}`,G=(n,a)=>{const s=u=>N(p,{operation:"boundary",sourceId:n.id,path:a,error:u});let i;try{i=n.boundary.contains(a)}catch(u){return s(u),!1}return typeof i=="boolean"?i:(Xe(i,s),s(new TypeError(`[markdown-explorer] boundary.contains of source ${x.describeValue(n.id)} must return a boolean; got ${x.describeValue(i)}`)),!1)},de=async(n,a,s)=>{const{confirm:i}=n.boundary;if(i===void 0)return{status:"inside",readPath:s};let u;try{u=await i(a,s)}catch(R){return{status:"error",failure:v(R,{operation:"boundary",sourceId:n.id,path:s},a.signal,p)}}const l=R=>(N(p,{operation:"boundary",sourceId:n.id,path:s,error:new TypeError(`[markdown-explorer] boundary.confirm of source ${x.describeValue(n.id)} ${R}`)}),{status:"outside"});if(u===null||typeof u!="object")return l(`must resolve to { inside, readPath? }; got ${u===null?"null":typeof u}`);const{inside:w,readPath:g}=u;return w===!1?{status:"outside"}:w!==!0||typeof g!="string"?l("must resolve to { inside: false } or { inside: true, readPath: string }"):!m.isAcceptableDocumentPath(g)||h.deniesPath(g)?(N(p,{operation:"boundary",sourceId:n.id,path:s,error:new RangeError(`[markdown-explorer] boundary.confirm of source ${x.describeValue(n.id)} answered a readPath the explorer does not serve (unacceptable or denied)`)}),{status:"error",failure:{reason:"failed"}}):{status:"inside",readPath:g}},W=async(n,a)=>{const s=c.filter(l=>G(l,a));if(s.length===0)return{status:"error",failure:{reason:"forbidden"}};const i=s.find(l=>l.boundary.confirm===void 0);if(i!==void 0)return{status:"inside",readPath:a,sourceId:i.id};let u=null;for(const l of s){const w=await de(l,n,a);if(w.status==="inside")return{status:"inside",readPath:w.readPath,sourceId:l.id};w.status==="error"&&u===null&&(u=w.failure)}return{status:"error",failure:u===null?{reason:"forbidden"}:u}},Ae=async(n,a,s)=>{try{return Ye(await e.asset(n,a,s,{delivery:"file"})),null}catch(i){return v(i,{operation:"asset",path:a},n.signal,p)}},xe=async(n,a,s)=>{let i;try{i=await n.resolve(a,s)}catch(g){return{status:"error",failure:v(g,{operation:"resolve-id"},a.signal,p)}}const u=on(i);if(u===void 0)return N(p,{operation:"resolve-id",error:new TypeError('[markdown-explorer] documentIds.resolve must resolve to { kind: "unbound" } or { kind: "bound", path } with a document path that has a URL')}),{status:"error",failure:{reason:"failed"}};if(u===null)return{status:"error",failure:{reason:"not-found"}};if(h.deniesPath(u))return Z(p,{operation:"resolve-id",path:u}),{status:"error",failure:{reason:"forbidden"}};const l=await W(a,u);if(l.status==="error")return l;const w=await Ae(a,u,l.readPath);return w!==null?{status:"error",failure:w}:{status:"resolved",path:u,sourceId:l.sourceId}},Er=async(n,a,s)=>{if(h.deniesPath(s))return Z(p,{operation:"issue-id",path:s}),{status:"error",failure:{reason:"forbidden"}};const i=await W(a,s);if(i.status==="error")return i;const u=await Ae(a,s,i.readPath);if(u!==null)return{status:"error",failure:u};for(let l=0;l<Ze;l+=1){const w=m.createDocumentId(D=>crypto.getRandomValues(D));let g;try{g=await n.issue(a,s,w)}catch(D){return{status:"error",failure:v(D,{operation:"issue-id",path:s},a.signal,p)}}const R=sn(g);if(R===null)return N(p,{operation:"issue-id",path:s,error:new TypeError('[markdown-explorer] documentIds.issue must resolve to { kind: "issued" }, { kind: "existing", id } with an ID in its canonical form, or { kind: "taken" }')}),{status:"error",failure:{reason:"failed"}};if(R.kind==="issued")return{status:"ok",id:w};if(R.kind==="existing")return{status:"ok",id:R.id}}return N(p,{operation:"issue-id",path:s,error:new Error(`[markdown-explorer] documentIds.issue answered taken for ${String(Ze)} candidates in a row`)}),{status:"error",failure:{reason:"failed"}}},ve=(n,a,s)=>{const i=({path:u,reason:l})=>pt(p,{operation:s.operation,sourceId:s.sourceId,path:u,error:new TypeError(`[markdown-explorer] an entry with ${l} was left out`)});try{return{status:"ok",entries:Tt(n,h,a.children!==void 0,i,u=>G(a,u))}}catch(u){return N(p,{...s,error:u}),{status:"error",failure:{reason:"failed"}}}},br=async(n,a,s)=>{let i;try{i=await n.tree(a)}catch(l){return{status:"error",failure:v(l,{operation:"tree",sourceId:n.id},a.signal,p)}}const u=ve(i,n,{operation:"tree",sourceId:n.id});return u.status==="ok"?{status:"ok",entries:u.entries,loadedAt:s}:u},_e=(n,a,s,i)=>(u,l)=>br(n,{principal:a,request:s,signal:u,refresh:i},l),Se=(n,a,s,i,u)=>F.load(ue(n,s),u,_e(n,a,i,!1)),Tr=(n,a,s,i)=>F.refresh(ue(n,s),i.signal,_e(n,a,i,!0)),Rr=(n,a)=>{if(Oe===void 0)return;const s=i=>N(p,{operation:"refresh",sourceId:n.id,error:i});try{Xe(Oe(a),s)}catch(i){s(i)}},kr=async(n,a,s,i)=>{if(h.deniesPath(i)||!G(n,i))return{status:"error",failure:{reason:"forbidden"}};const u=await de(n,s,i);if(u.status==="outside")return{status:"error",failure:{reason:"forbidden"}};if(u.status==="error")return{status:"error",failure:u.failure};let l;try{l=await a(s,i,u.readPath)}catch(w){return{status:"error",failure:v(w,{operation:"children",sourceId:n.id,path:i},s.signal,p)}}return ve(l,n,{operation:"children",sourceId:n.id,path:i})},Pe=async(n,a,s,i)=>{const u=await de(n,s,i);if(u.status==="outside")return{status:"ok",ancestors:null};if(u.status==="error")return{status:"error",failure:u.failure};let l;try{l=await a(s,i,u.readPath,{maxDepth:t.revealDocument.maxDepth})}catch(w){return{status:"error",failure:v(w,{operation:"ancestors",sourceId:n.id,path:i},s.signal,p)}}if(Array.isArray(l)&&l.length>t.revealDocument.maxDepth)return{status:"ok",ancestors:null};try{return{status:"ok",ancestors:bt(l,i,h,w=>G(n,w))}}catch(w){return N(p,{operation:"ancestors",sourceId:n.id,path:i,error:w}),{status:"error",failure:{reason:"failed"}}}},Or=async(n,a,s,i)=>h.deniesPath(i)?{status:"error",failure:{reason:"forbidden"}}:G(n,i)?Pe(n,a,s,i):{status:"ok",ancestors:null},Ar=async(n,a,s)=>{if(h.deniesPath(s))return{status:"error",failure:{reason:"forbidden"}};for(const i of[n,...c.filter(u=>u!==n)]){if(a.signal.aborted)break;const u=i.ancestors;if(u===void 0||!G(i,s))continue;const l=await Pe(i,u,a,s);if(l.status==="ok"&&l.ancestors!==null)return{status:"ok",source:i.id,ancestors:l.ancestors}}return Ct},Ie=async(n,a,s)=>{if(h.deniesPath(s))return m.failureDocument("forbidden");const i=await W(n,s);if(i.status==="error")return{kind:"failure",failure:i.failure};let u;try{u=await e.document(n,s,i.readPath)}catch(g){return{kind:"failure",failure:v(g,{operation:"document",path:s},n.signal,p)}}let l;try{l=At(u,g=>m.explorerAssetHref(t.dataPath,s,g),b!==void 0)}catch(g){return N(p,{operation:"document",path:s,error:g}),m.failureDocument("failed")}if(l.kind!=="unsanitized-markdown")return l;const w=await U(l.html,{scope:a,signal:n.signal});return w.status==="sanitized"?{kind:"markdown",name:l.name,htmlContent:w.html,headings:l.headings,lang:l.lang,edit:l.edit}:(w.cause!==null&&N(p,{operation:"document",path:s,error:w.cause}),m.failureDocument(w.reason))},xr=async n=>{if(e.notices===void 0)return he;try{return Nt(await e.notices(n))}catch(a){return v(a,{operation:"notices"},n.signal,p),he}},De=async(n,a,s,i)=>{const u=z(a,m.EXPLORER_DATA_QUERY.path);if(u===null||!m.isAcceptableDocumentPath(u))return{status:"answered",response:O({reason:"invalid"},s)};const l=m.readExplorerAssetDisplay(a);if(l===null||!i.has(l))return{status:"answered",response:O({reason:"invalid"},s)};if(h.deniesPath(u))return Z(p,{operation:"asset",path:u}),{status:"answered",response:O({reason:"forbidden"},s)};const w=await W(n,u);if(w.status==="error")return{status:"answered",response:O(w.failure,s)};try{const g=await e.asset(n,u,w.readPath,{delivery:l}),R=l==="file"?Ye(g):ge(g);return"kind"in R?{status:"answered",response:ct(R.url,s)}:{status:"admitted",path:u,display:l,file:R}}catch(g){return{status:"answered",response:O(v(g,{operation:"asset",path:u},n.signal,p),s)}}},vr=async(n,a,s)=>{const i=await De(n,a,s,zt);if(i.status==="answered")return i.response;const{path:u,display:l,file:w}=i;try{return l==="text"?await st(n.request,w,s,t.legacyTextEncoding,j):l==="workbook"?await at(n.request,w,s):await rt(n.request,w,s,j)}catch(g){return O(v(g,{operation:"asset",path:u},n.signal,p),s)}},_r=async(n,a,s)=>{const i=fr(n,a,s,t.legacyTextEncoding,j);return i.kind==="respond"?i:ye(i.selection,await lr(a,t.legacyTextEncoding))},Sr=async(n,a,s)=>{const i=await De(n,a,s,Ut);if(i.status==="answered")return{kind:"response",response:i.response};const{path:u,display:l,file:w}=i,g=L=>O(v(L,{operation:"asset",path:u},n.signal,p),s);let R;try{R=l==="text"?await _r(n.request,w,s):ur(n.request,w,s,j)}catch(L){return{kind:"response",response:g(L)}}if(R.kind==="respond")return{kind:"response",response:R.response};const{bridge:D}=w;return D===void 0?(N(p,{operation:"asset",path:u,error:new TypeError("[markdown-explorer] the asset port must attach a bridge to a file the host streams itself")}),{kind:"response",response:O({reason:"failed"},s)}):{kind:"file",status:R.status,headers:R.headers,bridge:{uri:D.uri,storageVersion:D.storageVersion},range:R.range,length:R.length,fail:L=>g(Gt(D.readFailure,L))}},Pr=async(n,a)=>{if(h.deniesPath(a))return Z(p,{operation:"text",path:a}),m.failureDocument("forbidden");const s=await W(n,a);if(s.status==="error")return{kind:"failure",failure:s.failure};try{const i=ge(await e.asset(n,a,s.readPath,{delivery:"text"})),u=await wt(i,y,t.legacyTextEncoding);return u===null?m.failureDocument("unsupported"):{kind:"text",name:i.name,text:u.text,truncated:u.truncated,url:m.explorerAssetHref(t.dataPath,a,i.version)}}catch(i){return{kind:"failure",failure:v(i,{operation:"text",path:a},n.signal,p)}}},Q=async(n,a,s)=>h.deniesPath(s)?(Z(p,{operation:a,path:s}),{status:"error",failure:{reason:"forbidden"}}):W(n,s),Ir=async(n,a,s)=>{const i=await Q(a,"edit",s);if(i.status==="error")return{kind:"failure",failure:i.failure};try{return _t(await n.source(a,s,i.readPath),T)}catch(u){return{kind:"failure",failure:v(u,{operation:"edit",path:s},a.signal,p)}}},Dr=async(n,a,s,i,u)=>{const l=await Q(a,"save",s);if(l.status==="error")return{kind:"failure",failure:l.failure};try{return St(await n.save(a,s,l.readPath,{text:u,baseVersion:i}),T)}catch(w){return{kind:"failure",failure:v(w,{operation:"save",path:s},a.signal,p)}}},Lr=async(n,a,s,i,u)=>{const l=await Q(a,"preview",i);if(l.status==="error")return{kind:"failure",failure:l.failure};let w;try{w=Pt(await n.preview(a,i,l.readPath,u))}catch(R){return{kind:"failure",failure:v(R,{operation:"preview",path:i},a.signal,p)}}if("kind"in w)return w.kind==="failure"?w:m.failureDocument("failed");const g=await U(w.html,{scope:s,signal:a.signal});return g.status==="sanitized"?{kind:"preview",htmlContent:g.html,headings:w.headings}:(g.cause!==null&&N(p,{operation:"preview",path:i,error:g.cause}),m.failureDocument(g.reason))},Nr=async(n,a,s)=>{const i=await Q(a,"revisions",s);if(i.status==="error")return{kind:"failure",failure:i.failure};try{return{kind:"revisions",revisions:It(await n.revisions(a,s,i.readPath))}}catch(u){return{kind:"failure",failure:v(u,{operation:"revisions",path:s},a.signal,p)}}},$r=async(n,a,s,i)=>{const u=await Q(a,"revision",s);if(u.status==="error")return{kind:"failure",failure:u.failure};try{return{kind:"revision",id:i,text:Dt(await n.revision(a,s,u.readPath,i),T)}}catch(l){return{kind:"failure",failure:v(l,{operation:"revision",path:s},a.signal,p)}}},jr=async(n,a,s,i,u,l)=>{const w=z(u,m.EXPLORER_DATA_QUERY.path);if(w===null||!m.isAcceptableDocumentPath(w))return O({reason:"invalid"},l);if(a==="edit")return S(200,JSON.stringify(await Ir(n,s,w)),l);if(a==="revisions")return S(200,JSON.stringify(await Nr(n,s,w)),l);if(a==="revision"){const D=z(u,m.EXPLORER_DATA_QUERY.revision);return m.isExplorerEditToken(D)?S(200,JSON.stringify(await $r(n,s,w,D)),l):O({reason:"invalid"},l)}const g=z(u,m.EXPLORER_DATA_QUERY.base);if(a==="save"&&!m.isExplorerEditToken(g))return O({reason:"invalid"},l);const R=await rn(s.request,T);return R.status==="error"?O(R.failure,l):a==="preview"?S(200,JSON.stringify(await Lr(n,s,i,w,R.text)),l):S(200,JSON.stringify(await Dr(n,s,w,g,R.text)),l)},Cr=async({request:n,url:a,params:s})=>{const i=Ke(await K(n,We));if(i.status==="forbidden")throw Xr.accessFailureResponse("forbidden",{headers:we(i.headers)});const u=we(i.headers);if(u.set("Cache-Control",mr),i.status==="signed-out")throw Yt("signedOutPage",yr({request:n,url:a},u));const l=$.resolveExplorerLocation(d,s["*"],a.searchParams);if(l.kind==="redirect")throw ee.redirect(l.href,{headers:u});const{principal:w}=i,g=Qe(o,ke(w));if(l.kind==="document-id"){if(A===void 0)throw new TypeError("[markdown-explorer] an ID URL was resolved without the documentIds ports");const R=l.id===null?Vt:await xe(A,{principal:w,request:n,signal:n.signal,refresh:!1},l.id);if(R.status==="resolved")throw ee.redirect(Mr(l.opens,R),{headers:u});return ee.data(Le(w,g,n,l.location,{id:l.id,failure:R.failure}),{status:m.EXPLORER_FAILURE_STATUS[R.failure.reason],headers:u})}return ee.data(Le(w,g,n,l.location,null),{headers:u})},Mr=(n,a)=>$.explorerHref(d,$.documentIdOpeningTarget(n,a.path,a.sourceId)),Le=(n,a,s,i,u)=>{const l=M.get(i.source);if(l===void 0)throw new RangeError(`[markdown-explorer] no source for ${x.describeValue(i.source)}`);const w={signal:s.signal,timeoutMs:k,late:null,handOverMs:k};return{scope:a,sources:c.map(g=>({id:g.id,label:gr(g,n)})),settings:$.parseViewSettings(Wt(X,s),ce),tree:i.view==="single"?null:{sourceId:i.source,result:fe(w,g=>Se(l,n,a,s,g).then(R=>R.result))},documents:Jt(i).map(g=>({path:g,document:fe(w,R=>Ie({principal:n,request:s,signal:R,refresh:!1},a,g))})),notices:fe({signal:s.signal,timeoutMs:k,late:he,handOverMs:0},g=>xr({principal:n,request:s,signal:g,refresh:!1})),documentId:u}},Ne=async(n,a)=>{const s=Ke(await K(n,a));return{authentication:s,headers:we(s.headers)}},$e=async n=>{let a;try{a=await Ne(n,We)}catch(u){return{status:"answered",response:O(v(Je(u),{operation:"authenticate"},n.signal,p))}}const{authentication:s,headers:i}=a;return s.status==="signed-out"?{status:"answered",response:O({reason:"unauthorized"},i)}:s.status==="forbidden"?{status:"answered",response:O({reason:"forbidden"},i)}:{status:"signed-in",principal:s.principal,headers:i}},zr=async(n,a,s)=>{const i=await $e(a);if(i.status==="answered")return i.response;const{principal:u,headers:l}=i;if(n==="asset")return vr({principal:u,request:a,signal:a.signal,refresh:!1},s,l);const w=Qe(o,ke(u));l.set(m.EXPLORER_SCOPE_HEADER,w);const g={principal:u,request:a,signal:a.signal,refresh:!1},R=()=>O({reason:"invalid"},l);if(n==="document"){const _=z(s,m.EXPLORER_DATA_QUERY.path);if(_===null||!m.isAcceptableDocumentPath(_))return R();const H=a.headers.has(m.EXPLORER_PROOF_HEADER);return H&&!er(a)?O({reason:"forbidden"},l):S(200,JSON.stringify(await Ie({...g,refresh:H},w,_)),l)}if(n==="text"){const _=z(s,m.EXPLORER_DATA_QUERY.path);return _===null||!m.isAcceptableDocumentPath(_)?R():S(200,JSON.stringify(await Pr(g,_)),l)}if(n==="edit"||n==="save"||n==="preview"||n==="revisions"||n==="revision")return b===void 0?O({reason:"not-found"},l):jr(b,n,g,w,s,l);if(n==="issue-id"){if(A===void 0)return O({reason:"not-found"},l);const _=z(s,m.EXPLORER_DATA_QUERY.path);return _===null||!$.hasDocumentUrl(_)?R():rr(await Er(A,g,_),l)}if(n==="resolve-id"){if(A===void 0)return O({reason:"not-found"},l);const _=z(s,m.EXPLORER_DATA_QUERY.id);if(_===null||!m.isCanonicalDocumentId(_))return R();const H=await xe(A,g,_);return rr(H.status==="resolved"?{status:"ok",path:H.path,source:H.sourceId}:H,l)}const D=z(s,m.EXPLORER_DATA_QUERY.source),L=z(s,m.EXPLORER_DATA_QUERY.path);if(D===null||(n==="children"||n==="ancestors"||n==="reveal")&&(L===null||!m.isAcceptableDocumentPath(L)))return R();const C=M.get(D);if(C===void 0)return O({reason:"not-found"},l);if(n==="tree")return S(200,(await Se(C,u,w,a,a.signal)).json,l);if(n==="refresh"){const _=await Tr(C,u,w,a);return a.signal.aborted||Rr(C,ue(C,w)),S(200,_.json,l)}return n==="ancestors"?C.ancestors===void 0||L===null?O({reason:"not-found"},l):S(200,JSON.stringify(await Or(C,C.ancestors,g,L)),l):n==="reveal"?L===null?R():S(200,JSON.stringify(await Ar(C,g,L)),l):C.children===void 0||L===null?O({reason:"not-found"},l):S(200,JSON.stringify(await kr(C,C.children,g,L)),l)},Ur=async n=>{const{authentication:a,headers:s}=await Ne(n,Mt);if(!s.keys().next().done)throw new TypeError("[markdown-explorer] authenticate returned headers in read-only mode; a read-only authentication must only read the session (none was forwarded)");return a.status==="signed-in"},je=t.embeds.linkCardEndpoint===null?null:r.createLinkCardHandler({authorize:Ur}),Vr=async(n,a)=>{try{return await n(a)}catch(s){return O(v(Je(s),{operation:"authenticate"},a.signal,p))}},le=async(n,a,s)=>{if(new URL(n.url).pathname.endsWith(".data"))return O({reason:"not-found"});if(!m.isExplorerDataOperation(s))return O({reason:"not-found"});if(s==="link-card"){if(je===null)return O({reason:"not-found"});const u=qe(n,s);return u!==null?u:Vr(je,n)}if(Zt.has(s)&&b===void 0)return O({reason:"not-found"});if(Qt.has(s)&&A===void 0)return O({reason:"not-found"});const i=qe(n,s);if(i!==null)return i;if(s==="refresh"&&!er(n))return O({reason:"forbidden"});if((s==="save"||s==="preview")&&!qt(n))return O({reason:"forbidden"});if(s==="issue-id"&&!en(n))return O({reason:"forbidden"});try{return await zr(s,n,a.searchParams)}catch(u){return O(v(u,{operation:s},n.signal,p))}},Fr=async(n,a,s)=>{if(s!=="asset"||n.method.toUpperCase()!=="GET"||new URL(n.url).pathname.endsWith(".data"))return{kind:"response",response:await le(n,a,s)};try{const i=await $e(n);return i.status==="answered"?{kind:"response",response:i.response}:await Sr({principal:i.principal,request:n,signal:n.signal,refresh:!1},a.searchParams,i.headers)}catch(i){return{kind:"response",response:O(v(i,{operation:"asset"},n.signal,p))}}};return Object.freeze({loader:Cr,headers:an,dataLoader:({request:n,url:a,params:s})=>le(n,a,s["*"]),dataAction:({request:n,url:a,params:s})=>le(n,a,s["*"]),planData:({request:n,url:a,params:s})=>Fr(n,a,s["*"]),forgetTree:n=>{if(typeof n!="string")throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${x.describeValue(n)}`);F.forget(n)}})};exports.ASSET_CONTENT_SECURITY_POLICIES=se;exports.ExplorerError=dt;exports.createExplorerServer=cn;
|