@aiquants/markdown-explorer 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +30 -4
  3. package/dist/ExplorerSplit-CN5TvRj6.js +1495 -0
  4. package/dist/ExplorerSplit-CUIbSLQm.cjs +1 -0
  5. package/dist/MultiLayout-BDcQSpa6.cjs +1 -0
  6. package/dist/{MultiLayout-8s7q3-Hm.js → MultiLayout-hPmV-bae.js} +69 -66
  7. package/dist/{NativeScrollBar-DqkutcGb.cjs → NativeScrollBar-CHEQgaVx.cjs} +1 -1
  8. package/dist/{NativeScrollBar-D3VDRQqf.js → NativeScrollBar-DYEv2GLV.js} +1 -1
  9. package/dist/TreeLayout-BDaIyoGT.cjs +1 -0
  10. package/dist/TreeLayout-CqzxLpoM.js +23 -0
  11. package/dist/core/contracts.d.cts +23 -7
  12. package/dist/core/contracts.d.ts +23 -7
  13. package/dist/core/labels.d.cts +4 -0
  14. package/dist/core/labels.d.ts +4 -0
  15. package/dist/dataRoute-CUXlMhUJ.cjs +1 -0
  16. package/dist/{dataRoute-Dl6xmEFs.js → dataRoute-Ce6EIuu4.js} +69 -63
  17. package/dist/index-B3nShkkt.cjs +3 -0
  18. package/dist/{index-Dv9lUZqD.js → index-gJp1iXTc.js} +1020 -916
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.js +3 -3
  21. package/dist/{location-CaNtUswk.js → location-CtM94G0O.js} +1 -1
  22. package/dist/{location-2QZADLiv.cjs → location-FavgY_gB.cjs} +1 -1
  23. package/dist/sanitizeWorker.cjs +1 -1
  24. package/dist/sanitizeWorker.js +1 -1
  25. package/dist/server/errors.d.cts +1 -1
  26. package/dist/server/errors.d.ts +1 -1
  27. package/dist/server/ports.d.cts +1 -0
  28. package/dist/server/ports.d.ts +1 -0
  29. package/dist/server.cjs +1 -1
  30. package/dist/server.js +753 -716
  31. package/dist/styles/markdown-explorer.css +1 -1
  32. package/docs/behavior/dom-hooks.md +6 -3
  33. package/docs/behavior/layout.md +6 -0
  34. package/docs/behavior/localization.md +4 -1
  35. package/docs/behavior/security.md +11 -4
  36. package/docs/behavior/url-contract.md +1 -0
  37. package/package.json +4 -3
  38. package/dist/ExplorerSplit-rUVsf5i-.cjs +0 -1
  39. package/dist/ExplorerSplit-uX2ojZe8.js +0 -1479
  40. package/dist/MultiLayout-ZK2V9nms.cjs +0 -1
  41. package/dist/TreeLayout-C7ZNnaOr.js +0 -22
  42. package/dist/TreeLayout-DkTVgxxb.cjs +0 -1
  43. package/dist/dataRoute-DYjYBiXF.cjs +0 -1
  44. package/dist/index-CLe6vRXs.cjs +0 -3
package/dist/server.js CHANGED
@@ -1,20 +1,21 @@
1
- import { b as ut, c as Nt, f as _e, d as At, g as It, h as Mt, j as vt, E as Pt, i as te, k as $t, l as jt, r as lt, m as Lt, n as zt, o as dt, p as Dt, q as Ct, s as fe, t as ne, e as Ht } from "./dataRoute-Dl6xmEFs.js";
2
- import { D as mo, M as po, u as wo } from "./dataRoute-Dl6xmEFs.js";
3
- import { createHash as Bt, createHmac as Ft } from "node:crypto";
4
- import { createLinkCardHandler as Ut } from "@aiquants/markdown/server";
5
- import { data as je, redirect as Xt } from "react-router";
6
- import { w as Gt, d as Jt, r as Wt, i as Yt, a as Kt, p as Vt, b as Zt, f as Qt, N as qt } from "./location-CaNtUswk.js";
7
- import { existsSync as er, statSync as tr, realpathSync as rr, constants as ce } from "node:fs";
8
- import { extname as nr, isAbsolute as Le, relative as ze, sep as De, join as or, resolve as sr } from "node:path";
1
+ import { b as mt, c as Lt, f as Re, d as jt, g as zt, h as Dt, j as Ct, E as Ht, i as ee, k as Bt, l as Ft, r as pt, m as Ut, n as Xt, o as wt, p as Gt, q as Jt, s as de, t as te, e as je } from "./dataRoute-Ce6EIuu4.js";
2
+ import { D as Oo, M as _o, u as Ro } from "./dataRoute-Ce6EIuu4.js";
3
+ import { createHash as Yt, createHmac as Wt } from "node:crypto";
4
+ import { createLinkCardHandler as Kt } from "@aiquants/markdown/server";
5
+ import { crossOriginRefusal as Vt, NO_CROSS_ORIGIN_NAVIGATION as Zt } from "@aiquants/request-isolation";
6
+ import { data as ze, redirect as Qt } from "react-router";
7
+ import { w as qt, d as er, r as tr, i as rr, a as nr, p as or, b as sr, f as ar, N as ir } from "./location-CtM94G0O.js";
8
+ import { existsSync as cr, statSync as ur, realpathSync as lr, constants as ue } from "node:fs";
9
+ import { extname as dr, isAbsolute as De, relative as Ce, sep as He, join as fr, resolve as mr } from "node:path";
9
10
  import { fileURLToPath as Se } from "node:url";
10
- import { Worker as ar } from "node:worker_threads";
11
- import { open as ft, lstat as ir, realpath as cr, readdir as ur } from "node:fs/promises";
12
- import { Readable as lr } from "node:stream";
13
- const Ce = Object.freeze({ kind: "anonymous" }), io = Object.freeze({
14
- authenticate: async () => ({ status: "signed-in", principal: Ce }),
15
- principalKey: () => Ce.kind,
11
+ import { Worker as pr } from "node:worker_threads";
12
+ import { open as ht, lstat as wr, realpath as hr, readdir as gr } from "node:fs/promises";
13
+ import { Readable as yr } from "node:stream";
14
+ const Be = Object.freeze({ kind: "anonymous" }), bo = Object.freeze({
15
+ authenticate: async () => ({ status: "signed-in", principal: Be }),
16
+ principalKey: () => Be.kind,
16
17
  signedOutPage: (e, t) => new Response(null, { status: 401, headers: t })
17
- }), dr = "application/octet-stream", mt = "application/pdf", fr = /* @__PURE__ */ new Set([
18
+ }), Er = "application/octet-stream", gt = "application/pdf", br = /* @__PURE__ */ new Set([
18
19
  "image/png",
19
20
  "image/apng",
20
21
  "image/jpeg",
@@ -40,8 +41,8 @@ const Ce = Object.freeze({ kind: "anonymous" }), io = Object.freeze({
40
41
  "video/webm",
41
42
  "video/ogg",
42
43
  "video/quicktime",
43
- mt
44
- ]), pt = "default-src 'none'; media-src 'self'; style-src 'unsafe-inline'", mr = `${pt}; sandbox`, pr = `${pt}; sandbox allow-same-origin`, He = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u, wr = /^[\t\n\r ]+|[\t\n\r ]+$/gu, Ne = /^[\t ]+|[\t ]+$/gu, hr = (e) => {
44
+ gt
45
+ ]), yt = "default-src 'none'; media-src 'self'; style-src 'unsafe-inline'", Sr = `${yt}; sandbox`, Tr = `${yt}; sandbox allow-same-origin`, Fe = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u, xr = /^[\t\n\r ]+|[\t\n\r ]+$/gu, Ae = /^[\t ]+|[\t ]+$/gu, kr = (e) => {
45
46
  const t = [];
46
47
  let r = "", n = 0;
47
48
  for (; ; ) {
@@ -53,71 +54,71 @@ const Ce = Object.freeze({ kind: "anonymous" }), io = Object.freeze({
53
54
  n += e[n] === "\\" ? 2 : 1;
54
55
  if (n = Math.min(n + 1, e.length), r += e.slice(a, n), n < e.length) continue;
55
56
  }
56
- if (t.push(r.replace(Ne, "")), r = "", n >= e.length) return t;
57
+ if (t.push(r.replace(Ae, "")), r = "", n >= e.length) return t;
57
58
  n += 1;
58
59
  }
59
- }, gr = (e) => {
60
- const t = e.replace(wr, ""), r = t.indexOf("/");
60
+ }, Or = (e) => {
61
+ const t = e.replace(xr, ""), r = t.indexOf("/");
61
62
  if (r < 0) return null;
62
- const n = t.slice(0, r), a = t.indexOf(";", r + 1), o = t.slice(r + 1, a < 0 ? t.length : a).replace(/[\t\n\r ]+$/u, "");
63
- return He.test(n) && He.test(o) ? `${n}/${o}`.toLowerCase() : null;
64
- }, yr = (e) => {
63
+ const n = t.slice(0, r), a = t.indexOf(";", r + 1), s = t.slice(r + 1, a < 0 ? t.length : a).replace(/[\t\n\r ]+$/u, "");
64
+ return Fe.test(n) && Fe.test(s) ? `${n}/${s}`.toLowerCase() : null;
65
+ }, _r = (e) => {
65
66
  let t = null;
66
- for (const r of hr(e)) {
67
- const n = gr(r);
67
+ for (const r of kr(e)) {
68
+ const n = Or(r);
68
69
  n !== null && n !== "*/*" && (t = n);
69
70
  }
70
71
  return t;
71
- }, Er = /['()*]/gu, br = (e) => encodeURIComponent(e).replace(Er, (t) => `%${t.charCodeAt(0).toString(16).toUpperCase()}`), Sr = Object.freeze({
72
+ }, Rr = /['()*]/gu, Ar = (e) => encodeURIComponent(e).replace(Rr, (t) => `%${t.charCodeAt(0).toString(16).toUpperCase()}`), Nr = Object.freeze({
72
73
  "Cache-Control": "private, max-age=60, stale-while-revalidate=600, no-transform",
73
74
  Vary: "Cookie"
74
- }), Tr = (e, t) => {
75
- const r = yr(e), n = r !== null && fr.has(r), a = n && (r.startsWith("audio/") || r.startsWith("video/"));
75
+ }), Ir = (e, t) => {
76
+ const r = _r(e), n = r !== null && br.has(r), a = n && (r.startsWith("audio/") || r.startsWith("video/"));
76
77
  return {
77
- contentType: r === null ? dr : r,
78
+ contentType: r === null ? Er : r,
78
79
  inline: n,
79
80
  headers: {
80
81
  "X-Content-Type-Options": "nosniff",
81
- "Content-Disposition": `${n ? "inline" : "attachment"}; filename*=UTF-8''${br(t)}`,
82
- ...r === mt ? {} : { "Content-Security-Policy": a ? pr : mr },
82
+ "Content-Disposition": `${n ? "inline" : "attachment"}; filename*=UTF-8''${Ar(t)}`,
83
+ ...r === gt ? {} : { "Content-Security-Policy": a ? Tr : Sr },
83
84
  "Cross-Origin-Resource-Policy": "same-origin"
84
85
  }
85
86
  };
86
- }, xr = /^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu, me = Object.freeze({ kind: "whole" }), Be = Object.freeze({ kind: "unsatisfiable" }), kr = (e, t, r) => {
87
+ }, Mr = /^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu, we = Object.freeze({ kind: "whole" }), Ue = Object.freeze({ kind: "unsatisfiable" }), vr = (e, t, r) => {
87
88
  const n = e.get("Range");
88
- if (n === null) return me;
89
+ if (n === null) return we;
89
90
  const a = e.get("If-Range");
90
- if (a !== null && a !== r) return me;
91
- const o = xr.exec(n);
92
- if (o === null) return me;
93
- const [, i, l, y] = o;
91
+ if (a !== null && a !== r) return we;
92
+ const s = Mr.exec(n);
93
+ if (s === null) return we;
94
+ const [, c, f, y] = s;
94
95
  if (y !== void 0) {
95
- const w = Number(y);
96
- if (w === 0) return Be;
97
- const O = Math.max(0, t - w);
98
- return { kind: "partial", range: { offset: O, length: t - O } };
96
+ const h = Number(y);
97
+ if (h === 0) return Ue;
98
+ const x = Math.max(0, t - h);
99
+ return { kind: "partial", range: { offset: x, length: t - x } };
99
100
  }
100
- const x = Number(i), f = l === "" ? Number.POSITIVE_INFINITY : Number(l);
101
- return f < x ? me : x >= t ? Be : { kind: "partial", range: { offset: x, length: Math.min(f, t - 1) - x + 1 } };
102
- }, Fe = "W/", Or = (e) => {
101
+ const k = Number(c), p = f === "" ? Number.POSITIVE_INFINITY : Number(f);
102
+ return p < k ? we : k >= t ? Ue : { kind: "partial", range: { offset: k, length: Math.min(p, t - 1) - k + 1 } };
103
+ }, Xe = "W/", Pr = (e) => {
103
104
  const t = [];
104
105
  let r = 0, n = !1;
105
106
  for (let a = 0; a < e.length; a += 1)
106
- e[a] === '"' ? n = !n : e[a] === "," && !n && (t.push(e.slice(r, a).replace(Ne, "")), r = a + 1);
107
- return t.push(e.slice(r).replace(Ne, "")), t;
108
- }, Ue = (e) => e.startsWith(Fe) ? e.slice(Fe.length) : e, Rr = (e, t) => {
107
+ e[a] === '"' ? n = !n : e[a] === "," && !n && (t.push(e.slice(r, a).replace(Ae, "")), r = a + 1);
108
+ return t.push(e.slice(r).replace(Ae, "")), t;
109
+ }, Ge = (e) => e.startsWith(Xe) ? e.slice(Xe.length) : e, $r = (e, t) => {
109
110
  if (e === null) return !1;
110
- const r = Or(e);
111
+ const r = Pr(e);
111
112
  if (r.length === 1 && r[0] === "*") return !0;
112
- const n = Ue(t);
113
- return r.some((a) => Ue(a) === n);
114
- }, _r = (e, t) => {
113
+ const n = Ge(t);
114
+ return r.some((a) => Ge(a) === n);
115
+ }, Lr = (e, t) => {
115
116
  let r = t;
116
117
  return e.pipeThrough(
117
118
  new TransformStream({
118
119
  transform: (n, a) => {
119
- const o = n.byteLength > r ? n.subarray(0, r) : n;
120
- r -= o.byteLength, a.enqueue(o), r === 0 && a.terminate();
120
+ const s = n.byteLength > r ? n.subarray(0, r) : n;
121
+ r -= s.byteLength, a.enqueue(s), r === 0 && a.terminate();
121
122
  },
122
123
  flush: (n) => {
123
124
  r > 0 && n.error(new RangeError("[markdown-explorer] the asset ended before its declared length"));
@@ -126,86 +127,103 @@ const Ce = Object.freeze({ kind: "anonymous" }), io = Object.freeze({
126
127
  );
127
128
  }, Te = async (e, t, r, n, a) => {
128
129
  if (n !== null && r.set("Content-Length", String(n)), e.method.toUpperCase() === "HEAD") return new Response(null, { status: t, headers: r });
129
- const o = await a();
130
- return new Response(n === null ? o : _r(o, n), { status: t, headers: r });
131
- }, Nr = (e, t) => {
130
+ const s = await a();
131
+ return new Response(n === null ? s : Lr(s, n), { status: t, headers: r });
132
+ }, jr = (e, t) => {
132
133
  const r = new Headers(e);
133
134
  for (const [n, a] of Object.entries({ "Accept-Ranges": "bytes", "Content-Range": `bytes */${t}`, "Cache-Control": "private, no-store", "X-Content-Type-Options": "nosniff" })) r.set(n, a);
134
135
  return new Response(null, { status: 416, headers: r });
135
- }, Ar = async (e, t, r) => {
136
- const n = `"${t.version}"`, a = Tr(t.contentType, t.name), o = new Headers(r);
137
- for (const [y, x] of Object.entries({ ...a.headers, ...Sr, ETag: n })) o.set(y, x);
138
- if (Rr(e.headers.get("If-None-Match"), n)) return new Response(null, { status: 304, headers: o });
139
- if (o.set("Content-Type", a.contentType), t.size === null) return Te(e, 200, o, null, () => t.open(null));
136
+ }, zr = async (e, t, r) => {
137
+ const n = `"${t.version}"`, a = Ir(t.contentType, t.name), s = new Headers(r);
138
+ for (const [y, k] of Object.entries({ ...a.headers, ...Nr, ETag: n })) s.set(y, k);
139
+ if ($r(e.headers.get("If-None-Match"), n)) return new Response(null, { status: 304, headers: s });
140
+ if (s.set("Content-Type", a.contentType), t.size === null) return Te(e, 200, s, null, () => t.open(null));
140
141
  if (t.size === 0)
141
- return o.set("Content-Length", "0"), new Response(null, { status: 200, headers: o });
142
- o.set("Accept-Ranges", "bytes");
143
- const i = kr(e.headers, t.size, n);
144
- if (i.kind === "unsatisfiable") return Nr(r, t.size);
145
- if (i.kind === "whole") return Te(e, 200, o, t.size, () => t.open(null));
146
- const { range: l } = i;
147
- return o.set("Content-Range", `bytes ${l.offset}-${l.offset + l.length - 1}/${t.size}`), Te(e, 206, o, l.length, () => t.open(l));
142
+ return s.set("Content-Length", "0"), new Response(null, { status: 200, headers: s });
143
+ s.set("Accept-Ranges", "bytes");
144
+ const c = vr(e.headers, t.size, n);
145
+ if (c.kind === "unsatisfiable") return jr(r, t.size);
146
+ if (c.kind === "whole") return Te(e, 200, s, t.size, () => t.open(null));
147
+ const { range: f } = c;
148
+ return s.set("Content-Range", `bytes ${f.offset}-${f.offset + f.length - 1}/${t.size}`), Te(e, 206, s, f.length, () => t.open(f));
148
149
  }, xe = (e, t) => {
149
150
  const r = new AbortController(), n = t(AbortSignal.any([e.signal, r.signal]));
150
151
  return new Promise((a) => {
151
- let o;
152
- const i = setTimeout(() => {
153
- a(e.late), o = setTimeout(() => r.abort(), e.handOverMs);
154
- }, e.timeoutMs), l = () => {
155
- clearTimeout(i), clearTimeout(o);
152
+ let s;
153
+ const c = setTimeout(() => {
154
+ a(e.late), s = setTimeout(() => r.abort(), e.handOverMs);
155
+ }, e.timeoutMs), f = () => {
156
+ clearTimeout(c), clearTimeout(s);
156
157
  };
157
158
  n.then(
158
159
  (y) => {
159
- l(), a(y);
160
+ f(), a(y);
160
161
  },
161
162
  () => {
162
- l(), a(e.late);
163
+ f(), a(e.late);
163
164
  }
164
165
  );
165
166
  });
166
- }, Ir = Object.freeze({
167
+ }, Dr = Object.freeze({
167
168
  error: (e, t) => {
168
169
  console.error(e, t);
169
170
  }
170
- }), wt = /* @__PURE__ */ Symbol.for("@aiquants/markdown-explorer:ExplorerError");
171
+ }), Et = /* @__PURE__ */ Symbol.for("@aiquants/markdown-explorer:ExplorerError");
171
172
  class Ee extends Error {
172
173
  reason;
173
174
  code;
174
175
  constructor(t, r = {}) {
175
- if (!ut(t)) throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${JSON.stringify(t)}`);
176
- if (r.code !== void 0 && !Nt(r.code)) throw new RangeError(`[markdown-explorer] an ExplorerError code must be 1 to 64 lowercase letters, digits or hyphens; got ${JSON.stringify(r.code)}`);
177
- super(`[markdown-explorer] ${t}`, r.cause === void 0 ? void 0 : { cause: r.cause }), this.name = "ExplorerError", this.reason = t, this.code = r.code, Object.defineProperty(this, wt, { value: !0 });
176
+ if (!mt(t)) throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${JSON.stringify(t)}`);
177
+ if (r.code !== void 0 && !Lt(r.code)) throw new RangeError(`[markdown-explorer] an ExplorerError code must be 1 to 64 lowercase letters, digits or hyphens; got ${JSON.stringify(r.code)}`);
178
+ super(`[markdown-explorer] ${t}`, r.cause === void 0 ? void 0 : { cause: r.cause }), this.name = "ExplorerError", this.reason = t, this.code = r.code, Object.defineProperty(this, Et, { value: !0 });
178
179
  }
179
180
  }
180
- const Mr = (e) => e instanceof Error && Object.hasOwn(e, wt) && ut(e.reason), vr = (e) => typeof e == "object" && e !== null && e.name === "AbortError", Ie = (e, t, r) => {
181
+ const Cr = (e) => e instanceof Error && Object.hasOwn(e, Et) && mt(e.reason), Hr = (e) => typeof e == "object" && e !== null && e.name === "AbortError", Ie = (e, t, r) => {
181
182
  try {
182
183
  e.error(t, r);
183
184
  } catch (n) {
184
185
  console.error("[markdown-explorer] the logger threw while reporting a failure", { operation: r.operation, error: n });
185
186
  }
186
- }, ee = (e, t) => Ie(e, `[markdown-explorer] ${t.operation} failed`, t), Pr = (e, t) => Ie(e, `[markdown-explorer] ${t.operation} left out an entry`, t), $r = (e, t) => Ie(e, `[markdown-explorer] ${t.operation} refused a path the deny rules match`, { ...t, error: new RangeError("[markdown-explorer] the path matches a deny rule") }), Xe = (e, t) => {
187
+ }, ne = (e, t) => Ie(e, `[markdown-explorer] ${t.operation} failed`, t), Br = (e, t) => Ie(e, `[markdown-explorer] ${t.operation} left out an entry`, t), Je = (e, t) => Ie(e, `[markdown-explorer] ${t.operation} refused a path the deny rules match`, { ...t, error: new RangeError("[markdown-explorer] the path matches a deny rule") }), Ye = (e, t) => {
187
188
  e === null || typeof e != "object" && typeof e != "function" || Promise.resolve(e).then(void 0, t);
188
- }, Q = (e, t, r, n) => Mr(e) ? _e(e.reason, e.code) : (vr(e) || r.aborted || ee(n, { ...t, error: e }), { reason: "failed" }), Ge = (e, t) => {
189
+ }, Z = (e, t, r, n) => Cr(e) ? Re(e.reason, e.code) : (Hr(e) || r.aborted || ne(n, { ...t, error: e }), { reason: "failed" }), Fr = 2 * 1024 * 1024, Ur = 256 * 1024 * 1024, Xr = async (e, t) => {
190
+ const r = e.getReader(), n = new Uint8Array(t);
191
+ let a = 0;
192
+ for (; a < t; ) {
193
+ const { done: s, value: c } = await r.read();
194
+ if (s) return n.subarray(0, a);
195
+ const f = c.subarray(0, t - a);
196
+ n.set(f, a), a += f.byteLength;
197
+ }
198
+ return r.cancel().catch(() => {
199
+ }), n;
200
+ }, Gr = async (e, t) => {
201
+ if (e.size === 0) return { text: "", truncated: !1 };
202
+ const r = e.size !== null && e.size > t, n = e.size === null ? t + 1 : Math.min(e.size, t), a = await Xr(await e.open(r ? { offset: 0, length: t } : null), n);
203
+ if (e.size !== null && a.byteLength < n) throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");
204
+ const s = r || a.byteLength > t, c = s ? a.subarray(0, t) : a;
205
+ return c.includes(0) ? null : { text: new TextDecoder("utf-8").decode(c, { stream: s }), truncated: s };
206
+ }, We = (e, t) => {
189
207
  if (!Number.isSafeInteger(t) || t <= 0) throw new RangeError(`[markdown-explorer] a cache ${e} must be a positive integer; got ${String(t)}`);
190
- }, ht = (e, t) => {
191
- Ge("capacity", e), t !== void 0 && Ge("weight budget", t.max);
208
+ }, bt = (e, t) => {
209
+ We("capacity", e), t !== void 0 && We("weight budget", t.max);
192
210
  const r = /* @__PURE__ */ new Map();
193
211
  let n = 0;
194
- const a = (o) => {
195
- const i = r.get(o);
196
- i !== void 0 && (r.delete(o), n -= i.weight);
212
+ const a = (s) => {
213
+ const c = r.get(s);
214
+ c !== void 0 && (r.delete(s), n -= c.weight);
197
215
  };
198
216
  return {
199
- get: (o) => {
200
- const i = r.get(o);
201
- if (i !== void 0)
202
- return r.delete(o), r.set(o, i), i.value;
217
+ get: (s) => {
218
+ const c = r.get(s);
219
+ if (c !== void 0)
220
+ return r.delete(s), r.set(s, c), c.value;
203
221
  },
204
- set: (o, i) => {
205
- a(o);
206
- const l = t === void 0 ? 0 : t.of(o, i);
207
- if (!(t !== void 0 && l > t.max)) {
208
- r.set(o, { value: i, weight: l }), n += l;
222
+ set: (s, c) => {
223
+ a(s);
224
+ const f = t === void 0 ? 0 : t.of(s, c);
225
+ if (!(t !== void 0 && f > t.max)) {
226
+ r.set(s, { value: c, weight: f }), n += f;
209
227
  for (const y of r.keys()) {
210
228
  if (r.size <= e && (t === void 0 || n <= t.max)) break;
211
229
  a(y);
@@ -216,693 +234,712 @@ const Mr = (e) => e instanceof Error && Object.hasOwn(e, wt) && ut(e.reason), vr
216
234
  size: () => r.size,
217
235
  weight: () => n
218
236
  };
219
- }, gt = (e) => Math.max(1, e - 1), jr = 2147483647, Je = Object.freeze({ status: "aborted" }), oe = (e, t, r) => {
237
+ }, St = (e) => Math.max(1, e - 1), Jr = 2147483647, Ke = Object.freeze({ status: "aborted" }), ae = (e, t, r) => {
220
238
  const n = (e.get(t) ?? 0) + r;
221
239
  n === 0 ? e.delete(t) : e.set(t, n);
222
- }, ie = (e, t, r) => {
240
+ }, ce = (e, t, r) => {
223
241
  if (!Number.isSafeInteger(t) || t <= 0 || t > r) throw new RangeError(`[markdown-explorer] a worker pool's ${e} must be an integer in 1..${String(r)}; got ${String(t)}`);
224
- }, Lr = (e) => e !== null && typeof e == "object" && e.ready === !0 && !("id" in e), zr = (e, t) => e !== null && typeof e == "object" && e.id === t && "output" in e, Dr = ({ url: e, size: t, deadlineMs: r, jobsPerScope: n, maxQueuedJobs: a, heapLimits: o }) => {
225
- ie("size", t, Number.MAX_SAFE_INTEGER), ie("deadline", r, jr), ie("jobsPerScope", n, Number.MAX_SAFE_INTEGER), ie("maxQueuedJobs", a, Number.MAX_SAFE_INTEGER), ie("maxOldGenerationSizeMb", o.maxOldGenerationSizeMb, Number.MAX_SAFE_INTEGER), ie("maxYoungGenerationSizeMb", o.maxYoungGenerationSizeMb, Number.MAX_SAFE_INTEGER);
226
- const i = Object.freeze({ maxOldGenerationSizeMb: o.maxOldGenerationSizeMb, maxYoungGenerationSizeMb: o.maxYoungGenerationSizeMb }), l = /* @__PURE__ */ new Set(), y = [], x = /* @__PURE__ */ new Map(), f = /* @__PURE__ */ new Map(), w = gt(t);
227
- let O = 0;
228
- const _ = (u, h) => {
229
- const { job: g } = u;
230
- u.timer !== null && clearTimeout(u.timer), u.timer = null, u.job = null, u.sent = !1, g !== null && (oe(x, g.scope, -1), oe(f, g.scope, -1), g.settle(h));
231
- }, v = (u) => {
232
- const [h] = y.splice(u, 1);
233
- h?.detach();
234
- }, R = () => {
235
- let u = -1, h = w, g = Number.POSITIVE_INFINITY;
242
+ }, Yr = (e) => e !== null && typeof e == "object" && e.ready === !0 && !("id" in e), Wr = (e, t) => e !== null && typeof e == "object" && e.id === t && "output" in e, Kr = ({ url: e, size: t, deadlineMs: r, jobsPerScope: n, maxQueuedJobs: a, heapLimits: s }) => {
243
+ ce("size", t, Number.MAX_SAFE_INTEGER), ce("deadline", r, Jr), ce("jobsPerScope", n, Number.MAX_SAFE_INTEGER), ce("maxQueuedJobs", a, Number.MAX_SAFE_INTEGER), ce("maxOldGenerationSizeMb", s.maxOldGenerationSizeMb, Number.MAX_SAFE_INTEGER), ce("maxYoungGenerationSizeMb", s.maxYoungGenerationSizeMb, Number.MAX_SAFE_INTEGER);
244
+ const c = Object.freeze({ maxOldGenerationSizeMb: s.maxOldGenerationSizeMb, maxYoungGenerationSizeMb: s.maxYoungGenerationSizeMb }), f = /* @__PURE__ */ new Set(), y = [], k = /* @__PURE__ */ new Map(), p = /* @__PURE__ */ new Map(), h = St(t);
245
+ let x = 0;
246
+ const R = (d, E) => {
247
+ const { job: w } = d;
248
+ d.timer !== null && clearTimeout(d.timer), d.timer = null, d.job = null, d.sent = !1, w !== null && (ae(k, w.scope, -1), ae(p, w.scope, -1), w.settle(E));
249
+ }, v = (d) => {
250
+ const [E] = y.splice(d, 1);
251
+ E?.detach();
252
+ }, _ = () => {
253
+ let d = -1, E = h, w = Number.POSITIVE_INFINITY;
236
254
  for (const [T, b] of y.entries()) {
237
- const N = x.get(b.scope) ?? 0, P = f.get(b.scope) ?? 0;
238
- (N < h || N === h && u >= 0 && P < g) && (u = T, h = N, g = P);
255
+ const A = k.get(b.scope) ?? 0, P = p.get(b.scope) ?? 0;
256
+ (A < E || A === E && d >= 0 && P < w) && (d = T, E = A, w = P);
239
257
  }
240
- return u;
241
- }, k = (u, h) => {
242
- l.has(u) && (l.delete(u), _(u, h), u.worker.terminate().catch(() => {
243
- }), C());
244
- }, j = (u) => {
245
- u.timer = setTimeout(() => {
246
- k(u, { status: "timeout" });
258
+ return d;
259
+ }, O = (d, E) => {
260
+ f.has(d) && (f.delete(d), R(d, E), d.worker.terminate().catch(() => {
261
+ }), j());
262
+ }, L = (d) => {
263
+ d.timer = setTimeout(() => {
264
+ O(d, { status: "timeout" });
247
265
  }, r);
248
- }, S = (u, h) => u.sent ? { status: "crashed", error: h } : { status: "unavailable", error: h }, A = (u, h) => {
249
- u.sent = !0, j(u);
266
+ }, S = (d, E) => d.sent ? { status: "crashed", error: E } : { status: "unavailable", error: E }, N = (d, E) => {
267
+ d.sent = !0, L(d);
250
268
  try {
251
- u.worker.postMessage({ id: h.id, input: h.input });
252
- } catch (g) {
253
- _(u, { status: "crashed", error: g }), u.worker.unref();
269
+ d.worker.postMessage({ id: E.id, input: E.input });
270
+ } catch (w) {
271
+ R(d, { status: "crashed", error: w }), d.worker.unref();
254
272
  }
255
- }, D = () => {
256
- const u = { worker: new ar(e, { resourceLimits: i }), job: null, sent: !1, timer: null, ready: !1 };
257
- return u.worker.unref(), u.timer = setTimeout(() => {
258
- k(u, { status: "unavailable", error: new Error(`[markdown-explorer] a worker did not start within ${String(r)} ms`) });
259
- }, r), u.worker.on("message", (h) => {
260
- if (!u.ready && Lr(h)) {
261
- u.ready = !0, u.timer !== null && clearTimeout(u.timer), u.timer = null, u.job === null ? u.worker.unref() : A(u, u.job), u.job === null && C();
273
+ }, H = () => {
274
+ const d = { worker: new pr(e, { resourceLimits: c }), job: null, sent: !1, timer: null, ready: !1 };
275
+ return d.worker.unref(), d.timer = setTimeout(() => {
276
+ O(d, { status: "unavailable", error: new Error(`[markdown-explorer] a worker did not start within ${String(r)} ms`) });
277
+ }, r), d.worker.on("message", (E) => {
278
+ if (!d.ready && Yr(E)) {
279
+ d.ready = !0, d.timer !== null && clearTimeout(d.timer), d.timer = null, d.job === null ? d.worker.unref() : N(d, d.job), d.job === null && j();
262
280
  return;
263
281
  }
264
- const { job: g } = u;
265
- if (g === null || !zr(h, g.id)) {
266
- k(u, S(u, new Error("[markdown-explorer] a worker sent a message that answers no job")));
282
+ const { job: w } = d;
283
+ if (w === null || !Wr(E, w.id)) {
284
+ O(d, S(d, new Error("[markdown-explorer] a worker sent a message that answers no job")));
267
285
  return;
268
286
  }
269
- _(u, { status: "done", output: h.output }), u.worker.unref(), C();
270
- }), u.worker.on("error", (h) => {
271
- k(u, S(u, h));
272
- }), u.worker.on("messageerror", (h) => {
273
- k(u, S(u, h));
274
- }), u.worker.on("exit", (h) => {
275
- k(u, S(u, new Error(`[markdown-explorer] a worker exited with code ${String(h)}`)));
276
- }), l.add(u), u;
277
- }, C = () => {
287
+ R(d, { status: "done", output: E.output }), d.worker.unref(), j();
288
+ }), d.worker.on("error", (E) => {
289
+ O(d, S(d, E));
290
+ }), d.worker.on("messageerror", (E) => {
291
+ O(d, S(d, E));
292
+ }), d.worker.on("exit", (E) => {
293
+ O(d, S(d, new Error(`[markdown-explorer] a worker exited with code ${String(E)}`)));
294
+ }), f.add(d), d;
295
+ }, j = () => {
278
296
  for (; ; ) {
279
- const u = R(), h = y[u];
280
- if (h === void 0) return;
281
- let g;
282
- for (const b of l)
297
+ const d = _(), E = y[d];
298
+ if (E === void 0) return;
299
+ let w;
300
+ for (const b of f)
283
301
  if (b.job === null) {
284
- g = b;
302
+ w = b;
285
303
  break;
286
304
  }
287
- if (g === void 0 && l.size < t)
305
+ if (w === void 0 && f.size < t)
288
306
  try {
289
- g = D();
307
+ w = H();
290
308
  } catch (b) {
291
- v(u), oe(f, h.scope, -1), h.settle({ status: "unavailable", error: b });
309
+ v(d), ae(p, E.scope, -1), E.settle({ status: "unavailable", error: b });
292
310
  continue;
293
311
  }
294
- if (g === void 0) return;
295
- v(u), oe(x, h.scope, 1);
296
- const T = g;
297
- T.job = h, T.worker.ref(), T.ready && A(T, h);
312
+ if (w === void 0) return;
313
+ v(d), ae(k, E.scope, 1);
314
+ const T = w;
315
+ T.job = E, T.worker.ref(), T.ready && N(T, E);
298
316
  }
299
317
  };
300
318
  return {
301
- run: (u, { scope: h, signal: g }) => new Promise((T) => {
302
- if (g.aborted) {
303
- T(Je);
319
+ run: (d, { scope: E, signal: w }) => new Promise((T) => {
320
+ if (w.aborted) {
321
+ T(Ke);
304
322
  return;
305
323
  }
306
- if ((f.get(h) ?? 0) >= n) {
324
+ if ((p.get(E) ?? 0) >= n) {
307
325
  T({ status: "refused", limit: "scope" });
308
326
  return;
309
327
  }
310
- O += 1;
311
- const b = { id: O, input: u, scope: h, settle: T, detach: () => {
328
+ x += 1;
329
+ const b = { id: x, input: d, scope: E, settle: T, detach: () => {
312
330
  } };
313
- y.push(b), oe(f, h, 1), C();
314
- const N = y.indexOf(b);
315
- if (N < 0) return;
331
+ y.push(b), ae(p, E, 1), j();
332
+ const A = y.indexOf(b);
333
+ if (A < 0) return;
316
334
  if (y.length > a) {
317
- v(N), oe(f, h, -1), T({ status: "refused", limit: "queue" });
335
+ v(A), ae(p, E, -1), T({ status: "refused", limit: "queue" });
318
336
  return;
319
337
  }
320
338
  const P = () => {
321
339
  const B = y.indexOf(b);
322
- B < 0 || (v(B), oe(f, h, -1), T(Je));
340
+ B < 0 || (v(B), ae(p, E, -1), T(Ke));
323
341
  };
324
- g.addEventListener("abort", P, { once: !0 }), b.detach = () => {
325
- g.removeEventListener("abort", P);
342
+ w.addEventListener("abort", P, { once: !0 }), b.detach = () => {
343
+ w.removeEventListener("abort", P);
326
344
  };
327
345
  }),
328
- workers: () => l.size
346
+ workers: () => f.size
329
347
  };
330
- }, Me = 1024 * 1024, Cr = 3e4, Hr = 4 * Me, Br = 64 * Me, Fr = 3, Ur = 2, Xr = (e, t) => e + gt(t) + Fr, Gr = 4, Jr = 32, Wr = 512, Yr = 64, Kr = 4096, Vr = 32, We = 4096, Zr = 4, yt = ({ workerHeapMb: e, maxHtmlBytes: t }) => Math.floor(((e - Yr) * Me - t * Vr) / Kr), Qr = ({ maxHtmlBytes: e }) => e, qr = ({ maxHtmlBytes: e }) => Zr * e, en = 1024, tn = 2147483647, rn = 64, nn = 2 ** 29, on = 1024 * 1024, sn = 64, Ye = Object.freeze({ status: "rejected", reason: "too-large", cause: null }), ke = Object.freeze({ status: "rejected", reason: "failed", cause: null }), se = (e, t, r, n) => {
348
+ }, Me = 1024 * 1024, Vr = 3e4, Zr = 4 * Me, Qr = 64 * Me, qr = 3, en = 2, tn = (e, t) => e + St(t) + qr, rn = 4, nn = 32, on = 512, sn = 64, an = 4096, cn = 32, Ve = 4096, un = 4, Tt = ({ workerHeapMb: e, maxHtmlBytes: t }) => Math.floor(((e - sn) * Me - t * cn) / an), ln = ({ maxHtmlBytes: e }) => e, dn = ({ maxHtmlBytes: e }) => un * e, fn = 1024, mn = 2147483647, pn = 64, wn = 2 ** 29, hn = 1024 * 1024, gn = 64, Ze = Object.freeze({ status: "rejected", reason: "too-large", cause: null }), ke = Object.freeze({ status: "rejected", reason: "failed", cause: null }), ie = (e, t, r, n) => {
331
349
  if (t === void 0) return r;
332
350
  if (typeof t != "number") throw new TypeError(`[markdown-explorer] sanitizer.${e} must be a number; got ${typeof t}`);
333
351
  if (!Number.isSafeInteger(t) || t <= 0 || t > n) throw new RangeError(`[markdown-explorer] sanitizer.${e} must be an integer in 1..${String(n)}; got ${String(t)}`);
334
352
  return t;
335
- }, an = (e, t) => {
353
+ }, yn = (e, t) => {
336
354
  if (e !== void 0 && (e === null || typeof e != "object")) throw new TypeError("[markdown-explorer] sanitizer must be an object of { workers, deadlineMs, maxHtmlBytes, cacheBytes, workerHeapMb, jobsPerScope, maxQueuedJobs }");
337
- const { workers: r, deadlineMs: n, maxHtmlBytes: a, cacheBytes: o, workerHeapMb: i, jobsPerScope: l, maxQueuedJobs: y } = e ?? {}, x = se("workers", r, Ur, rn), f = se("jobsPerScope", l, Xr(t, x), Number.MAX_SAFE_INTEGER), w = Object.freeze({
338
- workers: x,
339
- deadlineMs: se("deadlineMs", n, Cr, tn),
340
- maxHtmlBytes: se("maxHtmlBytes", a, Hr, nn),
341
- cacheBytes: se("cacheBytes", o, Br, Number.MAX_SAFE_INTEGER),
342
- workerHeapMb: se("workerHeapMb", i, Wr, on),
343
- jobsPerScope: f,
344
- maxQueuedJobs: se("maxQueuedJobs", y, Gr * f, Number.MAX_SAFE_INTEGER)
355
+ const { workers: r, deadlineMs: n, maxHtmlBytes: a, cacheBytes: s, workerHeapMb: c, jobsPerScope: f, maxQueuedJobs: y } = e ?? {}, k = ie("workers", r, en, pn), p = ie("jobsPerScope", f, tn(t, k), Number.MAX_SAFE_INTEGER), h = Object.freeze({
356
+ workers: k,
357
+ deadlineMs: ie("deadlineMs", n, Vr, mn),
358
+ maxHtmlBytes: ie("maxHtmlBytes", a, Zr, wn),
359
+ cacheBytes: ie("cacheBytes", s, Qr, Number.MAX_SAFE_INTEGER),
360
+ workerHeapMb: ie("workerHeapMb", c, on, hn),
361
+ jobsPerScope: p,
362
+ maxQueuedJobs: ie("maxQueuedJobs", y, rn * p, Number.MAX_SAFE_INTEGER)
345
363
  });
346
- if (w.jobsPerScope < t)
347
- throw new RangeError(`[markdown-explorer] sanitizer.jobsPerScope must be at least multiView.maxPanels (${String(t)}), because a page sends the document of every panel to the sanitizer at once for one reader; got ${String(w.jobsPerScope)}`);
348
- if (w.maxQueuedJobs < t)
349
- throw new RangeError(`[markdown-explorer] sanitizer.maxQueuedJobs must be at least multiView.maxPanels (${String(t)}), because a reader whose page finds every worker busy waits with the document of every panel; got ${String(w.maxQueuedJobs)}`);
350
- if (yt(w) < We)
364
+ if (h.jobsPerScope < t)
365
+ throw new RangeError(`[markdown-explorer] sanitizer.jobsPerScope must be at least multiView.maxPanels (${String(t)}), because a page sends the document of every panel to the sanitizer at once for one reader; got ${String(h.jobsPerScope)}`);
366
+ if (h.maxQueuedJobs < t)
367
+ throw new RangeError(`[markdown-explorer] sanitizer.maxQueuedJobs must be at least multiView.maxPanels (${String(t)}), because a reader whose page finds every worker busy waits with the document of every panel; got ${String(h.maxQueuedJobs)}`);
368
+ if (Tt(h) < Ve)
351
369
  throw new RangeError(
352
- `[markdown-explorer] sanitizer.workerHeapMb (${String(w.workerHeapMb)} MiB) must leave room for ${String(We)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(w.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`
370
+ `[markdown-explorer] sanitizer.workerHeapMb (${String(h.workerHeapMb)} MiB) must leave room for ${String(Ve)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(h.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`
353
371
  );
354
- return w;
355
- }, cn = () => {
356
- const e = import.meta.url, t = new URL(`./sanitizeWorker${nr(Se(e))}`, e);
357
- if (!er(Se(t))) throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${Se(t)}`);
372
+ return h;
373
+ }, En = () => {
374
+ const e = import.meta.url, t = new URL(`./sanitizeWorker${dr(Se(e))}`, e);
375
+ if (!cr(Se(t))) throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${Se(t)}`);
358
376
  return t;
359
- }, Ke = /* @__PURE__ */ new Map(), un = (e, t) => {
377
+ }, Qe = /* @__PURE__ */ new Map(), bn = (e, t) => {
360
378
  const r = [e.href, t.workers, t.deadlineMs, t.workerHeapMb, t.jobsPerScope, t.maxQueuedJobs].map(String).join("\0");
361
- let n = Ke.get(r);
362
- return n === void 0 && (n = Dr({
379
+ let n = Qe.get(r);
380
+ return n === void 0 && (n = Kr({
363
381
  url: e,
364
382
  size: t.workers,
365
383
  deadlineMs: t.deadlineMs,
366
384
  jobsPerScope: t.jobsPerScope,
367
385
  maxQueuedJobs: t.maxQueuedJobs,
368
- heapLimits: { maxOldGenerationSizeMb: t.workerHeapMb, maxYoungGenerationSizeMb: Jr }
369
- }), Ke.set(r, n)), n;
370
- }, ln = (e) => {
386
+ heapLimits: { maxOldGenerationSizeMb: t.workerHeapMb, maxYoungGenerationSizeMb: nn }
387
+ }), Qe.set(r, n)), n;
388
+ }, Sn = (e) => {
371
389
  if (e === null || typeof e != "object") return !1;
372
390
  const { status: t, html: r, message: n } = e;
373
391
  return t === "sanitized" && typeof r == "string" || t === "too-large" || t === "error" && typeof n == "string";
374
- }, dn = (e) => e instanceof Error && e.code === "ERR_WORKER_OUT_OF_MEMORY", fn = ({ iframeHosts: e, dataPath: t, options: r, pool: n }) => {
375
- const a = Object.freeze([...e]), o = yt(r), i = Qr(r), l = qr(r), y = ht(en, {
392
+ }, Tn = (e) => e instanceof Error && e.code === "ERR_WORKER_OUT_OF_MEMORY", xn = ({ iframeHosts: e, dataPath: t, options: r, pool: n }) => {
393
+ const a = Object.freeze([...e]), s = Tt(r), c = ln(r), f = dn(r), y = bt(fn, {
376
394
  max: r.cacheBytes,
377
- of: (R, k) => 2 * R.length + (k.status === "sanitized" ? 2 * k.html.length : sn)
378
- }), x = /* @__PURE__ */ new Map(), f = /* @__PURE__ */ new Map(), w = (R) => {
379
- x.get(R.key) === R && x.delete(R.key);
380
- const k = f.get(R.hash);
381
- k?.delete(R), k?.size === 0 && f.delete(R.hash);
382
- }, O = async (R, k, j) => {
383
- const S = await n.run({ html: R, iframeHosts: a, dataPath: t, maxNodes: o, maxAttributeChars: i, maxSanitizedChars: l }, { scope: k, signal: j });
395
+ of: (_, O) => 2 * _.length + (O.status === "sanitized" ? 2 * O.html.length : gn)
396
+ }), k = /* @__PURE__ */ new Map(), p = /* @__PURE__ */ new Map(), h = (_) => {
397
+ k.get(_.key) === _ && k.delete(_.key);
398
+ const O = p.get(_.hash);
399
+ O?.delete(_), O?.size === 0 && p.delete(_.hash);
400
+ }, x = async (_, O, L) => {
401
+ const S = await n.run({ html: _, iframeHosts: a, dataPath: t, maxNodes: s, maxAttributeChars: c, maxSanitizedChars: f }, { scope: O, signal: L });
384
402
  if (S.status === "refused") {
385
- const D = S.limit === "scope" ? `its reader already has ${String(r.jobsPerScope)} documents being sanitized or waiting` : `${String(r.maxQueuedJobs)} documents are already waiting`;
386
- return { outcome: { status: "rejected", reason: "failed", cause: new Error(`[markdown-explorer] the HTML sanitizer refused a document: ${D}`) }, lasting: !1 };
403
+ const H = S.limit === "scope" ? `its reader already has ${String(r.jobsPerScope)} documents being sanitized or waiting` : `${String(r.maxQueuedJobs)} documents are already waiting`;
404
+ return { outcome: { status: "rejected", reason: "failed", cause: new Error(`[markdown-explorer] the HTML sanitizer refused a document: ${H}`) }, lasting: !1 };
387
405
  }
388
406
  if (S.status === "aborted") return { outcome: ke, lasting: !1 };
389
407
  if (S.status === "timeout") return { outcome: { status: "rejected", reason: "too-large", cause: new Error(`[markdown-explorer] the HTML sanitizer did not finish within ${String(r.deadlineMs)} ms`) }, lasting: !0 };
390
408
  if (S.status === "unavailable") return { outcome: { status: "rejected", reason: "failed", cause: new Error("[markdown-explorer] the HTML sanitizer worker could not start", { cause: S.error }) }, lasting: !1 };
391
- if (S.status === "crashed" && dn(S.error))
409
+ if (S.status === "crashed" && Tn(S.error))
392
410
  return { outcome: { status: "rejected", reason: "too-large", cause: new Error(`[markdown-explorer] the HTML sanitizer ran out of its ${String(r.workerHeapMb)} MiB worker heap`, { cause: S.error }) }, lasting: !0 };
393
411
  if (S.status === "crashed") return { outcome: { status: "rejected", reason: "failed", cause: new Error("[markdown-explorer] the HTML sanitizer worker failed", { cause: S.error }) }, lasting: !0 };
394
- const { output: A } = S;
395
- return ln(A) ? A.status === "too-large" ? { outcome: Ye, lasting: !0 } : A.status === "error" ? { outcome: { status: "rejected", reason: "failed", cause: new Error(`[markdown-explorer] the HTML sanitizer failed: ${A.message}`) }, lasting: !0 } : A.html.length > l ? { outcome: { status: "rejected", reason: "too-large", cause: new Error(`[markdown-explorer] the HTML sanitizer's output of ${String(A.html.length)} characters exceeds its limit of ${String(l)}`) }, lasting: !0 } : { outcome: { status: "sanitized", html: A.html }, lasting: !0 } : { outcome: { status: "rejected", reason: "failed", cause: new Error("[markdown-explorer] the HTML sanitizer worker answered something that is not an outcome") }, lasting: !0 };
396
- }, _ = (R, k, j, S) => {
397
- let A = () => {
412
+ const { output: N } = S;
413
+ return Sn(N) ? N.status === "too-large" ? { outcome: Ze, lasting: !0 } : N.status === "error" ? { outcome: { status: "rejected", reason: "failed", cause: new Error(`[markdown-explorer] the HTML sanitizer failed: ${N.message}`) }, lasting: !0 } : N.html.length > f ? { outcome: { status: "rejected", reason: "too-large", cause: new Error(`[markdown-explorer] the HTML sanitizer's output of ${String(N.html.length)} characters exceeds its limit of ${String(f)}`) }, lasting: !0 } : { outcome: { status: "sanitized", html: N.html }, lasting: !0 } : { outcome: { status: "rejected", reason: "failed", cause: new Error("[markdown-explorer] the HTML sanitizer worker answered something that is not an outcome") }, lasting: !0 };
414
+ }, R = (_, O, L, S) => {
415
+ let N = () => {
398
416
  };
399
- const D = new Promise((h) => {
400
- A = h;
401
- }), C = { hash: k, key: j, outcome: D, answer: A, controller: new AbortController(), waiters: 0 };
402
- x.set(j, C);
403
- const u = f.get(k);
404
- return u === void 0 ? f.set(k, /* @__PURE__ */ new Set([C])) : u.add(C), O(R, S, C.controller.signal).catch((h) => ({ outcome: { status: "rejected", reason: "failed", cause: h instanceof Error ? h : new Error(String(h)) }, lasting: !0 })).then(({ outcome: h, lasting: g }) => {
405
- if (w(C), C.answer(h), !g) return;
406
- const T = y.get(k), b = T ?? (h.status === "rejected" ? { ...h, cause: null } : h);
407
- T === void 0 && y.set(k, b);
408
- for (const N of f.get(k) ?? [])
409
- w(N), N.answer(b), N.controller.abort();
410
- }), C;
411
- }, v = (R, k) => new Promise((j) => {
412
- R.waiters += 1;
417
+ const H = new Promise((E) => {
418
+ N = E;
419
+ }), j = { hash: O, key: L, outcome: H, answer: N, controller: new AbortController(), waiters: 0 };
420
+ k.set(L, j);
421
+ const d = p.get(O);
422
+ return d === void 0 ? p.set(O, /* @__PURE__ */ new Set([j])) : d.add(j), x(_, S, j.controller.signal).catch((E) => ({ outcome: { status: "rejected", reason: "failed", cause: E instanceof Error ? E : new Error(String(E)) }, lasting: !0 })).then(({ outcome: E, lasting: w }) => {
423
+ if (h(j), j.answer(E), !w) return;
424
+ const T = y.get(O), b = T ?? (E.status === "rejected" ? { ...E, cause: null } : E);
425
+ T === void 0 && y.set(O, b);
426
+ for (const A of p.get(O) ?? [])
427
+ h(A), A.answer(b), A.controller.abort();
428
+ }), j;
429
+ }, v = (_, O) => new Promise((L) => {
430
+ _.waiters += 1;
413
431
  const S = () => {
414
- R.waiters -= 1, j(ke), !(R.waiters > 0) && (w(R), R.controller.abort());
432
+ _.waiters -= 1, L(ke), !(_.waiters > 0) && (h(_), _.controller.abort());
415
433
  };
416
- k.addEventListener("abort", S, { once: !0 }), R.outcome.then((A) => {
417
- k.removeEventListener("abort", S), j(A);
434
+ O.addEventListener("abort", S, { once: !0 }), _.outcome.then((N) => {
435
+ O.removeEventListener("abort", S), L(N);
418
436
  });
419
437
  });
420
- return (R, { scope: k, signal: j }) => {
421
- if (R.length > r.maxHtmlBytes || Buffer.byteLength(R, "utf8") > r.maxHtmlBytes) return Promise.resolve(Ye);
422
- const S = Bt("sha256").update(R, "utf8").digest("base64"), A = y.get(S);
423
- if (A !== void 0) return Promise.resolve(A);
424
- if (j.aborted) return Promise.resolve(ke);
425
- const D = `${S}\0${k}`, C = x.get(D);
426
- return v(C === void 0 ? _(R, S, D, k) : C, j);
438
+ return (_, { scope: O, signal: L }) => {
439
+ if (_.length > r.maxHtmlBytes || Buffer.byteLength(_, "utf8") > r.maxHtmlBytes) return Promise.resolve(Ze);
440
+ const S = Yt("sha256").update(_, "utf8").digest("base64"), N = y.get(S);
441
+ if (N !== void 0) return Promise.resolve(N);
442
+ if (L.aborted) return Promise.resolve(ke);
443
+ const H = `${S}\0${O}`, j = k.get(H);
444
+ return v(j === void 0 ? R(_, S, H, O) : j, L);
427
445
  };
428
- }, be = (e) => ({ result: e, json: JSON.stringify(e) }), Oe = Object.freeze(be(Object.freeze({ status: "error", failure: Object.freeze({ reason: "failed" }) }))), mn = (e) => e.status === "ok" && e.entries.length > 0, pn = ({ ttlMs: e, maxEntries: t, maxBytes: r, now: n }) => {
429
- const a = ht(t, { max: r, of: (f, w) => 2 * w.tree.json.length }), o = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map(), l = (f, w) => {
430
- const O = new AbortController(), _ = { waiters: 0, superseded: !1, started: !1, loadTree: w }, v = i.get(f), R = (D, C) => {
431
- const u = be(D);
432
- return !(_.superseded || O.signal.aborted) && mn(D) && a.set(f, { tree: u, loadedAt: C }), u;
433
- }, j = (async () => {
434
- if (v !== void 0 && await v, O.signal.aborted) return Oe;
435
- const D = n();
436
- return _.started = !0, R(await _.loadTree(O.signal, D), D);
446
+ }, be = (e) => ({ result: e, json: JSON.stringify(e) }), Oe = Object.freeze(be(Object.freeze({ status: "error", failure: Object.freeze({ reason: "failed" }) }))), kn = (e) => e.status === "ok" && e.entries.length > 0, On = ({ ttlMs: e, maxEntries: t, maxBytes: r, now: n }) => {
447
+ const a = bt(t, { max: r, of: (p, h) => 2 * h.tree.json.length }), s = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map(), f = (p, h) => {
448
+ const x = new AbortController(), R = { waiters: 0, superseded: !1, started: !1, loadTree: h }, v = c.get(p), _ = (H, j) => {
449
+ const d = be(H);
450
+ return !(R.superseded || x.signal.aborted) && kn(H) && a.set(p, { tree: d, loadedAt: j }), d;
451
+ }, L = (async () => {
452
+ if (v !== void 0 && await v, x.signal.aborted) return Oe;
453
+ const H = n();
454
+ return R.started = !0, _(await R.loadTree(x.signal, H), H);
437
455
  })().finally(() => {
438
- o.get(f) === S && o.delete(f);
439
- }), S = { promise: j, controller: O, state: _ };
440
- o.set(f, S);
441
- const A = j.then(
456
+ s.get(p) === S && s.delete(p);
457
+ }), S = { promise: L, controller: x, state: R };
458
+ s.set(p, S);
459
+ const N = L.then(
442
460
  () => {
443
461
  },
444
462
  () => {
445
463
  }
446
464
  );
447
- return i.set(f, A), A.then(() => {
448
- i.get(f) === A && i.delete(f);
465
+ return c.set(p, N), N.then(() => {
466
+ c.get(p) === N && c.delete(p);
449
467
  }), S;
450
- }, y = (f, w, O) => {
451
- w.state.waiters += 1;
452
- const _ = () => {
453
- w.state.waiters -= 1, !(w.state.waiters > 0) && (o.get(f) === w && o.delete(f), w.controller.abort());
468
+ }, y = (p, h, x) => {
469
+ h.state.waiters += 1;
470
+ const R = () => {
471
+ h.state.waiters -= 1, !(h.state.waiters > 0) && (s.get(p) === h && s.delete(p), h.controller.abort());
454
472
  };
455
- return O.addEventListener("abort", _, { once: !0 }), w.promise.finally(() => {
456
- O.removeEventListener("abort", _);
473
+ return x.addEventListener("abort", R, { once: !0 }), h.promise.finally(() => {
474
+ x.removeEventListener("abort", R);
457
475
  });
458
- }, x = (f) => {
459
- a.delete(f);
460
- const w = o.get(f);
461
- w?.state.started && (w.state.superseded = !0, o.delete(f));
476
+ }, k = (p) => {
477
+ a.delete(p);
478
+ const h = s.get(p);
479
+ h?.state.started && (h.state.superseded = !0, s.delete(p));
462
480
  };
463
481
  return {
464
- load: (f, w, O) => {
465
- if (w.aborted) return Promise.resolve(Oe);
466
- const _ = a.get(f);
467
- if (_ !== void 0) {
468
- if (n() - _.loadedAt < e) return Promise.resolve(_.tree);
469
- a.delete(f);
482
+ load: (p, h, x) => {
483
+ if (h.aborted) return Promise.resolve(Oe);
484
+ const R = a.get(p);
485
+ if (R !== void 0) {
486
+ if (n() - R.loadedAt < e) return Promise.resolve(R.tree);
487
+ a.delete(p);
470
488
  }
471
- const v = o.get(f);
472
- return y(f, v === void 0 ? l(f, O) : v, w);
489
+ const v = s.get(p);
490
+ return y(p, v === void 0 ? f(p, x) : v, h);
473
491
  },
474
- refresh: (f, w, O) => {
475
- if (w.aborted) return Promise.resolve(Oe);
476
- x(f);
477
- const _ = o.get(f);
478
- return _ === void 0 ? y(f, l(f, O), w) : (_.state.loadTree = O, y(f, _, w));
492
+ refresh: (p, h, x) => {
493
+ if (h.aborted) return Promise.resolve(Oe);
494
+ k(p);
495
+ const R = s.get(p);
496
+ return R === void 0 ? y(p, f(p, x), h) : (R.state.loadTree = x, y(p, R, h));
479
497
  },
480
- forget: x
498
+ forget: k
481
499
  };
482
- }, wn = (e) => ({
500
+ }, _n = (e) => ({
483
501
  load: (t, r, n) => n(r, e()).then(be),
484
502
  refresh: (t, r, n) => n(r, e()).then(be),
485
503
  forget: () => {
486
504
  }
487
505
  }), $ = (e) => {
488
506
  throw new TypeError(`[markdown-explorer] ${e}`);
489
- }, hn = (e) => {
507
+ }, Rn = (e) => {
490
508
  if (e === null || typeof e != "object") return null;
491
509
  const { name: t, path: r } = e;
492
- return typeof t != "string" || typeof r != "string" ? null : t === "" ? { path: r, reason: "an empty name" } : te(r) ? null : { path: r, reason: "a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)" };
493
- }, gn = (e, t, r, n) => {
510
+ return typeof t != "string" || typeof r != "string" ? null : t === "" ? { path: r, reason: "an empty name" } : ee(r) ? null : { path: r, reason: "a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)" };
511
+ }, An = (e, t, r, n) => {
494
512
  if (e === null) return null;
495
513
  if (!Array.isArray(e)) throw new TypeError(`[markdown-explorer] a source's ancestors must be null or an array of folder paths; got ${typeof e}`);
496
514
  const a = /* @__PURE__ */ new Set();
497
- for (const o of e) {
498
- if (typeof o != "string" || !te(o)) throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");
499
- if (r.deniesPath(o)) throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");
500
- if (!n(o)) throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");
501
- if (o === t) throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");
502
- if (a.has(o)) throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");
503
- a.add(o);
515
+ for (const s of e) {
516
+ if (typeof s != "string" || !ee(s)) throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");
517
+ if (r.deniesPath(s)) throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");
518
+ if (!n(s)) throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");
519
+ if (s === t) throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");
520
+ if (a.has(s)) throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");
521
+ a.add(s);
504
522
  }
505
523
  return Object.freeze([...a]);
506
- }, yn = (e, t, r, n, a) => {
507
- const o = /* @__PURE__ */ new Set(), i = (y) => {
524
+ }, Nn = (e, t, r, n, a) => {
525
+ const s = /* @__PURE__ */ new Set(), c = (y) => {
508
526
  if (!Array.isArray(y)) return $("a source returned entries that are not an array");
509
- const x = [];
510
- for (const f of y) {
511
- const w = l(f);
512
- w !== null && x.push(w);
527
+ const k = [];
528
+ for (const p of y) {
529
+ const h = f(p);
530
+ h !== null && k.push(h);
513
531
  }
514
- return x;
515
- }, l = (y) => {
516
- const x = hn(y);
517
- if (x !== null)
518
- return n(x), null;
519
- const f = $t(y);
520
- if (f !== null) return $(f);
521
- const w = y;
522
- if (o.has(w)) return $("a source returned entries that contain themselves");
523
- const { name: O, path: _, type: v, mimeType: R, children: k, lazy: j } = w;
524
- if (t.deniesName(O) || t.deniesPath(_)) return null;
525
- if (!a(_))
526
- return n({ path: _, reason: "a path outside the source's boundary" }), null;
527
- const S = R === void 0 ? { name: O, path: _ } : { name: O, path: _, mimeType: R };
532
+ return k;
533
+ }, f = (y) => {
534
+ const k = Rn(y);
535
+ if (k !== null)
536
+ return n(k), null;
537
+ const p = Bt(y);
538
+ if (p !== null) return $(p);
539
+ const h = y;
540
+ if (s.has(h)) return $("a source returned entries that contain themselves");
541
+ const { name: x, path: R, type: v, mimeType: _, children: O, lazy: L } = h;
542
+ if (t.deniesName(x) || t.deniesPath(R)) return null;
543
+ if (!a(R))
544
+ return n({ path: R, reason: "a path outside the source's boundary" }), null;
545
+ const S = _ === void 0 ? { name: x, path: R } : { name: x, path: R, mimeType: _ };
528
546
  if (v === "file") return { ...S, type: v };
529
- if (j === !0)
547
+ if (L === !0)
530
548
  return r ? { ...S, type: v, lazy: !0, children: [] } : $("a lazy directory came from a source without a children function");
531
- if (k === void 0) return { ...S, type: v };
532
- o.add(w);
533
- const A = i(k);
534
- return o.delete(w), { ...S, type: v, children: A };
549
+ if (O === void 0) return { ...S, type: v };
550
+ s.add(h);
551
+ const N = c(O);
552
+ return s.delete(h), { ...S, type: v, children: N };
535
553
  };
536
- return i(e);
537
- }, En = /^[\x21\x23-\x7E]{1,256}$/u, Et = (e) => typeof e == "string" && En.test(e), bn = /* @__PURE__ */ new Set(["text", "image", "media", "file"]), Sn = (e) => typeof e == "string" && bn.has(e), Tn = (e, t) => {
554
+ return c(e);
555
+ }, In = /^[\x21\x23-\x7E]{1,256}$/u, xt = (e) => typeof e == "string" && In.test(e), Mn = /* @__PURE__ */ new Set(["text", "image", "media", "file"]), vn = (e) => typeof e == "string" && Mn.has(e), Pn = (e, t) => {
538
556
  if (e !== null && typeof e == "object") {
539
- const a = e, { kind: o } = a;
540
- if (Sn(o)) {
541
- if (Object.hasOwn(a, "url")) return $(`a ${o} document carries its version, not a url`);
557
+ const a = e, { kind: s } = a;
558
+ if (vn(s)) {
559
+ if (Object.hasOwn(a, "url")) return $(`a ${s} document carries its version, not a url`);
542
560
  if (typeof a.name != "string") return $("a document needs a name string");
543
- if (!Et(a.version)) return $(`a ${o} document needs a version of 1 to 256 visible ASCII characters other than '"'`);
544
- const i = t(a.version);
545
- switch (o) {
561
+ if (!xt(a.version)) return $(`a ${s} document needs a version of 1 to 256 visible ASCII characters other than '"'`);
562
+ const c = t(a.version);
563
+ switch (s) {
546
564
  case "image":
547
565
  case "file":
548
- return { kind: o, name: a.name, url: i };
566
+ return { kind: s, name: a.name, url: c };
549
567
  case "media": {
550
- const { mediaType: l } = a;
551
- return Mt(l) ? { kind: o, name: a.name, url: i, mediaType: l } : $(`unknown media type ${typeof l == "string" ? JSON.stringify(l.slice(0, 64)) : typeof l}`);
568
+ const { mediaType: f } = a;
569
+ return Dt(f) ? { kind: s, name: a.name, url: c, mediaType: f } : $(`unknown media type ${typeof f == "string" ? JSON.stringify(f.slice(0, 64)) : typeof f}`);
552
570
  }
553
571
  case "text":
554
- return typeof a.text != "string" || typeof a.truncated != "boolean" ? $("a text document needs text and truncated") : { kind: o, name: a.name, text: a.text, truncated: a.truncated, url: i };
572
+ return typeof a.text != "string" || typeof a.truncated != "boolean" ? $("a text document needs text and truncated") : { kind: s, name: a.name, text: a.text, truncated: a.truncated, url: c };
555
573
  }
556
574
  }
557
575
  }
558
- const r = vt(e);
576
+ const r = Ct(e);
559
577
  if (r !== null) return $(r);
560
578
  const n = e;
561
579
  switch (n.kind) {
562
580
  case "failure": {
563
- const { reason: a, code: o } = n.failure;
564
- return { kind: "failure", failure: _e(a, o) };
581
+ const { reason: a, code: s } = n.failure;
582
+ return { kind: "failure", failure: Re(a, s) };
565
583
  }
566
584
  case "markdown":
567
- return n.headings.length > Pt ? { kind: "failure", failure: _e("too-large") } : { kind: "unsanitized-markdown", name: n.name, html: n.htmlContent, headings: n.headings.map(({ text: a, depth: o, id: i }) => ({ text: a, depth: o, id: i })) };
585
+ return n.headings.length > Ht ? { kind: "failure", failure: Re("too-large") } : { kind: "unsanitized-markdown", name: n.name, html: n.htmlContent, headings: n.headings.map(({ text: a, depth: s, id: c }) => ({ text: a, depth: s, id: c })) };
568
586
  }
569
- }, xn = (e) => {
587
+ }, qe = (e) => {
570
588
  if (e === null || typeof e != "object") return $("an asset file must be an object");
571
- const { name: t, contentType: r, size: n, version: a, open: o } = e;
572
- return typeof t != "string" || t === "" ? $("an asset file needs a non-empty name") : typeof r != "string" ? $("an asset file needs a contentType string ('' when unknown)") : n !== null && !(typeof n == "number" && Number.isSafeInteger(n) && n >= 0) ? $("an asset file's size must be null or a non-negative safe integer") : Et(a) ? typeof o != "function" ? $("an asset file needs an open function") : Object.freeze({ name: t, contentType: r, size: n, version: a, open: o }) : $(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`);
573
- }, kn = (e) => Array.isArray(e) ? e.map((t) => {
589
+ const { name: t, contentType: r, size: n, version: a, open: s } = e;
590
+ return typeof t != "string" || t === "" ? $("an asset file needs a non-empty name") : typeof r != "string" ? $("an asset file needs a contentType string ('' when unknown)") : n !== null && !(typeof n == "number" && Number.isSafeInteger(n) && n >= 0) ? $("an asset file's size must be null or a non-negative safe integer") : xt(a) ? typeof s != "function" ? $("an asset file needs an open function") : Object.freeze({ name: t, contentType: r, size: n, version: a, open: s }) : $(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`);
591
+ }, $n = (e) => Array.isArray(e) ? e.map((t) => {
574
592
  if (t === null || typeof t != "object") return $("a notice must be an object");
575
- const { id: r, tone: n, title: a, body: o, action: i } = t;
593
+ const { id: r, tone: n, title: a, body: s, action: c } = t;
576
594
  if (typeof r != "string" || r === "" || typeof a != "string") return $("a notice needs an id and a title");
577
- if (!At(n)) return $(`unknown notice tone ${typeof n == "string" ? JSON.stringify(n.slice(0, 64)) : typeof n}`);
578
- if (o !== void 0 && typeof o != "string") return $("a notice body must be a string");
579
- const y = { id: r, tone: n, title: a, ...o === void 0 ? {} : { body: o } };
580
- if (i === void 0) return y;
581
- if (i === null || typeof i != "object") return $("a notice action must be an object");
582
- const { label: x, href: f } = i;
583
- return typeof x != "string" || !It(f, jt) ? $("a notice action needs a label and an http(s), mailto or relative href") : { ...y, action: { label: x, href: f } };
584
- }) : $("notices must be an array"), On = 4e3, pe = Object.freeze({ ttlMs: 3e5, maxEntries: 64, maxBytes: 64 * 1024 * 1024 }), Ve = 32, bt = "private, no-store", Rn = Object.freeze({
595
+ if (!jt(n)) return $(`unknown notice tone ${typeof n == "string" ? JSON.stringify(n.slice(0, 64)) : typeof n}`);
596
+ if (s !== void 0 && typeof s != "string") return $("a notice body must be a string");
597
+ const y = { id: r, tone: n, title: a, ...s === void 0 ? {} : { body: s } };
598
+ if (c === void 0) return y;
599
+ if (c === null || typeof c != "object") return $("a notice action must be an object");
600
+ const { label: k, href: p } = c;
601
+ return typeof k != "string" || !zt(p, Ft) ? $("a notice action needs a label and an http(s), mailto or relative href") : { ...y, action: { label: k, href: p } };
602
+ }) : $("notices must be an array"), Ln = 4e3, he = Object.freeze({ ttlMs: 3e5, maxEntries: 64, maxBytes: 64 * 1024 * 1024 }), et = 32, kt = "private, no-store", jn = Object.freeze({
585
603
  "Content-Type": "application/json; charset=utf-8",
586
- "Cache-Control": bt,
604
+ "Cache-Control": kt,
587
605
  "X-Content-Type-Options": "nosniff",
588
606
  "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'; sandbox",
589
607
  "Cross-Origin-Resource-Policy": "same-origin"
590
- }), _n = 22, Nn = 2147483647, Re = Object.freeze([]), Ze = Object.freeze(["contains", "confirm"]), Qe = Object.freeze({ readOnly: !1 }), An = Object.freeze({ readOnly: !0 }), G = (e, t, r) => {
608
+ }), zn = 22, Dn = 2147483647, _e = Object.freeze([]), Cn = Object.freeze({ status: "ok", source: null, ancestors: null }), tt = Object.freeze(["contains", "confirm"]), rt = Object.freeze({ readOnly: !1 }), Hn = Object.freeze({ readOnly: !0 }), Y = (e, t, r) => {
591
609
  if (!(r && t === void 0) && typeof t != "function")
592
610
  throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${typeof t}`);
593
- }, ye = (e, t, r) => {
611
+ }, me = (e, t, r) => {
594
612
  if (typeof t != "number") throw new TypeError(`[markdown-explorer] ${e} must be a number; got ${typeof t}`);
595
613
  if (!Number.isSafeInteger(t) || t <= 0 || t > r) throw new RangeError(`[markdown-explorer] ${e} must be an integer in 1..${String(r)}; got ${String(t)}`);
596
614
  return t;
597
- }, In = (e) => {
615
+ }, Bn = (e) => {
598
616
  if (e === null || typeof e != "object" || !Object.isFrozen(e)) throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");
599
- return Wt(e);
600
- }, qe = (e) => {
617
+ return tr(e);
618
+ }, nt = (e) => {
601
619
  try {
602
620
  return new Headers(e);
603
621
  } catch {
604
622
  throw new TypeError("[markdown-explorer] authenticate returned headers that are not a valid headers init (their values are not logged)");
605
623
  }
606
- }, et = (e) => e instanceof Response ? new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`) : e, Mn = (e) => {
624
+ }, ot = (e) => e instanceof Response ? new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`) : e, Fn = (e) => {
607
625
  if (typeof e != "string") throw new TypeError(`[markdown-explorer] scopeSecret must be a string; got ${typeof e}`);
608
- if (e.length < Ve) throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(Ve)} characters; got ${String(e.length)}`);
626
+ if (e.length < et) throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(et)} characters; got ${String(e.length)}`);
609
627
  return e;
610
- }, vn = (e, t) => {
611
- if (!Qt(t)) throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);
628
+ }, Un = (e, t) => {
629
+ if (!ar(t)) throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);
612
630
  for (const r of Object.keys(t))
613
- if (!Ze.includes(r)) throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${Ze.join(", ")}`);
614
- G(`${e}.boundary.contains`, t.contains, !1), G(`${e}.boundary.confirm`, t.confirm, !0);
615
- }, Pn = (e) => {
631
+ if (!tt.includes(r)) throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${tt.join(", ")}`);
632
+ Y(`${e}.boundary.contains`, t.contains, !1), Y(`${e}.boundary.confirm`, t.confirm, !0);
633
+ }, Xn = (e) => {
616
634
  if (!Array.isArray(e)) throw new TypeError("[markdown-explorer] sources must be an array");
617
635
  const t = e;
618
636
  if (t.length === 0) throw new RangeError("[markdown-explorer] sources must hold at least one source");
619
637
  const r = /* @__PURE__ */ new Set();
620
638
  for (const [n, a] of t.entries()) {
621
639
  if (a === null || typeof a != "object") throw new TypeError(`[markdown-explorer] sources[${String(n)}] must be an object`);
622
- const { id: o, label: i, boundary: l, tree: y, children: x, ancestors: f, cacheScope: w } = a;
623
- if (!Yt(o))
624
- throw new RangeError(`[markdown-explorer] sources[${String(n)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${typeof o == "string" ? JSON.stringify(o) : typeof o}`);
625
- const O = `source ${JSON.stringify(o)}`;
626
- if (r.has(o)) throw new RangeError(`[markdown-explorer] source ids must be unique; ${JSON.stringify(o)} repeats at sources[${String(n)}]`);
627
- if (r.add(o), typeof i != "string" && typeof i != "function") throw new TypeError(`[markdown-explorer] ${O}.label must be a string or a function`);
628
- if (typeof i == "string" && i.trim() === "") throw new RangeError(`[markdown-explorer] ${O}.label must not be blank`);
629
- if (vn(O, l), G(`${O}.tree`, y, !1), G(`${O}.children`, x, !0), G(`${O}.ancestors`, f, !0), w !== void 0 && w !== "principal" && w !== "shared") throw new RangeError(`[markdown-explorer] ${O}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(w)}`);
640
+ const { id: s, label: c, boundary: f, tree: y, children: k, ancestors: p, cacheScope: h } = a;
641
+ if (!rr(s))
642
+ throw new RangeError(`[markdown-explorer] sources[${String(n)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${typeof s == "string" ? JSON.stringify(s) : typeof s}`);
643
+ const x = `source ${JSON.stringify(s)}`;
644
+ if (r.has(s)) throw new RangeError(`[markdown-explorer] source ids must be unique; ${JSON.stringify(s)} repeats at sources[${String(n)}]`);
645
+ if (r.add(s), typeof c != "string" && typeof c != "function") throw new TypeError(`[markdown-explorer] ${x}.label must be a string or a function`);
646
+ if (typeof c == "string" && c.trim() === "") throw new RangeError(`[markdown-explorer] ${x}.label must not be blank`);
647
+ if (Un(x, f), Y(`${x}.tree`, y, !1), Y(`${x}.children`, k, !0), Y(`${x}.ancestors`, p, !0), h !== void 0 && h !== "principal" && h !== "shared") throw new RangeError(`[markdown-explorer] ${x}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(h)}`);
630
648
  }
631
649
  return t;
632
- }, $n = (e) => {
650
+ }, Gn = (e) => {
633
651
  if (e === !1) return !1;
634
- if (e === void 0) return pe;
652
+ if (e === void 0) return he;
635
653
  if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] treeCache must be { ttlMs, maxEntries, maxBytes } or false");
636
654
  const { ttlMs: t, maxEntries: r, maxBytes: n } = e;
637
655
  return {
638
- ttlMs: t === void 0 ? pe.ttlMs : ye("treeCache.ttlMs", t, Number.MAX_SAFE_INTEGER),
639
- maxEntries: r === void 0 ? pe.maxEntries : ye("treeCache.maxEntries", r, Number.MAX_SAFE_INTEGER),
640
- maxBytes: n === void 0 ? pe.maxBytes : ye("treeCache.maxBytes", n, Number.MAX_SAFE_INTEGER)
656
+ ttlMs: t === void 0 ? he.ttlMs : me("treeCache.ttlMs", t, Number.MAX_SAFE_INTEGER),
657
+ maxEntries: r === void 0 ? he.maxEntries : me("treeCache.maxEntries", r, Number.MAX_SAFE_INTEGER),
658
+ maxBytes: n === void 0 ? he.maxBytes : me("treeCache.maxBytes", n, Number.MAX_SAFE_INTEGER)
641
659
  };
642
- }, tt = (e) => {
660
+ }, st = (e) => {
643
661
  if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] authenticate must resolve to { status, ... }");
644
662
  const { status: t } = e;
645
663
  if (t !== "signed-in" && t !== "signed-out" && t !== "forbidden") throw new TypeError(`[markdown-explorer] authenticate resolved to an unknown status ${JSON.stringify(t)}`);
646
664
  return e;
647
- }, rt = (e, t) => {
665
+ }, at = (e, t) => {
648
666
  if (!(t instanceof Response)) throw new TypeError(`[markdown-explorer] ${e} must return a Response`);
649
667
  return t;
650
- }, nt = (e, t) => {
668
+ }, it = (e, t) => {
651
669
  if (typeof t != "string" || t === "") throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");
652
- return Ft("sha256", e).update(t, "utf8").digest("base64url").slice(0, _n);
653
- }, jn = (e) => e.view === "multi" ? e.docs : e.doc === null ? [] : [e.doc], we = (e, t) => {
670
+ return Wt("sha256", e).update(t, "utf8").digest("base64url").slice(0, zn);
671
+ }, Jn = (e) => e.view === "multi" ? e.docs : e.doc === null ? [] : [e.doc], fe = (e, t) => {
654
672
  const r = e.getAll(t), [n] = r;
655
673
  return r.length === 1 && n !== void 0 && n !== "" ? n : null;
656
- }, ae = (e, t, r, n = {}) => {
674
+ }, oe = (e, t, r, n = {}) => {
657
675
  const a = new Headers(r);
658
- for (const [o, i] of Object.entries({ ...Rn, ...n })) a.set(o, i);
676
+ for (const [s, c] of Object.entries({ ...jn, ...n })) a.set(s, c);
659
677
  return new Response(t, { status: e, headers: a });
660
- }, F = (e, t, r) => ae(zt[e.reason], JSON.stringify({ failure: e }), t, r), ot = (e, t) => {
678
+ }, F = (e, t, r) => oe(Xt[e.reason], JSON.stringify({ failure: e }), t, r), ct = (e, t) => {
661
679
  const r = t === "refresh" ? ["POST"] : ["GET", "HEAD"];
662
- return r.includes(e.method.toUpperCase()) ? null : ae(405, JSON.stringify({ failure: { reason: "invalid" } }), void 0, { Allow: r.join(", ") });
663
- }, st = (e) => {
664
- if (e.headers.get(dt) !== Dt) return !1;
665
- const t = e.headers.get("Sec-Fetch-Site");
666
- return t === null || t === "same-origin";
667
- }, Ln = ({ parentHeaders: e, loaderHeaders: t, errorHeaders: r }) => {
680
+ return r.includes(e.method.toUpperCase()) ? null : oe(405, JSON.stringify({ failure: { reason: "invalid" } }), void 0, { Allow: r.join(", ") });
681
+ }, ut = (e) => e.headers.get(wt) === Gt && Vt(e, Zt) === void 0, Yn = ({ parentHeaders: e, loaderHeaders: t, errorHeaders: r }) => {
668
682
  const n = new Headers(), a = r === void 0 ? [e, t] : [e, t, r];
669
- for (const o of a)
670
- for (const [i, l] of o)
671
- i !== "set-cookie" && n.set(i, l);
683
+ for (const s of a)
684
+ for (const [c, f] of s)
685
+ c !== "set-cookie" && n.set(c, f);
672
686
  return n;
673
- }, co = (e) => {
687
+ }, So = (e) => {
674
688
  if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] the server configuration must be an object");
675
- const t = In(e.config), r = Mn(e.scopeSecret);
676
- G("authenticate", e.authenticate, !1), G("principalKey", e.principalKey, !1), G("document", e.document, !1), G("asset", e.asset, !1), G("signedOutPage", e.signedOutPage, !1), G("forbiddenPage", e.forbiddenPage, !0), G("notices", e.notices, !0), G("onTreeRefreshed", e.onTreeRefreshed, !0);
677
- const n = Pn(e.sources), a = Gt(
689
+ const t = Bn(e.config), r = Fn(e.scopeSecret);
690
+ Y("authenticate", e.authenticate, !1), Y("principalKey", e.principalKey, !1), Y("document", e.document, !1), Y("asset", e.asset, !1), Y("signedOutPage", e.signedOutPage, !1), Y("forbiddenPage", e.forbiddenPage, !0), Y("notices", e.notices, !0), Y("onTreeRefreshed", e.onTreeRefreshed, !0);
691
+ const n = Xn(e.sources), a = qt(
678
692
  t,
679
- n.map((s) => s.id)
680
- ), o = e.logger;
681
- if (o !== void 0 && (o === null || typeof o != "object" || typeof o.error != "function"))
693
+ n.map((o) => o.id)
694
+ ), s = e.logger;
695
+ if (s !== void 0 && (s === null || typeof s != "object" || typeof s.error != "function"))
682
696
  throw new TypeError("[markdown-explorer] logger must be an object with an error function");
683
- const i = e.logger === void 0 ? Ir : e.logger, l = lt(e.deny), y = e.deferredTimeoutMs === void 0 ? On : ye("deferredTimeoutMs", e.deferredTimeoutMs, Nn), x = $n(e.treeCache), f = () => Date.now(), w = x === !1 ? wn(f) : pn({ ...x, now: f }), O = an(e.sanitizer, t.multiView.maxPanels), _ = fn({ iframeHosts: t.iframeHosts, dataPath: t.dataPath, options: O, pool: un(cn(), O) }), v = new Map(n.map((s) => [s.id, s])), R = Jt(t), { authenticate: k, principalKey: j, signedOutPage: S, forbiddenPage: A, onTreeRefreshed: D } = e, C = (s, m) => {
684
- if (typeof s.label == "string") return s.label;
685
- const c = s.label(m);
686
- if (typeof c != "string" || c.trim() === "") throw new TypeError(`[markdown-explorer] the label of source ${JSON.stringify(s.id)} must be a non-blank string`);
687
- return c;
688
- }, u = (s, m) => s.cacheScope === "shared" ? s.id : `${s.id}\0${m}`, h = (s, m) => {
689
- const c = (p) => ee(i, { operation: "boundary", sourceId: s.id, path: m, error: p });
690
- let d;
697
+ const c = e.logger === void 0 ? Dr : e.logger, f = pt(e.deny), y = e.deferredTimeoutMs === void 0 ? Ln : me("deferredTimeoutMs", e.deferredTimeoutMs, Dn), k = e.textMaxBytes === void 0 ? Fr : me("textMaxBytes", e.textMaxBytes, Ur), p = Gn(e.treeCache), h = () => Date.now(), x = p === !1 ? _n(h) : On({ ...p, now: h }), R = yn(e.sanitizer, t.multiView.maxPanels), v = xn({ iframeHosts: t.iframeHosts, dataPath: t.dataPath, options: R, pool: bn(En(), R) }), _ = new Map(n.map((o) => [o.id, o])), O = er(t), { authenticate: L, principalKey: S, signedOutPage: N, forbiddenPage: H, onTreeRefreshed: j } = e, d = (o, l) => {
698
+ if (typeof o.label == "string") return o.label;
699
+ const i = o.label(l);
700
+ if (typeof i != "string" || i.trim() === "") throw new TypeError(`[markdown-explorer] the label of source ${JSON.stringify(o.id)} must be a non-blank string`);
701
+ return i;
702
+ }, E = (o, l) => o.cacheScope === "shared" ? o.id : `${o.id}\0${l}`, w = (o, l) => {
703
+ const i = (m) => ne(c, { operation: "boundary", sourceId: o.id, path: l, error: m });
704
+ let u;
691
705
  try {
692
- d = s.boundary.contains(m);
693
- } catch (p) {
694
- return c(p), !1;
706
+ u = o.boundary.contains(l);
707
+ } catch (m) {
708
+ return i(m), !1;
695
709
  }
696
- return typeof d == "boolean" ? d : (Xe(d, c), c(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(s.id)} must return a boolean; got ${typeof d}`)), !1);
697
- }, g = async (s, m, c) => {
698
- const { confirm: d } = s.boundary;
699
- if (d === void 0) return { status: "inside", readPath: c };
700
- let p;
710
+ return typeof u == "boolean" ? u : (Ye(u, i), i(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(o.id)} must return a boolean; got ${typeof u}`)), !1);
711
+ }, T = async (o, l, i) => {
712
+ const { confirm: u } = o.boundary;
713
+ if (u === void 0) return { status: "inside", readPath: i };
714
+ let m;
701
715
  try {
702
- p = await d(m, c);
703
- } catch (K) {
704
- return { status: "error", failure: Q(K, { operation: "boundary", sourceId: s.id, path: c }, m.signal, i) };
716
+ m = await u(l, i);
717
+ } catch (J) {
718
+ return { status: "error", failure: Z(J, { operation: "boundary", sourceId: o.id, path: i }, l.signal, c) };
705
719
  }
706
- const E = (K) => (ee(i, { operation: "boundary", sourceId: s.id, path: c, error: new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(s.id)} ${K}`) }), { status: "outside" });
707
- if (p === null || typeof p != "object") return E(`must resolve to { inside, readPath? }; got ${p === null ? "null" : typeof p}`);
708
- const { inside: I, readPath: z } = p;
709
- return I === !1 ? { status: "outside" } : I !== !0 || typeof z != "string" ? E("must resolve to { inside: false } or { inside: true, readPath: string }") : !te(z) || l.deniesPath(z) ? (ee(i, { operation: "boundary", sourceId: s.id, path: c, error: new RangeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(s.id)} answered a readPath the explorer does not serve (unacceptable or denied)`) }), { status: "error", failure: { reason: "failed" } }) : { status: "inside", readPath: z };
710
- }, T = async (s, m) => {
711
- const c = n.filter((p) => h(p, m));
712
- if (c.length === 0) return { status: "error", failure: { reason: "forbidden" } };
713
- if (c.some((p) => p.boundary.confirm === void 0)) return { status: "inside", readPath: m };
714
- let d = null;
715
- for (const p of c) {
716
- const E = await g(p, s, m);
717
- if (E.status === "inside") return E;
718
- E.status === "error" && d === null && (d = E.failure);
720
+ const g = (J) => (ne(c, { operation: "boundary", sourceId: o.id, path: i, error: new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} ${J}`) }), { status: "outside" });
721
+ if (m === null || typeof m != "object") return g(`must resolve to { inside, readPath? }; got ${m === null ? "null" : typeof m}`);
722
+ const { inside: M, readPath: D } = m;
723
+ return M === !1 ? { status: "outside" } : M !== !0 || typeof D != "string" ? g("must resolve to { inside: false } or { inside: true, readPath: string }") : !ee(D) || f.deniesPath(D) ? (ne(c, { operation: "boundary", sourceId: o.id, path: i, error: new RangeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} answered a readPath the explorer does not serve (unacceptable or denied)`) }), { status: "error", failure: { reason: "failed" } }) : { status: "inside", readPath: D };
724
+ }, b = async (o, l) => {
725
+ const i = n.filter((m) => w(m, l));
726
+ if (i.length === 0) return { status: "error", failure: { reason: "forbidden" } };
727
+ if (i.some((m) => m.boundary.confirm === void 0)) return { status: "inside", readPath: l };
728
+ let u = null;
729
+ for (const m of i) {
730
+ const g = await T(m, o, l);
731
+ if (g.status === "inside") return g;
732
+ g.status === "error" && u === null && (u = g.failure);
719
733
  }
720
- return { status: "error", failure: d === null ? { reason: "forbidden" } : d };
721
- }, b = (s, m, c) => {
722
- const d = ({ path: p, reason: E }) => Pr(i, { operation: c.operation, sourceId: c.sourceId, path: p, error: new TypeError(`[markdown-explorer] an entry with ${E} was left out`) });
734
+ return { status: "error", failure: u === null ? { reason: "forbidden" } : u };
735
+ }, A = (o, l, i) => {
736
+ const u = ({ path: m, reason: g }) => Br(c, { operation: i.operation, sourceId: i.sourceId, path: m, error: new TypeError(`[markdown-explorer] an entry with ${g} was left out`) });
723
737
  try {
724
- return { status: "ok", entries: yn(s, l, m.children !== void 0, d, (p) => h(m, p)) };
725
- } catch (p) {
726
- return ee(i, { ...c, error: p }), { status: "error", failure: { reason: "failed" } };
738
+ return { status: "ok", entries: Nn(o, f, l.children !== void 0, u, (m) => w(l, m)) };
739
+ } catch (m) {
740
+ return ne(c, { ...i, error: m }), { status: "error", failure: { reason: "failed" } };
727
741
  }
728
- }, N = async (s, m, c) => {
729
- let d;
742
+ }, P = async (o, l, i) => {
743
+ let u;
730
744
  try {
731
- d = await s.tree(m);
732
- } catch (E) {
733
- return { status: "error", failure: Q(E, { operation: "tree", sourceId: s.id }, m.signal, i) };
745
+ u = await o.tree(l);
746
+ } catch (g) {
747
+ return { status: "error", failure: Z(g, { operation: "tree", sourceId: o.id }, l.signal, c) };
734
748
  }
735
- const p = b(d, s, { operation: "tree", sourceId: s.id });
736
- return p.status === "ok" ? { status: "ok", entries: p.entries, loadedAt: c } : p;
737
- }, P = (s, m, c, d) => (p, E) => N(s, { principal: m, request: c, signal: p, refresh: d }, E), B = (s, m, c, d, p) => w.load(u(s, c), p, P(s, m, d, !1)), M = (s, m, c, d) => w.refresh(u(s, c), d.signal, P(s, m, d, !0)), X = (s, m) => {
738
- if (D === void 0) return;
739
- const c = (d) => ee(i, { operation: "refresh", sourceId: s.id, error: d });
749
+ const m = A(u, o, { operation: "tree", sourceId: o.id });
750
+ return m.status === "ok" ? { status: "ok", entries: m.entries, loadedAt: i } : m;
751
+ }, B = (o, l, i, u) => (m, g) => P(o, { principal: l, request: i, signal: m, refresh: u }, g), I = (o, l, i, u, m) => x.load(E(o, i), m, B(o, l, u, !1)), X = (o, l, i, u) => x.refresh(E(o, i), u.signal, B(o, l, u, !0)), W = (o, l) => {
752
+ if (j === void 0) return;
753
+ const i = (u) => ne(c, { operation: "refresh", sourceId: o.id, error: u });
740
754
  try {
741
- Xe(D(m), c);
742
- } catch (d) {
743
- c(d);
755
+ Ye(j(l), i);
756
+ } catch (u) {
757
+ i(u);
744
758
  }
745
- }, J = async (s, m, c, d) => {
746
- if (l.deniesPath(d) || !h(s, d)) return { status: "error", failure: { reason: "forbidden" } };
747
- const p = await g(s, c, d);
748
- if (p.status === "outside") return { status: "error", failure: { reason: "forbidden" } };
749
- if (p.status === "error") return { status: "error", failure: p.failure };
750
- let E;
759
+ }, U = async (o, l, i, u) => {
760
+ if (f.deniesPath(u) || !w(o, u)) return { status: "error", failure: { reason: "forbidden" } };
761
+ const m = await T(o, i, u);
762
+ if (m.status === "outside") return { status: "error", failure: { reason: "forbidden" } };
763
+ if (m.status === "error") return { status: "error", failure: m.failure };
764
+ let g;
751
765
  try {
752
- E = await m(c, d, p.readPath);
753
- } catch (I) {
754
- return { status: "error", failure: Q(I, { operation: "children", sourceId: s.id, path: d }, c.signal, i) };
766
+ g = await l(i, u, m.readPath);
767
+ } catch (M) {
768
+ return { status: "error", failure: Z(M, { operation: "children", sourceId: o.id, path: u }, i.signal, c) };
755
769
  }
756
- return b(E, s, { operation: "children", sourceId: s.id, path: d });
757
- }, U = async (s, m, c, d) => {
758
- if (l.deniesPath(d)) return { status: "error", failure: { reason: "forbidden" } };
759
- if (!h(s, d)) return { status: "ok", ancestors: null };
760
- const p = await g(s, c, d);
761
- if (p.status === "outside") return { status: "ok", ancestors: null };
762
- if (p.status === "error") return { status: "error", failure: p.failure };
763
- let E;
770
+ return A(g, o, { operation: "children", sourceId: o.id, path: u });
771
+ }, re = async (o, l, i, u) => {
772
+ const m = await T(o, i, u);
773
+ if (m.status === "outside") return { status: "ok", ancestors: null };
774
+ if (m.status === "error") return { status: "error", failure: m.failure };
775
+ let g;
764
776
  try {
765
- E = await m(c, d, p.readPath, { maxDepth: t.revealDocument.maxDepth });
766
- } catch (I) {
767
- return { status: "error", failure: Q(I, { operation: "ancestors", sourceId: s.id, path: d }, c.signal, i) };
777
+ g = await l(i, u, m.readPath, { maxDepth: t.revealDocument.maxDepth });
778
+ } catch (M) {
779
+ return { status: "error", failure: Z(M, { operation: "ancestors", sourceId: o.id, path: u }, i.signal, c) };
768
780
  }
769
- if (Array.isArray(E) && E.length > t.revealDocument.maxDepth) return { status: "ok", ancestors: null };
781
+ if (Array.isArray(g) && g.length > t.revealDocument.maxDepth) return { status: "ok", ancestors: null };
770
782
  try {
771
- return { status: "ok", ancestors: gn(E, d, l, (I) => h(s, I)) };
772
- } catch (I) {
773
- return ee(i, { operation: "ancestors", sourceId: s.id, path: d, error: I }), { status: "error", failure: { reason: "failed" } };
783
+ return { status: "ok", ancestors: An(g, u, f, (M) => w(o, M)) };
784
+ } catch (M) {
785
+ return ne(c, { operation: "ancestors", sourceId: o.id, path: u, error: M }), { status: "error", failure: { reason: "failed" } };
774
786
  }
775
- }, q = async (s, m, c) => {
776
- if (l.deniesPath(c)) return ne("forbidden");
777
- const d = await T(s, c);
778
- if (d.status === "error") return { kind: "failure", failure: d.failure };
779
- let p;
787
+ }, z = async (o, l, i, u) => f.deniesPath(u) ? { status: "error", failure: { reason: "forbidden" } } : w(o, u) ? re(o, l, i, u) : { status: "ok", ancestors: null }, K = async (o, l, i) => {
788
+ if (f.deniesPath(i)) return { status: "error", failure: { reason: "forbidden" } };
789
+ for (const u of [o, ...n.filter((m) => m !== o)]) {
790
+ if (l.signal.aborted) break;
791
+ const m = u.ancestors;
792
+ if (m === void 0 || !w(u, i)) continue;
793
+ const g = await re(u, m, l, i);
794
+ if (g.status === "ok" && g.ancestors !== null) return { status: "ok", source: u.id, ancestors: g.ancestors };
795
+ }
796
+ return Cn;
797
+ }, V = async (o, l, i) => {
798
+ if (f.deniesPath(i)) return te("forbidden");
799
+ const u = await b(o, i);
800
+ if (u.status === "error") return { kind: "failure", failure: u.failure };
801
+ let m;
780
802
  try {
781
- p = await e.document(s, c, d.readPath);
782
- } catch (z) {
783
- return { kind: "failure", failure: Q(z, { operation: "document", path: c }, s.signal, i) };
803
+ m = await e.document(o, i, u.readPath);
804
+ } catch (D) {
805
+ return { kind: "failure", failure: Z(D, { operation: "document", path: i }, o.signal, c) };
784
806
  }
785
- let E;
807
+ let g;
786
808
  try {
787
- E = Tn(p, (z) => Ht(t.dataPath, c, z));
788
- } catch (z) {
789
- return ee(i, { operation: "document", path: c, error: z }), ne("failed");
809
+ g = Pn(m, (D) => je(t.dataPath, i, D));
810
+ } catch (D) {
811
+ return ne(c, { operation: "document", path: i, error: D }), te("failed");
790
812
  }
791
- if (E.kind !== "unsanitized-markdown") return E;
792
- const I = await _(E.html, { scope: m, signal: s.signal });
793
- return I.status === "sanitized" ? { kind: "markdown", name: E.name, htmlContent: I.html, headings: E.headings } : (I.cause !== null && ee(i, { operation: "document", path: c, error: I.cause }), ne(I.reason));
794
- }, L = async (s) => {
795
- if (e.notices === void 0) return Re;
813
+ if (g.kind !== "unsanitized-markdown") return g;
814
+ const M = await v(g.html, { scope: l, signal: o.signal });
815
+ return M.status === "sanitized" ? { kind: "markdown", name: g.name, htmlContent: M.html, headings: g.headings } : (M.cause !== null && ne(c, { operation: "document", path: i, error: M.cause }), te(M.reason));
816
+ }, Q = async (o) => {
817
+ if (e.notices === void 0) return _e;
796
818
  try {
797
- return kn(await e.notices(s));
798
- } catch (m) {
799
- return Q(m, { operation: "notices" }, s.signal, i), Re;
819
+ return $n(await e.notices(o));
820
+ } catch (l) {
821
+ return Z(l, { operation: "notices" }, o.signal, c), _e;
822
+ }
823
+ }, pe = async (o, l, i) => {
824
+ const u = fe(l, de.path);
825
+ if (u === null || !ee(u)) return F({ reason: "invalid" }, i);
826
+ if (f.deniesPath(u))
827
+ return Je(c, { operation: "asset", path: u }), F({ reason: "forbidden" }, i);
828
+ const m = await b(o, u);
829
+ if (m.status === "error") return F(m.failure, i);
830
+ try {
831
+ const g = qe(await e.asset(o, u, m.readPath));
832
+ return await zr(o.request, g, i);
833
+ } catch (g) {
834
+ return F(Z(g, { operation: "asset", path: u }, o.signal, c), i);
800
835
  }
801
- }, W = async (s, m, c) => {
802
- const d = we(m, fe.path);
803
- if (d === null || !te(d)) return F({ reason: "invalid" }, c);
804
- if (l.deniesPath(d))
805
- return $r(i, { operation: "asset", path: d }), F({ reason: "forbidden" }, c);
806
- const p = await T(s, d);
807
- if (p.status === "error") return F(p.failure, c);
836
+ }, It = async (o, l) => {
837
+ if (f.deniesPath(l))
838
+ return Je(c, { operation: "text", path: l }), te("forbidden");
839
+ const i = await b(o, l);
840
+ if (i.status === "error") return { kind: "failure", failure: i.failure };
808
841
  try {
809
- const E = xn(await e.asset(s, d, p.readPath));
810
- return await Ar(s.request, E, c);
811
- } catch (E) {
812
- return F(Q(E, { operation: "asset", path: d }, s.signal, i), c);
842
+ const u = qe(await e.asset(o, l, i.readPath)), m = await Gr(u, k);
843
+ return m === null ? te("unsupported") : { kind: "text", name: u.name, text: m.text, truncated: m.truncated, url: je(t.dataPath, l, u.version) };
844
+ } catch (u) {
845
+ return { kind: "failure", failure: Z(u, { operation: "text", path: l }, o.signal, c) };
813
846
  }
814
- }, Z = async ({ request: s, url: m, params: c }) => {
815
- const d = tt(await k(s, Qe)), p = qe(d.headers);
816
- if (p.set("Cache-Control", bt), d.status === "signed-out") throw rt("signedOutPage", S(s, p));
817
- if (d.status === "forbidden") throw A === void 0 ? je(null, { status: 403, headers: p }) : rt("forbiddenPage", A(s, p));
818
- const E = Kt(a, c["*"], m.searchParams);
819
- if (E.kind === "redirect") throw Xt(E.href, { headers: p });
820
- const { location: I } = E, { principal: z } = d, K = nt(r, j(z)), ue = v.get(I.source);
821
- if (ue === void 0) throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(I.source)}`);
822
- const le = { signal: s.signal, timeoutMs: y, late: null, handOverMs: y }, re = {
823
- scope: K,
824
- sources: n.map((H) => ({ id: H.id, label: C(H, z) })),
825
- settings: Vt(Zt(s.headers.get("Cookie"), t.settingsCookie), R),
826
- tree: I.view === "single" ? null : {
827
- sourceId: I.source,
828
- result: xe(le, (H) => B(ue, z, K, s, H).then((V) => V.result))
847
+ }, Mt = async ({ request: o, url: l, params: i }) => {
848
+ const u = st(await L(o, rt)), m = nt(u.headers);
849
+ if (m.set("Cache-Control", kt), u.status === "signed-out") throw at("signedOutPage", N(o, m));
850
+ if (u.status === "forbidden") throw H === void 0 ? ze(null, { status: 403, headers: m }) : at("forbiddenPage", H(o, m));
851
+ const g = nr(a, i["*"], l.searchParams);
852
+ if (g.kind === "redirect") throw Qt(g.href, { headers: m });
853
+ const { location: M } = g, { principal: D } = u, J = it(r, S(D)), se = _.get(M.source);
854
+ if (se === void 0) throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(M.source)}`);
855
+ const le = { signal: o.signal, timeoutMs: y, late: null, handOverMs: y }, q = {
856
+ scope: J,
857
+ sources: n.map((C) => ({ id: C.id, label: d(C, D) })),
858
+ settings: or(sr(o.headers.get("Cookie"), t.settingsCookie), O),
859
+ tree: M.view === "single" ? null : {
860
+ sourceId: M.source,
861
+ result: xe(le, (C) => I(se, D, J, o, C).then((G) => G.result))
829
862
  },
830
- documents: jn(I).map((H) => ({ path: H, document: xe(le, (V) => q({ principal: z, request: s, signal: V, refresh: !1 }, K, H)) })),
831
- notices: xe({ signal: s.signal, timeoutMs: y, late: Re, handOverMs: 0 }, (H) => L({ principal: z, request: s, signal: H, refresh: !1 }))
863
+ documents: Jn(M).map((C) => ({ path: C, document: xe(le, (G) => V({ principal: D, request: o, signal: G, refresh: !1 }, J, C)) })),
864
+ notices: xe({ signal: o.signal, timeoutMs: y, late: _e, handOverMs: 0 }, (C) => Q({ principal: D, request: o, signal: C, refresh: !1 }))
832
865
  };
833
- return je(re, { headers: p });
834
- }, Y = async (s, m) => {
835
- const c = tt(await k(s, m));
836
- return { authentication: c, headers: qe(c.headers) };
837
- }, de = async (s, m, c) => {
838
- let d;
866
+ return ze(q, { headers: m });
867
+ }, ve = async (o, l) => {
868
+ const i = st(await L(o, l));
869
+ return { authentication: i, headers: nt(i.headers) };
870
+ }, vt = async (o, l, i) => {
871
+ let u;
839
872
  try {
840
- d = await Y(m, Qe);
841
- } catch (V) {
842
- return F(Q(et(V), { operation: "authenticate" }, m.signal, i));
873
+ u = await ve(l, rt);
874
+ } catch (G) {
875
+ return F(Z(ot(G), { operation: "authenticate" }, l.signal, c));
843
876
  }
844
- const { authentication: p, headers: E } = d;
845
- if (p.status === "signed-out") return F({ reason: "unauthorized" }, E);
846
- if (p.status === "forbidden") return F({ reason: "forbidden" }, E);
847
- const { principal: I } = p;
848
- if (s === "asset") return W({ principal: I, request: m, signal: m.signal, refresh: !1 }, c, E);
849
- const z = nt(r, j(I));
850
- E.set(Ct, z);
851
- const K = { principal: I, request: m, signal: m.signal, refresh: !1 }, ue = () => F({ reason: "invalid" }, E);
852
- if (s === "document") {
853
- const V = we(c, fe.path);
854
- if (V === null || !te(V)) return ue();
855
- const $e = m.headers.has(dt);
856
- return $e && !st(m) ? F({ reason: "forbidden" }, E) : ae(200, JSON.stringify(await q({ ...K, refresh: $e }, z, V)), E);
877
+ const { authentication: m, headers: g } = u;
878
+ if (m.status === "signed-out") return F({ reason: "unauthorized" }, g);
879
+ if (m.status === "forbidden") return F({ reason: "forbidden" }, g);
880
+ const { principal: M } = m;
881
+ if (o === "asset") return pe({ principal: M, request: l, signal: l.signal, refresh: !1 }, i, g);
882
+ const D = it(r, S(M));
883
+ g.set(Jt, D);
884
+ const J = { principal: M, request: l, signal: l.signal, refresh: !1 }, se = () => F({ reason: "invalid" }, g);
885
+ if (o === "document") {
886
+ const G = fe(i, de.path);
887
+ if (G === null || !ee(G)) return se();
888
+ const Le = l.headers.has(wt);
889
+ return Le && !ut(l) ? F({ reason: "forbidden" }, g) : oe(200, JSON.stringify(await V({ ...J, refresh: Le }, D, G)), g);
857
890
  }
858
- const le = we(c, fe.source), re = we(c, fe.path);
859
- if (le === null || (s === "children" || s === "ancestors") && (re === null || !te(re))) return ue();
860
- const H = v.get(le);
861
- if (H === void 0) return F({ reason: "not-found" }, E);
862
- if (s === "tree") return ae(200, (await B(H, I, z, m, m.signal)).json, E);
863
- if (s === "refresh") {
864
- const V = await M(H, I, z, m);
865
- return m.signal.aborted || X(H, u(H, z)), ae(200, V.json, E);
891
+ if (o === "text") {
892
+ const G = fe(i, de.path);
893
+ return G === null || !ee(G) ? se() : oe(200, JSON.stringify(await It(J, G)), g);
866
894
  }
867
- return s === "ancestors" ? H.ancestors === void 0 || re === null ? F({ reason: "not-found" }, E) : ae(200, JSON.stringify(await U(H, H.ancestors, K, re)), E) : H.children === void 0 || re === null ? F({ reason: "not-found" }, E) : ae(200, JSON.stringify(await J(H, H.children, K, re)), E);
868
- }, Rt = async (s) => {
869
- const { authentication: m, headers: c } = await Y(s, An);
870
- if (!c.keys().next().done) throw new TypeError("[markdown-explorer] authenticate returned headers in read-only mode; a read-only authentication must only read the session (none was forwarded)");
871
- return m.status === "signed-in";
872
- }, ve = t.embeds.linkCardEndpoint === null ? null : Ut({ authorize: Rt }), _t = async (s, m) => {
895
+ const le = fe(i, de.source), q = fe(i, de.path);
896
+ if (le === null || (o === "children" || o === "ancestors" || o === "reveal") && (q === null || !ee(q))) return se();
897
+ const C = _.get(le);
898
+ if (C === void 0) return F({ reason: "not-found" }, g);
899
+ if (o === "tree") return oe(200, (await I(C, M, D, l, l.signal)).json, g);
900
+ if (o === "refresh") {
901
+ const G = await X(C, M, D, l);
902
+ return l.signal.aborted || W(C, E(C, D)), oe(200, G.json, g);
903
+ }
904
+ return o === "ancestors" ? C.ancestors === void 0 || q === null ? F({ reason: "not-found" }, g) : oe(200, JSON.stringify(await z(C, C.ancestors, J, q)), g) : o === "reveal" ? q === null ? se() : oe(200, JSON.stringify(await K(C, J, q)), g) : C.children === void 0 || q === null ? F({ reason: "not-found" }, g) : oe(200, JSON.stringify(await U(C, C.children, J, q)), g);
905
+ }, Pt = async (o) => {
906
+ const { authentication: l, headers: i } = await ve(o, Hn);
907
+ if (!i.keys().next().done) throw new TypeError("[markdown-explorer] authenticate returned headers in read-only mode; a read-only authentication must only read the session (none was forwarded)");
908
+ return l.status === "signed-in";
909
+ }, Pe = t.embeds.linkCardEndpoint === null ? null : Kt({ authorize: Pt }), $t = async (o, l) => {
873
910
  try {
874
- return await s(m);
875
- } catch (c) {
876
- return F(Q(et(c), { operation: "authenticate" }, m.signal, i));
911
+ return await o(l);
912
+ } catch (i) {
913
+ return F(Z(ot(i), { operation: "authenticate" }, l.signal, c));
877
914
  }
878
- }, Pe = async (s, m, c) => {
879
- if (new URL(s.url).pathname.endsWith(".data")) return F({ reason: "not-found" });
880
- if (!Lt(c)) return F({ reason: "not-found" });
881
- if (c === "link-card") {
882
- if (ve === null) return F({ reason: "not-found" });
883
- const p = ot(s, c);
884
- return p !== null ? p : _t(ve, s);
915
+ }, $e = async (o, l, i) => {
916
+ if (new URL(o.url).pathname.endsWith(".data")) return F({ reason: "not-found" });
917
+ if (!Ut(i)) return F({ reason: "not-found" });
918
+ if (i === "link-card") {
919
+ if (Pe === null) return F({ reason: "not-found" });
920
+ const m = ct(o, i);
921
+ return m !== null ? m : $t(Pe, o);
885
922
  }
886
- const d = ot(s, c);
887
- if (d !== null) return d;
888
- if (c === "refresh" && !st(s)) return F({ reason: "forbidden" });
923
+ const u = ct(o, i);
924
+ if (u !== null) return u;
925
+ if (i === "refresh" && !ut(o)) return F({ reason: "forbidden" });
889
926
  try {
890
- return await de(c, s, m.searchParams);
891
- } catch (p) {
892
- return F(Q(p, { operation: c }, s.signal, i));
927
+ return await vt(i, o, l.searchParams);
928
+ } catch (m) {
929
+ return F(Z(m, { operation: i }, o.signal, c));
893
930
  }
894
931
  };
895
932
  return Object.freeze({
896
- loader: Z,
897
- headers: Ln,
898
- dataLoader: ({ request: s, url: m, params: c }) => Pe(s, m, c["*"]),
899
- dataAction: ({ request: s, url: m, params: c }) => Pe(s, m, c["*"]),
900
- forgetTree: (s) => {
901
- if (typeof s != "string") throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof s}`);
902
- w.forget(s);
933
+ loader: Mt,
934
+ headers: Yn,
935
+ dataLoader: ({ request: o, url: l, params: i }) => $e(o, l, i["*"]),
936
+ dataAction: ({ request: o, url: l, params: i }) => $e(o, l, i["*"]),
937
+ forgetTree: (o) => {
938
+ if (typeof o != "string") throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof o}`);
939
+ x.forget(o);
903
940
  }
904
941
  });
905
- }, he = Object.freeze({ maxEntries: 2e4, maxDocumentBytes: 2 * 1024 * 1024, textPreviewBytes: 8 * 1024, walkConcurrency: 8 }), zn = /* @__PURE__ */ new Set(["md", "markdown", "mdx"]), St = new Map([
942
+ }, ge = Object.freeze({ maxEntries: 2e4, maxDocumentBytes: 2 * 1024 * 1024, textPreviewBytes: 8 * 1024, walkConcurrency: 8 }), Wn = /* @__PURE__ */ new Set(["md", "markdown", "mdx"]), Ot = new Map([
906
943
  ...[
907
944
  ["png", "image/png"],
908
945
  ["jpg", "image/jpeg"],
@@ -937,7 +974,7 @@ const Mr = (e) => e instanceof Error && Object.hasOwn(e, wt) && ut(e.reason), vr
937
974
  ["wma", "audio/x-ms-wma"]
938
975
  ].map(([e, t]) => [e, { kind: "media", mediaType: "audio", contentType: t }]),
939
976
  ["pdf", { kind: "media", mediaType: "pdf", contentType: "application/pdf" }]
940
- ]), Dn = /* @__PURE__ */ new Set([
977
+ ]), Kn = /* @__PURE__ */ new Set([
941
978
  "txt",
942
979
  "text",
943
980
  "log",
@@ -1062,7 +1099,7 @@ const Mr = (e) => e instanceof Error && Object.hasOwn(e, wt) && ut(e.reason), vr
1062
1099
  "eslintrc",
1063
1100
  "babelrc",
1064
1101
  "mailmap"
1065
- ]), Cn = /* @__PURE__ */ new Set([
1102
+ ]), Vn = /* @__PURE__ */ new Set([
1066
1103
  "readme",
1067
1104
  "license",
1068
1105
  "licence",
@@ -1083,17 +1120,17 @@ const Mr = (e) => e instanceof Error && Object.hasOwn(e, wt) && ut(e.reason), vr
1083
1120
  "jenkinsfile",
1084
1121
  "brewfile",
1085
1122
  "codeowners"
1086
- ]), Tt = typeof ce.O_NOFOLLOW == "number" ? ce.O_NOFOLLOW : 0, xt = typeof ce.O_NONBLOCK == "number" ? ce.O_NONBLOCK : 0, at = (e) => `${e.size}-${e.mtimeNs}`, Hn = (e) => e !== "" && e !== "." && e !== ".." && !e.includes(":") && !e.endsWith(".") && !e.endsWith(" "), it = (e) => te(e) && e === e.normalize("NFC") && e.split("/").every(Hn), kt = (e) => {
1123
+ ]), _t = typeof ue.O_NOFOLLOW == "number" ? ue.O_NOFOLLOW : 0, Rt = typeof ue.O_NONBLOCK == "number" ? ue.O_NONBLOCK : 0, lt = (e) => `${e.size}-${e.mtimeNs}`, Zn = (e) => e !== "" && e !== "." && e !== ".." && !e.includes(":") && !e.endsWith(".") && !e.endsWith(" "), dt = (e) => ee(e) && e === e.normalize("NFC") && e.split("/").every(Zn), At = (e) => {
1087
1124
  const t = e.toLowerCase(), r = t.lastIndexOf(".");
1088
1125
  return r < 0 ? "" : t.slice(r + 1);
1089
- }, Bn = (e) => {
1090
- const t = kt(e);
1091
- if (zn.has(t)) return { kind: "markdown" };
1092
- const r = St.get(t);
1126
+ }, Qn = (e) => {
1127
+ const t = At(e);
1128
+ if (Wn.has(t)) return { kind: "markdown" };
1129
+ const r = Ot.get(t);
1093
1130
  if (r !== void 0) return r.kind === "image" ? { kind: "image" } : { kind: "media", mediaType: r.mediaType };
1094
1131
  const n = e.toLowerCase();
1095
- return Dn.has(t) || !n.includes(".") && Cn.has(n) ? { kind: "text" } : { kind: "file" };
1096
- }, Ae = (e) => {
1132
+ return Kn.has(t) || !n.includes(".") && Vn.has(n) ? { kind: "text" } : { kind: "file" };
1133
+ }, Ne = (e) => {
1097
1134
  switch (typeof e == "object" && e !== null ? e.code : void 0) {
1098
1135
  case "ENOENT":
1099
1136
  case "ENOTDIR":
@@ -1109,34 +1146,34 @@ const Mr = (e) => e instanceof Error && Object.hasOwn(e, wt) && ut(e.reason), vr
1109
1146
  default:
1110
1147
  return null;
1111
1148
  }
1112
- }, Ot = (e) => {
1113
- const t = Ae(e);
1149
+ }, Nt = (e) => {
1150
+ const t = Ne(e);
1114
1151
  return t === null ? e : new Ee(t);
1115
- }, Fn = (e) => {
1152
+ }, qn = (e) => {
1116
1153
  const t = typeof e == "object" && e !== null ? e.code : void 0;
1117
1154
  return t === "EACCES" || t === "EPERM" || t === "ENOENT" || t === "ENOTDIR";
1118
- }, ct = async (e, t) => {
1155
+ }, ft = async (e, t) => {
1119
1156
  const r = [];
1120
1157
  for await (const n of e.createReadStream({ start: 0, end: t - 1, autoClose: !1 }))
1121
1158
  r.push(n);
1122
1159
  return Buffer.concat(r);
1123
- }, Un = (e, t) => e !== null ? { start: e.offset, end: e.offset + e.length - 1 } : t === 0n ? {} : { start: 0, end: Number(t) - 1 }, Xn = async (e, t, r, n) => {
1160
+ }, eo = (e, t) => e !== null ? { start: e.offset, end: e.offset + e.length - 1 } : t === 0n ? {} : { start: 0, end: Number(t) - 1 }, to = async (e, t, r, n) => {
1124
1161
  let a;
1125
1162
  try {
1126
- a = await ft(e, ce.O_RDONLY | Tt | xt);
1163
+ a = await ht(e, ue.O_RDONLY | _t | Rt);
1127
1164
  const y = await a.stat({ bigint: !0 });
1128
1165
  if (!y.isFile() || y.ino !== t.ino || y.dev !== t.dev || y.size !== t.size || y.mtimeNs !== t.mtimeNs) throw new Ee("not-found");
1129
1166
  } catch (y) {
1130
- throw await a?.close(), Ot(y);
1167
+ throw await a?.close(), Nt(y);
1131
1168
  }
1132
- const o = a.createReadStream(Un(r, t.size)), i = lr.toWeb(o), l = () => {
1133
- o.destroy(n.reason);
1169
+ const s = a.createReadStream(eo(r, t.size)), c = yr.toWeb(s), f = () => {
1170
+ s.destroy(n.reason);
1134
1171
  };
1135
- return n.aborted ? l() : n.addEventListener("abort", l, { once: !0 }), i;
1136
- }, Gn = (e, t) => {
1137
- const r = qt.compare(e, t);
1172
+ return n.aborted ? f() : n.addEventListener("abort", f, { once: !0 }), c;
1173
+ }, ro = (e, t) => {
1174
+ const r = ir.compare(e, t);
1138
1175
  return r !== 0 ? r : e === t ? 0 : e < t ? -1 : 1;
1139
- }, Jn = (e) => {
1176
+ }, no = (e) => {
1140
1177
  let t = 0;
1141
1178
  const r = [];
1142
1179
  return async (n) => {
@@ -1148,179 +1185,179 @@ const Mr = (e) => e instanceof Error && Object.hasOwn(e, wt) && ut(e.reason), vr
1148
1185
  a === void 0 ? t -= 1 : a();
1149
1186
  }
1150
1187
  };
1151
- }, Wn = (e, t) => {
1188
+ }, oo = (e, t) => {
1152
1189
  if (e.isSymbolicLink()) return "symbolic-link";
1153
1190
  if (!(e.isDirectory() || e.isFile())) return "special-file";
1154
1191
  const { name: r } = e;
1155
- return r !== r.normalize("NFC") ? "not-nfc" : r.includes(":") ? "colon" : r.endsWith(".") || r.endsWith(" ") ? "trailing-dot-or-space" : te(r) ? te(t) ? null : "path-too-long" : "control-character-or-backslash";
1156
- }, Yn = /* @__PURE__ */ new Set(["id", "label", "root", "pathPrefix", "parse", "deny", "maxEntries", "maxDocumentBytes", "textPreviewBytes", "walkConcurrency", "cacheScope", "reportSkipped"]), ge = (e, t, r) => {
1192
+ return r !== r.normalize("NFC") ? "not-nfc" : r.includes(":") ? "colon" : r.endsWith(".") || r.endsWith(" ") ? "trailing-dot-or-space" : ee(r) ? ee(t) ? null : "path-too-long" : "control-character-or-backslash";
1193
+ }, so = /* @__PURE__ */ new Set(["id", "label", "root", "pathPrefix", "parse", "deny", "maxEntries", "maxDocumentBytes", "textPreviewBytes", "walkConcurrency", "cacheScope", "reportSkipped"]), ye = (e, t, r) => {
1157
1194
  if (t === void 0) return r;
1158
1195
  if (typeof t != "number" || !Number.isSafeInteger(t) || t <= 0) throw new RangeError(`[markdown-explorer] ${e} must be a positive integer; got ${String(t)}`);
1159
1196
  return t;
1160
- }, uo = (e) => {
1197
+ }, To = (e) => {
1161
1198
  if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] createFileSystemSource needs an options object");
1162
- for (const g of Object.keys(e))
1163
- if (!Yn.has(g)) throw new TypeError(`[markdown-explorer] createFileSystemSource does not know the option ${JSON.stringify(g)}`);
1199
+ for (const w of Object.keys(e))
1200
+ if (!so.has(w)) throw new TypeError(`[markdown-explorer] createFileSystemSource does not know the option ${JSON.stringify(w)}`);
1164
1201
  const { id: t, label: r, root: n, parse: a } = e;
1165
1202
  if (typeof t != "string" || t === "") throw new TypeError("[markdown-explorer] a file-system source needs a non-empty id");
1166
1203
  if (typeof r != "string" || r.trim() === "") throw new TypeError("[markdown-explorer] a file-system source needs a non-blank label");
1167
1204
  if (typeof a != "function") throw new TypeError("[markdown-explorer] a file-system source needs a parse function");
1168
- if (typeof n != "string" || !Le(n)) throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);
1169
- let o;
1205
+ if (typeof n != "string" || !De(n)) throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);
1206
+ let s;
1170
1207
  try {
1171
- o = tr(n).isDirectory();
1172
- } catch (g) {
1173
- throw new RangeError(`[markdown-explorer] root does not exist: ${n}`, { cause: g });
1208
+ s = ur(n).isDirectory();
1209
+ } catch (w) {
1210
+ throw new RangeError(`[markdown-explorer] root does not exist: ${n}`, { cause: w });
1174
1211
  }
1175
- if (!o) throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);
1176
- const i = rr(n), l = e.pathPrefix;
1177
- if (typeof l != "string") throw new TypeError('[markdown-explorer] pathPrefix is required: "" for a source over the whole root, or relative segments ending with "/"');
1178
- if (l !== "" && !(l.endsWith("/") && it(l.slice(0, -1))))
1179
- throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(l)}`);
1180
- const y = lt(e.deny), x = ge("maxEntries", e.maxEntries, he.maxEntries), f = ge("maxDocumentBytes", e.maxDocumentBytes, he.maxDocumentBytes), w = ge("textPreviewBytes", e.textPreviewBytes, he.textPreviewBytes), O = ge("walkConcurrency", e.walkConcurrency, he.walkConcurrency), _ = e.cacheScope === void 0 ? "principal" : e.cacheScope;
1181
- if (_ !== "principal" && _ !== "shared") throw new RangeError(`[markdown-explorer] cacheScope must be "principal" or "shared"; got ${JSON.stringify(_)}`);
1212
+ if (!s) throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);
1213
+ const c = lr(n), f = e.pathPrefix;
1214
+ if (typeof f != "string") throw new TypeError('[markdown-explorer] pathPrefix is required: "" for a source over the whole root, or relative segments ending with "/"');
1215
+ if (f !== "" && !(f.endsWith("/") && dt(f.slice(0, -1))))
1216
+ throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(f)}`);
1217
+ const y = pt(e.deny), k = ye("maxEntries", e.maxEntries, ge.maxEntries), p = ye("maxDocumentBytes", e.maxDocumentBytes, ge.maxDocumentBytes), h = ye("textPreviewBytes", e.textPreviewBytes, ge.textPreviewBytes), x = ye("walkConcurrency", e.walkConcurrency, ge.walkConcurrency), R = e.cacheScope === void 0 ? "principal" : e.cacheScope;
1218
+ if (R !== "principal" && R !== "shared") throw new RangeError(`[markdown-explorer] cacheScope must be "principal" or "shared"; got ${JSON.stringify(R)}`);
1182
1219
  const v = e.reportSkipped;
1183
1220
  if (v !== void 0 && typeof v != "function") throw new TypeError("[markdown-explorer] reportSkipped must be a function");
1184
- const R = v === void 0 ? (g) => {
1185
- console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(g.sourceId)} does not list ${JSON.stringify(g.path)}: ${g.reason}`);
1186
- } : v, k = /* @__PURE__ */ new Set(), j = (g) => {
1187
- const T = sr(i, ...g.split("/")), b = ze(i, T);
1188
- return b === "" || b === ".." || b.startsWith(`..${De}`) || Le(b) ? null : T;
1189
- }, S = (g, T) => {
1190
- const b = `${T}\0${g}`;
1191
- k.has(b) || k.size >= x || (k.add(b), R({ sourceId: t, path: g, reason: T }));
1192
- }, A = async ({ signal: g }) => {
1193
- g.throwIfAborted();
1221
+ const _ = v === void 0 ? (w) => {
1222
+ console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(w.sourceId)} does not list ${JSON.stringify(w.path)}: ${w.reason}`);
1223
+ } : v, O = /* @__PURE__ */ new Set(), L = (w) => {
1224
+ const T = mr(c, ...w.split("/")), b = Ce(c, T);
1225
+ return b === "" || b === ".." || b.startsWith(`..${He}`) || De(b) ? null : T;
1226
+ }, S = (w, T) => {
1227
+ const b = `${T}\0${w}`;
1228
+ O.has(b) || O.size >= k || (O.add(b), _({ sourceId: t, path: w, reason: T }));
1229
+ }, N = async ({ signal: w }) => {
1230
+ w.throwIfAborted();
1194
1231
  const T = new AbortController(), b = () => {
1195
- T.abort(g.reason);
1232
+ T.abort(w.reason);
1196
1233
  };
1197
- g.addEventListener("abort", b, { once: !0 });
1198
- const N = Jn(O);
1234
+ w.addEventListener("abort", b, { once: !0 });
1235
+ const A = no(x);
1199
1236
  let P = 0;
1200
- const B = async (M, X) => {
1201
- const J = await N(async () => {
1237
+ const B = async (I, X) => {
1238
+ const W = await A(async () => {
1202
1239
  T.signal.throwIfAborted();
1203
1240
  try {
1204
- return await ur(M, { withFileTypes: !0 });
1205
- } catch (L) {
1206
- if (X === "" || !Fn(L)) throw L;
1241
+ return await gr(I, { withFileTypes: !0 });
1242
+ } catch (z) {
1243
+ if (X === "" || !qn(z)) throw z;
1207
1244
  return null;
1208
1245
  }
1209
1246
  });
1210
- if (T.signal.throwIfAborted(), J === null)
1211
- return S(`${l}${X}`, "unreadable-directory"), null;
1247
+ if (T.signal.throwIfAborted(), W === null)
1248
+ return S(`${f}${X}`, "unreadable-directory"), null;
1212
1249
  const U = [];
1213
- for (const L of J) {
1214
- if (y.deniesName(L.name)) continue;
1215
- const W = X === "" ? L.name : `${X}/${L.name}`, Z = `${l}${W}`, Y = Wn(L, Z);
1216
- if (Y !== null) {
1217
- S(Z, Y);
1250
+ for (const z of W) {
1251
+ if (y.deniesName(z.name)) continue;
1252
+ const K = X === "" ? z.name : `${X}/${z.name}`, V = `${f}${K}`, Q = oo(z, V);
1253
+ if (Q !== null) {
1254
+ S(V, Q);
1218
1255
  continue;
1219
1256
  }
1220
- U.push({ dirent: L, relativePath: W, path: Z });
1257
+ U.push({ dirent: z, relativePath: K, path: V });
1221
1258
  }
1222
- if (P += U.length, P > x) throw new Ee("too-large");
1223
- return U.sort((L, W) => Gn(L.dirent.name, W.dirent.name)), (await Promise.all(
1224
- U.map(async ({ dirent: L, relativePath: W, path: Z }) => {
1225
- if (!L.isDirectory()) return { name: L.name, path: Z, type: "file" };
1226
- const Y = await B(or(M, L.name), W);
1227
- return Y === null ? null : { name: L.name, path: Z, type: "directory", children: Y };
1259
+ if (P += U.length, P > k) throw new Ee("too-large");
1260
+ return U.sort((z, K) => ro(z.dirent.name, K.dirent.name)), (await Promise.all(
1261
+ U.map(async ({ dirent: z, relativePath: K, path: V }) => {
1262
+ if (!z.isDirectory()) return { name: z.name, path: V, type: "file" };
1263
+ const Q = await B(fr(I, z.name), K);
1264
+ return Q === null ? null : { name: z.name, path: V, type: "directory", children: Q };
1228
1265
  })
1229
- )).filter((L) => L !== null);
1266
+ )).filter((z) => z !== null);
1230
1267
  };
1231
1268
  try {
1232
- const M = await B(i, "");
1233
- if (M === null) throw new Error("[markdown-explorer] the source's root could not be listed");
1234
- return M;
1235
- } catch (M) {
1236
- throw T.abort(), M;
1269
+ const I = await B(c, "");
1270
+ if (I === null) throw new Error("[markdown-explorer] the source's root could not be listed");
1271
+ return I;
1272
+ } catch (I) {
1273
+ throw T.abort(), I;
1237
1274
  } finally {
1238
- g.removeEventListener("abort", b);
1275
+ w.removeEventListener("abort", b);
1239
1276
  }
1240
- }, D = async (g) => {
1241
- if (!g.startsWith(l)) return { status: "refused", reason: "not-found" };
1242
- const T = g.slice(l.length);
1243
- if (!it(T)) return { status: "refused", reason: "invalid" };
1277
+ }, H = async (w) => {
1278
+ if (!w.startsWith(f)) return { status: "refused", reason: "not-found" };
1279
+ const T = w.slice(f.length);
1280
+ if (!dt(T)) return { status: "refused", reason: "invalid" };
1244
1281
  if (y.deniesPath(T)) return { status: "refused", reason: "forbidden" };
1245
- const b = j(T);
1282
+ const b = L(T);
1246
1283
  if (b === null) return { status: "refused", reason: "forbidden" };
1247
- const N = await ir(b, { bigint: !0 });
1248
- if (N.isSymbolicLink()) return { status: "refused", reason: "forbidden" };
1249
- if (!N.isFile()) return { status: "refused", reason: "unsupported" };
1250
- const P = await cr(b);
1251
- return P !== b || y.deniesPath(ze(i, P).split(De).join("/")) ? { status: "refused", reason: "forbidden" } : { status: "file", target: b, name: T.slice(T.lastIndexOf("/") + 1), stats: N };
1252
- }, C = async (g, T, b) => {
1253
- let N;
1284
+ const A = await wr(b, { bigint: !0 });
1285
+ if (A.isSymbolicLink()) return { status: "refused", reason: "forbidden" };
1286
+ if (!A.isFile()) return { status: "refused", reason: "unsupported" };
1287
+ const P = await hr(b);
1288
+ return P !== b || y.deniesPath(Ce(c, P).split(He).join("/")) ? { status: "refused", reason: "forbidden" } : { status: "file", target: b, name: T.slice(T.lastIndexOf("/") + 1), stats: A };
1289
+ }, j = async (w, T, b) => {
1290
+ let A;
1254
1291
  try {
1255
- const P = await D(b);
1256
- if (P.status === "refused") return ne(P.reason);
1257
- const { target: B, name: M, stats: X } = P, J = Bn(M), U = at(X);
1258
- if (J.kind === "image") return { kind: "image", name: M, version: U };
1259
- if (J.kind === "media") return { kind: "media", name: M, mediaType: J.mediaType, version: U };
1260
- if (J.kind === "file") return { kind: "file", name: M, version: U };
1261
- N = await ft(B, ce.O_RDONLY | Tt | xt);
1262
- const q = await N.stat({ bigint: !0 });
1263
- if (!q.isFile() || q.ino !== X.ino || q.dev !== X.dev) return ne("forbidden");
1264
- if (J.kind === "markdown") {
1265
- if (q.size > BigInt(f)) return ne("too-large");
1266
- const Y = await ct(N, f + 1);
1267
- if (Y.length > f) return ne("too-large");
1268
- const de = await a(new TextDecoder("utf-8").decode(Y), T);
1269
- return { kind: "markdown", name: M, htmlContent: de.htmlContent, headings: de.headings };
1292
+ const P = await H(b);
1293
+ if (P.status === "refused") return te(P.reason);
1294
+ const { target: B, name: I, stats: X } = P, W = Qn(I), U = lt(X);
1295
+ if (W.kind === "image") return { kind: "image", name: I, version: U };
1296
+ if (W.kind === "media") return { kind: "media", name: I, mediaType: W.mediaType, version: U };
1297
+ if (W.kind === "file") return { kind: "file", name: I, version: U };
1298
+ A = await ht(B, ue.O_RDONLY | _t | Rt);
1299
+ const re = await A.stat({ bigint: !0 });
1300
+ if (!re.isFile() || re.ino !== X.ino || re.dev !== X.dev) return te("forbidden");
1301
+ if (W.kind === "markdown") {
1302
+ if (re.size > BigInt(p)) return te("too-large");
1303
+ const Q = await ft(A, p + 1);
1304
+ if (Q.length > p) return te("too-large");
1305
+ const pe = await a(new TextDecoder("utf-8").decode(Q), T);
1306
+ return { kind: "markdown", name: I, htmlContent: pe.htmlContent, headings: pe.headings };
1270
1307
  }
1271
- const L = await ct(N, w);
1272
- if (L.includes(0)) return { kind: "file", name: M, version: U };
1273
- const W = q.size > BigInt(w), Z = new TextDecoder("utf-8").decode(L, { stream: W });
1274
- return { kind: "text", name: M, text: Z, truncated: W, version: U };
1308
+ const z = await ft(A, h);
1309
+ if (z.includes(0)) return { kind: "file", name: I, version: U };
1310
+ const K = re.size > BigInt(h), V = new TextDecoder("utf-8").decode(z, { stream: K });
1311
+ return { kind: "text", name: I, text: V, truncated: K, version: U };
1275
1312
  } catch (P) {
1276
- const B = Ae(P);
1313
+ const B = Ne(P);
1277
1314
  if (B === null) throw P;
1278
- return ne(B);
1315
+ return te(B);
1279
1316
  } finally {
1280
- await N?.close();
1317
+ await A?.close();
1281
1318
  }
1282
- }, u = async (g, T, b) => {
1283
- let N;
1319
+ }, d = async (w, T, b) => {
1320
+ let A;
1284
1321
  try {
1285
- N = await D(b);
1322
+ A = await H(b);
1286
1323
  } catch (U) {
1287
- throw Ot(U);
1324
+ throw Nt(U);
1288
1325
  }
1289
- if (N.status === "refused") throw new Ee(N.reason);
1290
- const { target: P, name: B, stats: M } = N, X = St.get(kt(B)), J = X === void 0 ? "" : X.contentType;
1291
- return { name: B, contentType: J, size: Number(M.size), version: at(M), open: (U) => Xn(P, M, U, g.signal) };
1292
- }, h = async (g, T, b) => {
1293
- let N;
1326
+ if (A.status === "refused") throw new Ee(A.reason);
1327
+ const { target: P, name: B, stats: I } = A, X = Ot.get(At(B)), W = X === void 0 ? "" : X.contentType;
1328
+ return { name: B, contentType: W, size: Number(I.size), version: lt(I), open: (U) => to(P, I, U, w.signal) };
1329
+ }, E = async (w, T, b) => {
1330
+ let A;
1294
1331
  try {
1295
- N = await D(b);
1296
- } catch (M) {
1297
- if (Ae(M) !== null) return null;
1298
- throw M;
1332
+ A = await H(b);
1333
+ } catch (I) {
1334
+ if (Ne(I) !== null) return null;
1335
+ throw I;
1299
1336
  }
1300
- if (N.status === "refused") return null;
1301
- const P = b.slice(l.length).split("/");
1302
- if (P.some((M) => y.deniesName(M))) return null;
1337
+ if (A.status === "refused") return null;
1338
+ const P = b.slice(f.length).split("/");
1339
+ if (P.some((I) => y.deniesName(I))) return null;
1303
1340
  const B = P.slice(0, -1);
1304
- return B.map((M, X) => `${l}${B.slice(0, X + 1).join("/")}`);
1341
+ return B.map((I, X) => `${f}${B.slice(0, X + 1).join("/")}`);
1305
1342
  };
1306
1343
  return Object.freeze({
1307
1344
  id: t,
1308
1345
  label: r,
1309
- cacheScope: _,
1310
- boundary: Object.freeze({ contains: (g) => g.startsWith(l) }),
1311
- tree: A,
1312
- ancestors: h,
1313
- document: C,
1314
- asset: u
1346
+ cacheScope: R,
1347
+ boundary: Object.freeze({ contains: (w) => w.startsWith(f) }),
1348
+ tree: N,
1349
+ ancestors: E,
1350
+ document: j,
1351
+ asset: d
1315
1352
  });
1316
1353
  };
1317
1354
  export {
1318
- mo as DEFAULT_DENIED_PATH_SEGMENTS,
1355
+ Oo as DEFAULT_DENIED_PATH_SEGMENTS,
1319
1356
  Ee as ExplorerError,
1320
- po as MAX_DOCUMENT_PATH_LENGTH,
1321
- io as anonymousAccess,
1322
- uo as createFileSystemSource,
1323
- co as createMarkdownExplorer,
1324
- te as isAcceptableDocumentPath,
1325
- wo as isDeniedPath
1357
+ _o as MAX_DOCUMENT_PATH_LENGTH,
1358
+ bo as anonymousAccess,
1359
+ To as createFileSystemSource,
1360
+ So as createMarkdownExplorer,
1361
+ ee as isAcceptableDocumentPath,
1362
+ Ro as isDeniedPath
1326
1363
  };