@aiquants/markdown-explorer 0.5.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 (38) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +10 -2
  3. package/dist/{ExplorerSplit-CWcK1E4I.js → ExplorerSplit-CN5TvRj6.js} +2 -2
  4. package/dist/{ExplorerSplit-ajN3GSdA.cjs → ExplorerSplit-CUIbSLQm.cjs} +1 -1
  5. package/dist/{MultiLayout-DvkcdO9c.cjs → MultiLayout-BDcQSpa6.cjs} +1 -1
  6. package/dist/{MultiLayout-BtWtCzJV.js → MultiLayout-hPmV-bae.js} +4 -4
  7. package/dist/{NativeScrollBar-DbzyQ85y.cjs → NativeScrollBar-CHEQgaVx.cjs} +1 -1
  8. package/dist/{NativeScrollBar-apXjIKRW.js → NativeScrollBar-DYEv2GLV.js} +1 -1
  9. package/dist/{TreeLayout-rwhJfLmU.cjs → TreeLayout-BDaIyoGT.cjs} +1 -1
  10. package/dist/{TreeLayout-BcHsv9G8.js → TreeLayout-CqzxLpoM.js} +3 -3
  11. package/dist/core/contracts.d.cts +10 -7
  12. package/dist/core/contracts.d.ts +10 -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-Btg4w3vO.js → dataRoute-Ce6EIuu4.js} +41 -40
  17. package/dist/index-B3nShkkt.cjs +3 -0
  18. package/dist/{index-CIZw73j9.js → index-gJp1iXTc.js} +987 -903
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.js +5 -5
  21. package/dist/{location-c1zdeySY.js → location-CtM94G0O.js} +1 -1
  22. package/dist/{location-CSIhx-L4.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 +670 -641
  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/package.json +4 -3
  37. package/dist/dataRoute-DHpu0fg2.cjs +0 -1
  38. package/dist/index-Cie6WPiM.cjs +0 -3
package/dist/server.js CHANGED
@@ -1,20 +1,21 @@
1
- import { b as lt, c as It, f as _e, d as vt, g as Mt, h as Pt, j as $t, E as jt, i as te, k as Lt, l as zt, r as dt, m as Dt, n as Ct, o as ft, p as Ht, q as Bt, s as fe, t as oe, e as Ft } from "./dataRoute-Btg4w3vO.js";
2
- import { D as ho, M as go, u as yo } from "./dataRoute-Btg4w3vO.js";
3
- import { createHash as Ut, createHmac as Jt } from "node:crypto";
4
- import { createLinkCardHandler as Xt } from "@aiquants/markdown/server";
5
- import { data as Le, redirect as Gt } from "react-router";
6
- import { w as Wt, d as Yt, r as Kt, i as Vt, a as Zt, p as Qt, b as qt, f as er, N as tr } from "./location-c1zdeySY.js";
7
- import { existsSync as rr, statSync as nr, realpathSync as or, constants as ue } from "node:fs";
8
- import { extname as sr, isAbsolute as ze, relative as De, sep as Ce, join as ar, resolve as ir } 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 cr } from "node:worker_threads";
11
- import { open as mt, lstat as ur, realpath as lr, readdir as dr } from "node:fs/promises";
12
- import { Readable as fr } from "node:stream";
13
- const He = Object.freeze({ kind: "anonymous" }), lo = Object.freeze({
14
- authenticate: async () => ({ status: "signed-in", principal: He }),
15
- principalKey: () => He.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
- }), mr = "application/octet-stream", pt = "application/pdf", pr = /* @__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 He = Object.freeze({ kind: "anonymous" }), lo = Object.freeze({
40
41
  "video/webm",
41
42
  "video/ogg",
42
43
  "video/quicktime",
43
- pt
44
- ]), wt = "default-src 'none'; media-src 'self'; style-src 'unsafe-inline'", wr = `${wt}; sandbox`, hr = `${wt}; sandbox allow-same-origin`, Be = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u, gr = /^[\t\n\r ]+|[\t\n\r ]+$/gu, Ne = /^[\t ]+|[\t ]+$/gu, yr = (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,65 +54,65 @@ const He = Object.freeze({ kind: "anonymous" }), lo = 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
- }, Er = (e) => {
60
- const t = e.replace(gr, ""), r = t.indexOf("/");
60
+ }, Or = (e) => {
61
+ const t = e.replace(xr, ""), r = t.indexOf("/");
61
62
  if (r < 0) return null;
62
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, "");
63
- return Be.test(n) && Be.test(s) ? `${n}/${s}`.toLowerCase() : null;
64
- }, br = (e) => {
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 yr(e)) {
67
- const n = Er(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
- }, Sr = /['()*]/gu, Tr = (e) => encodeURIComponent(e).replace(Sr, (t) => `%${t.charCodeAt(0).toString(16).toUpperCase()}`), xr = 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
- }), kr = (e, t) => {
75
- const r = br(e), n = r !== null && pr.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 ? mr : 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''${Tr(t)}`,
82
- ...r === pt ? {} : { "Content-Security-Policy": a ? hr : wr },
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
- }, Or = /^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu, me = Object.freeze({ kind: "whole" }), Fe = Object.freeze({ kind: "unsatisfiable" }), Rr = (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 s = Or.exec(n);
92
- if (s === null) return me;
93
- const [, c, f, E] = s;
94
- if (E !== void 0) {
95
- const w = Number(E);
96
- if (w === 0) return Fe;
97
- const O = Math.max(0, t - w);
98
- return { kind: "partial", range: { offset: O, length: t - 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;
95
+ if (y !== void 0) {
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(c), p = f === "" ? Number.POSITIVE_INFINITY : Number(f);
101
- return p < x ? me : x >= t ? Fe : { kind: "partial", range: { offset: x, length: Math.min(p, t - 1) - x + 1 } };
102
- }, Ue = "W/", _r = (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
- }, Je = (e) => e.startsWith(Ue) ? e.slice(Ue.length) : e, Nr = (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 = _r(e);
111
+ const r = Pr(e);
111
112
  if (r.length === 1 && r[0] === "*") return !0;
112
- const n = Je(t);
113
- return r.some((a) => Je(a) === n);
114
- }, Ar = (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({
@@ -127,21 +128,21 @@ const He = Object.freeze({ kind: "anonymous" }), lo = Object.freeze({
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
130
  const s = await a();
130
- return new Response(n === null ? s : Ar(s, n), { status: t, headers: r });
131
- }, Ir = (e, t) => {
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
- }, vr = async (e, t, r) => {
136
- const n = `"${t.version}"`, a = kr(t.contentType, t.name), s = new Headers(r);
137
- for (const [E, x] of Object.entries({ ...a.headers, ...xr, ETag: n })) s.set(E, x);
138
- if (Nr(e.headers.get("If-None-Match"), n)) return new Response(null, { status: 304, headers: s });
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 });
139
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
142
  return s.set("Content-Length", "0"), new Response(null, { status: 200, headers: s });
142
143
  s.set("Accept-Ranges", "bytes");
143
- const c = Rr(e.headers, t.size, n);
144
- if (c.kind === "unsatisfiable") return Ir(r, t.size);
144
+ const c = vr(e.headers, t.size, n);
145
+ if (c.kind === "unsatisfiable") return jr(r, t.size);
145
146
  if (c.kind === "whole") return Te(e, 200, s, t.size, () => t.open(null));
146
147
  const { range: f } = c;
147
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));
@@ -155,40 +156,57 @@ const He = Object.freeze({ kind: "anonymous" }), lo = Object.freeze({
155
156
  clearTimeout(c), clearTimeout(s);
156
157
  };
157
158
  n.then(
158
- (E) => {
159
- f(), a(E);
159
+ (y) => {
160
+ f(), a(y);
160
161
  },
161
162
  () => {
162
163
  f(), a(e.late);
163
164
  }
164
165
  );
165
166
  });
166
- }, Mr = Object.freeze({
167
+ }, Dr = Object.freeze({
167
168
  error: (e, t) => {
168
169
  console.error(e, t);
169
170
  }
170
- }), ht = /* @__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 (!lt(t)) throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${JSON.stringify(t)}`);
176
- if (r.code !== void 0 && !It(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, ht, { 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 Pr = (e) => e instanceof Error && Object.hasOwn(e, ht) && lt(e.reason), $r = (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), jr = (e, t) => Ie(e, `[markdown-explorer] ${t.operation} left out an entry`, t), Lr = (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) => Pr(e) ? _e(e.reason, e.code) : ($r(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
- }, gt = (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
212
  const a = (s) => {
@@ -206,9 +224,9 @@ const Pr = (e) => e instanceof Error && Object.hasOwn(e, ht) && lt(e.reason), $r
206
224
  const f = t === void 0 ? 0 : t.of(s, c);
207
225
  if (!(t !== void 0 && f > t.max)) {
208
226
  r.set(s, { value: c, weight: f }), n += f;
209
- for (const E of r.keys()) {
227
+ for (const y of r.keys()) {
210
228
  if (r.size <= e && (t === void 0 || n <= t.max)) break;
211
- a(E);
229
+ a(y);
212
230
  }
213
231
  }
214
232
  },
@@ -216,286 +234,286 @@ const Pr = (e) => e instanceof Error && Object.hasOwn(e, ht) && lt(e.reason), $r
216
234
  size: () => r.size,
217
235
  weight: () => n
218
236
  };
219
- }, yt = (e) => Math.max(1, e - 1), zr = 2147483647, We = Object.freeze({ status: "aborted" }), se = (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
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
- }, Dr = (e) => e !== null && typeof e == "object" && e.ready === !0 && !("id" in e), Cr = (e, t) => e !== null && typeof e == "object" && e.id === t && "output" in e, Hr = ({ url: e, size: t, deadlineMs: r, jobsPerScope: n, maxQueuedJobs: a, heapLimits: s }) => {
225
- ce("size", t, Number.MAX_SAFE_INTEGER), ce("deadline", r, zr), 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);
226
- const c = Object.freeze({ maxOldGenerationSizeMb: s.maxOldGenerationSizeMb, maxYoungGenerationSizeMb: s.maxYoungGenerationSizeMb }), f = /* @__PURE__ */ new Set(), E = [], x = /* @__PURE__ */ new Map(), p = /* @__PURE__ */ new Map(), w = yt(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 && (se(x, g.scope, -1), se(p, g.scope, -1), g.settle(h));
231
- }, M = (u) => {
232
- const [h] = E.splice(u, 1);
233
- h?.detach();
234
- }, R = () => {
235
- let u = -1, h = w, g = Number.POSITIVE_INFINITY;
236
- for (const [T, b] of E.entries()) {
237
- const N = x.get(b.scope) ?? 0, P = p.get(b.scope) ?? 0;
238
- (N < h || N === h && u >= 0 && P < g) && (u = T, h = N, g = P);
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;
254
+ for (const [T, b] of y.entries()) {
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
- f.has(u) && (f.delete(u), _(u, h), u.worker.terminate().catch(() => {
243
- }), H());
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
- }, C = () => {
256
- const u = { worker: new cr(e, { resourceLimits: c }), 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 && Dr(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 && H();
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 || !Cr(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(), H();
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
- }), f.add(u), u;
277
- }, H = () => {
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 = E[u];
280
- if (h === void 0) return;
281
- let g;
297
+ const d = _(), E = y[d];
298
+ if (E === void 0) return;
299
+ let w;
282
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 && f.size < t)
305
+ if (w === void 0 && f.size < t)
288
306
  try {
289
- g = C();
307
+ w = H();
290
308
  } catch (b) {
291
- M(u), se(p, 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
- M(u), se(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(We);
319
+ run: (d, { scope: E, signal: w }) => new Promise((T) => {
320
+ if (w.aborted) {
321
+ T(Ke);
304
322
  return;
305
323
  }
306
- if ((p.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
- E.push(b), se(p, h, 1), H();
314
- const N = E.indexOf(b);
315
- if (N < 0) return;
316
- if (E.length > a) {
317
- M(N), se(p, h, -1), T({ status: "refused", limit: "queue" });
331
+ y.push(b), ae(p, E, 1), j();
332
+ const A = y.indexOf(b);
333
+ if (A < 0) return;
334
+ if (y.length > a) {
335
+ v(A), ae(p, E, -1), T({ status: "refused", limit: "queue" });
318
336
  return;
319
337
  }
320
338
  const P = () => {
321
- const B = E.indexOf(b);
322
- B < 0 || (M(B), se(p, h, -1), T(We));
339
+ const B = y.indexOf(b);
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
346
  workers: () => f.size
329
347
  };
330
- }, ve = 1024 * 1024, Br = 3e4, Fr = 4 * ve, Ur = 64 * ve, Jr = 3, Xr = 2, Gr = (e, t) => e + yt(t) + Jr, Wr = 4, Yr = 32, Kr = 512, Vr = 64, Zr = 4096, Qr = 32, Ye = 4096, qr = 4, Et = ({ workerHeapMb: e, maxHtmlBytes: t }) => Math.floor(((e - Vr) * ve - t * Qr) / Zr), en = ({ maxHtmlBytes: e }) => e, tn = ({ maxHtmlBytes: e }) => qr * e, rn = 1024, nn = 2147483647, on = 64, sn = 2 ** 29, an = 1024 * 1024, cn = 64, Ke = Object.freeze({ status: "rejected", reason: "too-large", cause: null }), ke = Object.freeze({ status: "rejected", reason: "failed", cause: null }), ae = (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
- }, un = (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: s, workerHeapMb: c, jobsPerScope: f, maxQueuedJobs: E } = e ?? {}, x = ae("workers", r, Xr, on), p = ae("jobsPerScope", f, Gr(t, x), Number.MAX_SAFE_INTEGER), w = Object.freeze({
338
- workers: x,
339
- deadlineMs: ae("deadlineMs", n, Br, nn),
340
- maxHtmlBytes: ae("maxHtmlBytes", a, Fr, sn),
341
- cacheBytes: ae("cacheBytes", s, Ur, Number.MAX_SAFE_INTEGER),
342
- workerHeapMb: ae("workerHeapMb", c, Kr, an),
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),
343
361
  jobsPerScope: p,
344
- maxQueuedJobs: ae("maxQueuedJobs", E, Wr * p, Number.MAX_SAFE_INTEGER)
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 (Et(w) < Ye)
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(Ye)} 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
- }, ln = () => {
356
- const e = import.meta.url, t = new URL(`./sanitizeWorker${sr(Se(e))}`, e);
357
- if (!rr(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
- }, Ve = /* @__PURE__ */ new Map(), dn = (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 = Ve.get(r);
362
- return n === void 0 && (n = Hr({
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: Yr }
369
- }), Ve.set(r, n)), n;
370
- }, fn = (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
- }, mn = (e) => e instanceof Error && e.code === "ERR_WORKER_OUT_OF_MEMORY", pn = ({ iframeHosts: e, dataPath: t, options: r, pool: n }) => {
375
- const a = Object.freeze([...e]), s = Et(r), c = en(r), f = tn(r), E = gt(rn, {
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 : cn)
378
- }), x = /* @__PURE__ */ new Map(), p = /* @__PURE__ */ new Map(), w = (R) => {
379
- x.get(R.key) === R && x.delete(R.key);
380
- const k = p.get(R.hash);
381
- k?.delete(R), k?.size === 0 && p.delete(R.hash);
382
- }, O = async (R, k, j) => {
383
- const S = await n.run({ html: R, iframeHosts: a, dataPath: t, maxNodes: s, maxAttributeChars: c, maxSanitizedChars: f }, { 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 C = 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: ${C}`) }, 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" && mn(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 fn(A) ? A.status === "too-large" ? { outcome: Ke, 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 > f ? { 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(f)}`) }, 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 C = new Promise((h) => {
400
- A = h;
401
- }), H = { hash: k, key: j, outcome: C, answer: A, controller: new AbortController(), waiters: 0 };
402
- x.set(j, H);
403
- const u = p.get(k);
404
- return u === void 0 ? p.set(k, /* @__PURE__ */ new Set([H])) : u.add(H), O(R, S, H.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(H), H.answer(h), !g) return;
406
- const T = E.get(k), b = T ?? (h.status === "rejected" ? { ...h, cause: null } : h);
407
- T === void 0 && E.set(k, b);
408
- for (const N of p.get(k) ?? [])
409
- w(N), N.answer(b), N.controller.abort();
410
- }), H;
411
- }, M = (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(Ke);
422
- const S = Ut("sha256").update(R, "utf8").digest("base64"), A = E.get(S);
423
- if (A !== void 0) return Promise.resolve(A);
424
- if (j.aborted) return Promise.resolve(ke);
425
- const C = `${S}\0${k}`, H = x.get(C);
426
- return M(H === void 0 ? _(R, S, C, k) : H, 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" }) }))), wn = (e) => e.status === "ok" && e.entries.length > 0, hn = ({ ttlMs: e, maxEntries: t, maxBytes: r, now: n }) => {
429
- const a = gt(t, { max: r, of: (p, w) => 2 * w.tree.json.length }), s = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map(), f = (p, w) => {
430
- const O = new AbortController(), _ = { waiters: 0, superseded: !1, started: !1, loadTree: w }, M = c.get(p), R = (C, H) => {
431
- const u = be(C);
432
- return !(_.superseded || O.signal.aborted) && wn(C) && a.set(p, { tree: u, loadedAt: H }), u;
433
- }, j = (async () => {
434
- if (M !== void 0 && await M, O.signal.aborted) return Oe;
435
- const C = n();
436
- return _.started = !0, R(await _.loadTree(O.signal, C), C);
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
456
  s.get(p) === S && s.delete(p);
439
- }), S = { promise: j, controller: O, state: _ };
457
+ }), S = { promise: L, controller: x, state: R };
440
458
  s.set(p, S);
441
- const A = j.then(
459
+ const N = L.then(
442
460
  () => {
443
461
  },
444
462
  () => {
445
463
  }
446
464
  );
447
- return c.set(p, A), A.then(() => {
448
- c.get(p) === A && c.delete(p);
465
+ return c.set(p, N), N.then(() => {
466
+ c.get(p) === N && c.delete(p);
449
467
  }), S;
450
- }, E = (p, w, O) => {
451
- w.state.waiters += 1;
452
- const _ = () => {
453
- w.state.waiters -= 1, !(w.state.waiters > 0) && (s.get(p) === w && s.delete(p), 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 = (p) => {
476
+ }, k = (p) => {
459
477
  a.delete(p);
460
- const w = s.get(p);
461
- w?.state.started && (w.state.superseded = !0, s.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: (p, w, O) => {
465
- if (w.aborted) return Promise.resolve(Oe);
466
- const _ = a.get(p);
467
- if (_ !== void 0) {
468
- if (n() - _.loadedAt < e) return Promise.resolve(_.tree);
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);
469
487
  a.delete(p);
470
488
  }
471
- const M = s.get(p);
472
- return E(p, M === void 0 ? f(p, O) : M, w);
489
+ const v = s.get(p);
490
+ return y(p, v === void 0 ? f(p, x) : v, h);
473
491
  },
474
- refresh: (p, w, O) => {
475
- if (w.aborted) return Promise.resolve(Oe);
476
- x(p);
477
- const _ = s.get(p);
478
- return _ === void 0 ? E(p, f(p, O), w) : (_.state.loadTree = O, E(p, _, 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
- }, gn = (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
- }, yn = (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
- }, En = (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
515
  for (const s of e) {
498
- if (typeof s != "string" || !te(s)) throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");
516
+ if (typeof s != "string" || !ee(s)) throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");
499
517
  if (r.deniesPath(s)) throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");
500
518
  if (!n(s)) throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");
501
519
  if (s === t) throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");
@@ -503,44 +521,44 @@ const Pr = (e) => e instanceof Error && Object.hasOwn(e, ht) && lt(e.reason), $r
503
521
  a.add(s);
504
522
  }
505
523
  return Object.freeze([...a]);
506
- }, bn = (e, t, r, n, a) => {
507
- const s = /* @__PURE__ */ new Set(), c = (E) => {
508
- if (!Array.isArray(E)) return $("a source returned entries that are not an array");
509
- const x = [];
510
- for (const p of E) {
511
- const w = f(p);
512
- w !== null && x.push(w);
524
+ }, Nn = (e, t, r, n, a) => {
525
+ const s = /* @__PURE__ */ new Set(), c = (y) => {
526
+ if (!Array.isArray(y)) return $("a source returned entries that are not an array");
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
- }, f = (E) => {
516
- const x = yn(E);
517
- if (x !== null)
518
- return n(x), null;
519
- const p = Lt(E);
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);
520
538
  if (p !== null) return $(p);
521
- const w = E;
522
- if (s.has(w)) return $("a source returned entries that contain themselves");
523
- const { name: O, path: _, type: M, 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 };
528
- if (M === "file") return { ...S, type: M };
529
- if (j === !0)
530
- return r ? { ...S, type: M, lazy: !0, children: [] } : $("a lazy directory came from a source without a children function");
531
- if (k === void 0) return { ...S, type: M };
532
- s.add(w);
533
- const A = c(k);
534
- return s.delete(w), { ...S, type: M, children: A };
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: _ };
546
+ if (v === "file") return { ...S, type: v };
547
+ if (L === !0)
548
+ return r ? { ...S, type: v, lazy: !0, children: [] } : $("a lazy directory came from a source without a children function");
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
554
  return c(e);
537
- }, Sn = /^[\x21\x23-\x7E]{1,256}$/u, bt = (e) => typeof e == "string" && Sn.test(e), Tn = /* @__PURE__ */ new Set(["text", "image", "media", "file"]), xn = (e) => typeof e == "string" && Tn.has(e), kn = (e, t) => {
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
557
  const a = e, { kind: s } = a;
540
- if (xn(s)) {
558
+ if (vn(s)) {
541
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 (!bt(a.version)) return $(`a ${s} document needs a version of 1 to 256 visible ASCII characters other than '"'`);
561
+ if (!xt(a.version)) return $(`a ${s} document needs a version of 1 to 256 visible ASCII characters other than '"'`);
544
562
  const c = t(a.version);
545
563
  switch (s) {
546
564
  case "image":
@@ -548,369 +566,380 @@ const Pr = (e) => e instanceof Error && Object.hasOwn(e, ht) && lt(e.reason), $r
548
566
  return { kind: s, name: a.name, url: c };
549
567
  case "media": {
550
568
  const { mediaType: f } = a;
551
- return Pt(f) ? { kind: s, name: a.name, url: c, mediaType: f } : $(`unknown media type ${typeof f == "string" ? JSON.stringify(f.slice(0, 64)) : typeof f}`);
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
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 = $t(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
581
  const { reason: a, code: s } = n.failure;
564
- return { kind: "failure", failure: _e(a, s) };
582
+ return { kind: "failure", failure: Re(a, s) };
565
583
  }
566
584
  case "markdown":
567
- return n.headings.length > jt ? { kind: "failure", failure: _e("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 })) };
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
- }, On = (e) => {
587
+ }, qe = (e) => {
570
588
  if (e === null || typeof e != "object") return $("an asset file must be an object");
571
589
  const { name: t, contentType: r, size: n, version: a, open: s } = 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") : bt(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 '"'`);
573
- }, Rn = (e) => Array.isArray(e) ? e.map((t) => {
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
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 (!vt(n)) return $(`unknown notice tone ${typeof n == "string" ? JSON.stringify(n.slice(0, 64)) : typeof n}`);
595
+ if (!jt(n)) return $(`unknown notice tone ${typeof n == "string" ? JSON.stringify(n.slice(0, 64)) : typeof n}`);
578
596
  if (s !== void 0 && typeof s != "string") return $("a notice body must be a string");
579
- const E = { id: r, tone: n, title: a, ...s === void 0 ? {} : { body: s } };
580
- if (c === void 0) return E;
597
+ const y = { id: r, tone: n, title: a, ...s === void 0 ? {} : { body: s } };
598
+ if (c === void 0) return y;
581
599
  if (c === null || typeof c != "object") return $("a notice action must be an object");
582
- const { label: x, href: p } = c;
583
- return typeof x != "string" || !Mt(p, zt) ? $("a notice action needs a label and an http(s), mailto or relative href") : { ...E, action: { label: x, href: p } };
584
- }) : $("notices must be an array"), _n = 4e3, pe = Object.freeze({ ttlMs: 3e5, maxEntries: 64, maxBytes: 64 * 1024 * 1024 }), Ze = 32, St = "private, no-store", Nn = Object.freeze({
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": St,
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
- }), An = 22, In = 2147483647, Re = Object.freeze([]), vn = Object.freeze({ status: "ok", source: null, ancestors: null }), Qe = Object.freeze(["contains", "confirm"]), qe = Object.freeze({ readOnly: !1 }), Mn = Object.freeze({ readOnly: !0 }), X = (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
- }, Pn = (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 Kt(e);
600
- }, et = (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
- }, tt = (e) => e instanceof Response ? new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`) : e, $n = (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 < Ze) throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(Ze)} 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
- }, jn = (e, t) => {
611
- if (!er(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 (!Qe.includes(r)) throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${Qe.join(", ")}`);
614
- X(`${e}.boundary.contains`, t.contains, !1), X(`${e}.boundary.confirm`, t.confirm, !0);
615
- }, Ln = (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: s, label: c, boundary: f, tree: E, children: x, ancestors: p, cacheScope: w } = a;
623
- if (!Vt(s))
640
+ const { id: s, label: c, boundary: f, tree: y, children: k, ancestors: p, cacheScope: h } = a;
641
+ if (!rr(s))
624
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}`);
625
- const O = `source ${JSON.stringify(s)}`;
643
+ const x = `source ${JSON.stringify(s)}`;
626
644
  if (r.has(s)) throw new RangeError(`[markdown-explorer] source ids must be unique; ${JSON.stringify(s)} repeats at sources[${String(n)}]`);
627
- if (r.add(s), typeof c != "string" && typeof c != "function") throw new TypeError(`[markdown-explorer] ${O}.label must be a string or a function`);
628
- if (typeof c == "string" && c.trim() === "") throw new RangeError(`[markdown-explorer] ${O}.label must not be blank`);
629
- if (jn(O, f), X(`${O}.tree`, E, !1), X(`${O}.children`, x, !0), X(`${O}.ancestors`, p, !0), w !== void 0 && w !== "principal" && w !== "shared") throw new RangeError(`[markdown-explorer] ${O}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(w)}`);
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
- }, zn = (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
- }, rt = (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
- }, nt = (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
- }, ot = (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 Jt("sha256", e).update(t, "utf8").digest("base64url").slice(0, An);
653
- }, Dn = (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
- }, ne = (e, t, r, n = {}) => {
674
+ }, oe = (e, t, r, n = {}) => {
657
675
  const a = new Headers(r);
658
- for (const [s, c] of Object.entries({ ...Nn, ...n })) a.set(s, c);
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) => ne(Ct[e.reason], JSON.stringify({ failure: e }), t, r), st = (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 : ne(405, JSON.stringify({ failure: { reason: "invalid" } }), void 0, { Allow: r.join(", ") });
663
- }, at = (e) => {
664
- if (e.headers.get(ft) !== Ht) return !1;
665
- const t = e.headers.get("Sec-Fetch-Site");
666
- return t === null || t === "same-origin";
667
- }, Cn = ({ 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
683
  for (const s of a)
670
684
  for (const [c, f] of s)
671
685
  c !== "set-cookie" && n.set(c, f);
672
686
  return n;
673
- }, fo = (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 = Pn(e.config), r = $n(e.scopeSecret);
676
- X("authenticate", e.authenticate, !1), X("principalKey", e.principalKey, !1), X("document", e.document, !1), X("asset", e.asset, !1), X("signedOutPage", e.signedOutPage, !1), X("forbiddenPage", e.forbiddenPage, !0), X("notices", e.notices, !0), X("onTreeRefreshed", e.onTreeRefreshed, !0);
677
- const n = Ln(e.sources), a = Wt(
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
693
  n.map((o) => o.id)
680
694
  ), s = e.logger;
681
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 c = e.logger === void 0 ? Mr : e.logger, f = dt(e.deny), E = e.deferredTimeoutMs === void 0 ? _n : ye("deferredTimeoutMs", e.deferredTimeoutMs, In), x = zn(e.treeCache), p = () => Date.now(), w = x === !1 ? gn(p) : hn({ ...x, now: p }), O = un(e.sanitizer, t.multiView.maxPanels), _ = pn({ iframeHosts: t.iframeHosts, dataPath: t.dataPath, options: O, pool: dn(ln(), O) }), M = new Map(n.map((o) => [o.id, o])), R = Yt(t), { authenticate: k, principalKey: j, signedOutPage: S, forbiddenPage: A, onTreeRefreshed: C } = e, H = (o, 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) => {
684
698
  if (typeof o.label == "string") return o.label;
685
- const i = o.label(d);
699
+ const i = o.label(l);
686
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`);
687
701
  return i;
688
- }, u = (o, d) => o.cacheScope === "shared" ? o.id : `${o.id}\0${d}`, h = (o, d) => {
689
- const i = (m) => ee(c, { operation: "boundary", sourceId: o.id, path: d, error: m });
690
- let l;
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
- l = o.boundary.contains(d);
706
+ u = o.boundary.contains(l);
693
707
  } catch (m) {
694
708
  return i(m), !1;
695
709
  }
696
- return typeof l == "boolean" ? l : (Xe(l, i), i(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(o.id)} must return a boolean; got ${typeof l}`)), !1);
697
- }, g = async (o, d, i) => {
698
- const { confirm: l } = o.boundary;
699
- if (l === void 0) return { status: "inside", readPath: i };
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 };
700
714
  let m;
701
715
  try {
702
- m = await l(d, i);
703
- } catch (Y) {
704
- return { status: "error", failure: q(Y, { operation: "boundary", sourceId: o.id, path: i }, d.signal, c) };
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 y = (Y) => (ee(c, { operation: "boundary", sourceId: o.id, path: i, error: new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} ${Y}`) }), { status: "outside" });
707
- if (m === null || typeof m != "object") return y(`must resolve to { inside, readPath? }; got ${m === null ? "null" : typeof m}`);
708
- const { inside: I, readPath: z } = m;
709
- return I === !1 ? { status: "outside" } : I !== !0 || typeof z != "string" ? y("must resolve to { inside: false } or { inside: true, readPath: string }") : !te(z) || f.deniesPath(z) ? (ee(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: z };
710
- }, T = async (o, d) => {
711
- const i = n.filter((m) => h(m, d));
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));
712
726
  if (i.length === 0) return { status: "error", failure: { reason: "forbidden" } };
713
- if (i.some((m) => m.boundary.confirm === void 0)) return { status: "inside", readPath: d };
714
- let l = null;
727
+ if (i.some((m) => m.boundary.confirm === void 0)) return { status: "inside", readPath: l };
728
+ let u = null;
715
729
  for (const m of i) {
716
- const y = await g(m, o, d);
717
- if (y.status === "inside") return y;
718
- y.status === "error" && l === null && (l = y.failure);
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: l === null ? { reason: "forbidden" } : l };
721
- }, b = (o, d, i) => {
722
- const l = ({ path: m, reason: y }) => jr(c, { operation: i.operation, sourceId: i.sourceId, path: m, error: new TypeError(`[markdown-explorer] an entry with ${y} 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: bn(o, f, d.children !== void 0, l, (m) => h(d, m)) };
738
+ return { status: "ok", entries: Nn(o, f, l.children !== void 0, u, (m) => w(l, m)) };
725
739
  } catch (m) {
726
- return ee(c, { ...i, error: m }), { status: "error", failure: { reason: "failed" } };
740
+ return ne(c, { ...i, error: m }), { status: "error", failure: { reason: "failed" } };
727
741
  }
728
- }, N = async (o, d, i) => {
729
- let l;
742
+ }, P = async (o, l, i) => {
743
+ let u;
730
744
  try {
731
- l = await o.tree(d);
732
- } catch (y) {
733
- return { status: "error", failure: q(y, { operation: "tree", sourceId: o.id }, d.signal, c) };
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 m = b(l, o, { operation: "tree", sourceId: o.id });
749
+ const m = A(u, o, { operation: "tree", sourceId: o.id });
736
750
  return m.status === "ok" ? { status: "ok", entries: m.entries, loadedAt: i } : m;
737
- }, P = (o, d, i, l) => (m, y) => N(o, { principal: d, request: i, signal: m, refresh: l }, y), B = (o, d, i, l, m) => w.load(u(o, i), m, P(o, d, l, !1)), v = (o, d, i, l) => w.refresh(u(o, i), l.signal, P(o, d, l, !0)), J = (o, d) => {
738
- if (C === void 0) return;
739
- const i = (l) => ee(c, { operation: "refresh", sourceId: o.id, error: l });
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(C(d), i);
742
- } catch (l) {
743
- i(l);
755
+ Ye(j(l), i);
756
+ } catch (u) {
757
+ i(u);
744
758
  }
745
- }, G = async (o, d, i, l) => {
746
- if (f.deniesPath(l) || !h(o, l)) return { status: "error", failure: { reason: "forbidden" } };
747
- const m = await g(o, i, l);
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);
748
762
  if (m.status === "outside") return { status: "error", failure: { reason: "forbidden" } };
749
763
  if (m.status === "error") return { status: "error", failure: m.failure };
750
- let y;
764
+ let g;
751
765
  try {
752
- y = await d(i, l, m.readPath);
753
- } catch (I) {
754
- return { status: "error", failure: q(I, { operation: "children", sourceId: o.id, path: l }, i.signal, c) };
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(y, o, { operation: "children", sourceId: o.id, path: l });
757
- }, U = async (o, d, i, l) => {
758
- const m = await g(o, i, l);
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);
759
773
  if (m.status === "outside") return { status: "ok", ancestors: null };
760
774
  if (m.status === "error") return { status: "error", failure: m.failure };
761
- let y;
775
+ let g;
762
776
  try {
763
- y = await d(i, l, m.readPath, { maxDepth: t.revealDocument.maxDepth });
764
- } catch (I) {
765
- return { status: "error", failure: q(I, { operation: "ancestors", sourceId: o.id, path: l }, i.signal, c) };
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) };
766
780
  }
767
- if (Array.isArray(y) && y.length > t.revealDocument.maxDepth) return { status: "ok", ancestors: null };
781
+ if (Array.isArray(g) && g.length > t.revealDocument.maxDepth) return { status: "ok", ancestors: null };
768
782
  try {
769
- return { status: "ok", ancestors: En(y, l, f, (I) => h(o, I)) };
770
- } catch (I) {
771
- return ee(c, { operation: "ancestors", sourceId: o.id, path: l, 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" } };
772
786
  }
773
- }, re = async (o, d, i, l) => f.deniesPath(l) ? { status: "error", failure: { reason: "forbidden" } } : h(o, l) ? U(o, d, i, l) : { status: "ok", ancestors: null }, L = async (o, d, i) => {
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) => {
774
788
  if (f.deniesPath(i)) return { status: "error", failure: { reason: "forbidden" } };
775
- for (const l of [o, ...n.filter((m) => m !== o)]) {
776
- if (d.signal.aborted) break;
777
- const m = l.ancestors;
778
- if (m === void 0 || !h(l, i)) continue;
779
- const y = await U(l, m, d, i);
780
- if (y.status === "ok" && y.ancestors !== null) return { status: "ok", source: l.id, ancestors: y.ancestors };
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 };
781
795
  }
782
- return vn;
783
- }, W = async (o, d, i) => {
784
- if (f.deniesPath(i)) return oe("forbidden");
785
- const l = await T(o, i);
786
- if (l.status === "error") return { kind: "failure", failure: l.failure };
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 };
787
801
  let m;
788
802
  try {
789
- m = await e.document(o, i, l.readPath);
790
- } catch (z) {
791
- return { kind: "failure", failure: q(z, { operation: "document", path: i }, o.signal, c) };
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) };
792
806
  }
793
- let y;
807
+ let g;
794
808
  try {
795
- y = kn(m, (z) => Ft(t.dataPath, i, z));
796
- } catch (z) {
797
- return ee(c, { operation: "document", path: i, error: z }), oe("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");
798
812
  }
799
- if (y.kind !== "unsanitized-markdown") return y;
800
- const I = await _(y.html, { scope: d, signal: o.signal });
801
- return I.status === "sanitized" ? { kind: "markdown", name: y.name, htmlContent: I.html, headings: y.headings } : (I.cause !== null && ee(c, { operation: "document", path: i, error: I.cause }), oe(I.reason));
802
- }, V = async (o) => {
803
- 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;
804
818
  try {
805
- return Rn(await e.notices(o));
806
- } catch (d) {
807
- return q(d, { operation: "notices" }, o.signal, c), Re;
819
+ return $n(await e.notices(o));
820
+ } catch (l) {
821
+ return Z(l, { operation: "notices" }, o.signal, c), _e;
808
822
  }
809
- }, Z = async (o, d, i) => {
810
- const l = we(d, fe.path);
811
- if (l === null || !te(l)) return F({ reason: "invalid" }, i);
812
- if (f.deniesPath(l))
813
- return Lr(c, { operation: "asset", path: l }), F({ reason: "forbidden" }, i);
814
- const m = await T(o, l);
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);
815
829
  if (m.status === "error") return F(m.failure, i);
816
830
  try {
817
- const y = On(await e.asset(o, l, m.readPath));
818
- return await vr(o.request, y, i);
819
- } catch (y) {
820
- return F(q(y, { operation: "asset", path: l }, o.signal, c), i);
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);
835
+ }
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 };
841
+ try {
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) };
821
846
  }
822
- }, de = async ({ request: o, url: d, params: i }) => {
823
- const l = rt(await k(o, qe)), m = et(l.headers);
824
- if (m.set("Cache-Control", St), l.status === "signed-out") throw nt("signedOutPage", S(o, m));
825
- if (l.status === "forbidden") throw A === void 0 ? Le(null, { status: 403, headers: m }) : nt("forbiddenPage", A(o, m));
826
- const y = Zt(a, i["*"], d.searchParams);
827
- if (y.kind === "redirect") throw Gt(y.href, { headers: m });
828
- const { location: I } = y, { principal: z } = l, Y = ot(r, j(z)), ie = M.get(I.source);
829
- if (ie === void 0) throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(I.source)}`);
830
- const le = { signal: o.signal, timeoutMs: E, late: null, handOverMs: E }, Q = {
831
- scope: Y,
832
- sources: n.map((D) => ({ id: D.id, label: H(D, z) })),
833
- settings: Qt(qt(o.headers.get("Cookie"), t.settingsCookie), R),
834
- tree: I.view === "single" ? null : {
835
- sourceId: I.source,
836
- result: xe(le, (D) => B(ie, z, Y, o, D).then((K) => K.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))
837
862
  },
838
- documents: Dn(I).map((D) => ({ path: D, document: xe(le, (K) => W({ principal: z, request: o, signal: K, refresh: !1 }, Y, D)) })),
839
- notices: xe({ signal: o.signal, timeoutMs: E, late: Re, handOverMs: 0 }, (D) => V({ principal: z, request: o, signal: D, 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 }))
840
865
  };
841
- return Le(Q, { headers: m });
842
- }, Me = async (o, d) => {
843
- const i = rt(await k(o, d));
844
- return { authentication: i, headers: et(i.headers) };
845
- }, _t = async (o, d, i) => {
846
- let l;
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;
847
872
  try {
848
- l = await Me(d, qe);
849
- } catch (K) {
850
- return F(q(tt(K), { operation: "authenticate" }, d.signal, c));
873
+ u = await ve(l, rt);
874
+ } catch (G) {
875
+ return F(Z(ot(G), { operation: "authenticate" }, l.signal, c));
851
876
  }
852
- const { authentication: m, headers: y } = l;
853
- if (m.status === "signed-out") return F({ reason: "unauthorized" }, y);
854
- if (m.status === "forbidden") return F({ reason: "forbidden" }, y);
855
- const { principal: I } = m;
856
- if (o === "asset") return Z({ principal: I, request: d, signal: d.signal, refresh: !1 }, i, y);
857
- const z = ot(r, j(I));
858
- y.set(Bt, z);
859
- const Y = { principal: I, request: d, signal: d.signal, refresh: !1 }, ie = () => F({ reason: "invalid" }, y);
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);
860
885
  if (o === "document") {
861
- const K = we(i, fe.path);
862
- if (K === null || !te(K)) return ie();
863
- const je = d.headers.has(ft);
864
- return je && !at(d) ? F({ reason: "forbidden" }, y) : ne(200, JSON.stringify(await W({ ...Y, refresh: je }, z, K)), y);
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);
890
+ }
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);
865
894
  }
866
- const le = we(i, fe.source), Q = we(i, fe.path);
867
- if (le === null || (o === "children" || o === "ancestors" || o === "reveal") && (Q === null || !te(Q))) return ie();
868
- const D = M.get(le);
869
- if (D === void 0) return F({ reason: "not-found" }, y);
870
- if (o === "tree") return ne(200, (await B(D, I, z, d, d.signal)).json, y);
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);
871
900
  if (o === "refresh") {
872
- const K = await v(D, I, z, d);
873
- return d.signal.aborted || J(D, u(D, z)), ne(200, K.json, y);
901
+ const G = await X(C, M, D, l);
902
+ return l.signal.aborted || W(C, E(C, D)), oe(200, G.json, g);
874
903
  }
875
- return o === "ancestors" ? D.ancestors === void 0 || Q === null ? F({ reason: "not-found" }, y) : ne(200, JSON.stringify(await re(D, D.ancestors, Y, Q)), y) : o === "reveal" ? Q === null ? ie() : ne(200, JSON.stringify(await L(D, Y, Q)), y) : D.children === void 0 || Q === null ? F({ reason: "not-found" }, y) : ne(200, JSON.stringify(await G(D, D.children, Y, Q)), y);
876
- }, Nt = async (o) => {
877
- const { authentication: d, headers: i } = await Me(o, Mn);
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);
878
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)");
879
- return d.status === "signed-in";
880
- }, Pe = t.embeds.linkCardEndpoint === null ? null : Xt({ authorize: Nt }), At = async (o, d) => {
908
+ return l.status === "signed-in";
909
+ }, Pe = t.embeds.linkCardEndpoint === null ? null : Kt({ authorize: Pt }), $t = async (o, l) => {
881
910
  try {
882
- return await o(d);
911
+ return await o(l);
883
912
  } catch (i) {
884
- return F(q(tt(i), { operation: "authenticate" }, d.signal, c));
913
+ return F(Z(ot(i), { operation: "authenticate" }, l.signal, c));
885
914
  }
886
- }, $e = async (o, d, i) => {
915
+ }, $e = async (o, l, i) => {
887
916
  if (new URL(o.url).pathname.endsWith(".data")) return F({ reason: "not-found" });
888
- if (!Dt(i)) return F({ reason: "not-found" });
917
+ if (!Ut(i)) return F({ reason: "not-found" });
889
918
  if (i === "link-card") {
890
919
  if (Pe === null) return F({ reason: "not-found" });
891
- const m = st(o, i);
892
- return m !== null ? m : At(Pe, o);
920
+ const m = ct(o, i);
921
+ return m !== null ? m : $t(Pe, o);
893
922
  }
894
- const l = st(o, i);
895
- if (l !== null) return l;
896
- if (i === "refresh" && !at(o)) 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" });
897
926
  try {
898
- return await _t(i, o, d.searchParams);
927
+ return await vt(i, o, l.searchParams);
899
928
  } catch (m) {
900
- return F(q(m, { operation: i }, o.signal, c));
929
+ return F(Z(m, { operation: i }, o.signal, c));
901
930
  }
902
931
  };
903
932
  return Object.freeze({
904
- loader: de,
905
- headers: Cn,
906
- dataLoader: ({ request: o, url: d, params: i }) => $e(o, d, i["*"]),
907
- dataAction: ({ request: o, url: d, params: i }) => $e(o, d, i["*"]),
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["*"]),
908
937
  forgetTree: (o) => {
909
938
  if (typeof o != "string") throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof o}`);
910
- w.forget(o);
939
+ x.forget(o);
911
940
  }
912
941
  });
913
- }, he = Object.freeze({ maxEntries: 2e4, maxDocumentBytes: 2 * 1024 * 1024, textPreviewBytes: 8 * 1024, walkConcurrency: 8 }), Hn = /* @__PURE__ */ new Set(["md", "markdown", "mdx"]), Tt = 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([
914
943
  ...[
915
944
  ["png", "image/png"],
916
945
  ["jpg", "image/jpeg"],
@@ -945,7 +974,7 @@ const Pr = (e) => e instanceof Error && Object.hasOwn(e, ht) && lt(e.reason), $r
945
974
  ["wma", "audio/x-ms-wma"]
946
975
  ].map(([e, t]) => [e, { kind: "media", mediaType: "audio", contentType: t }]),
947
976
  ["pdf", { kind: "media", mediaType: "pdf", contentType: "application/pdf" }]
948
- ]), Bn = /* @__PURE__ */ new Set([
977
+ ]), Kn = /* @__PURE__ */ new Set([
949
978
  "txt",
950
979
  "text",
951
980
  "log",
@@ -1070,7 +1099,7 @@ const Pr = (e) => e instanceof Error && Object.hasOwn(e, ht) && lt(e.reason), $r
1070
1099
  "eslintrc",
1071
1100
  "babelrc",
1072
1101
  "mailmap"
1073
- ]), Fn = /* @__PURE__ */ new Set([
1102
+ ]), Vn = /* @__PURE__ */ new Set([
1074
1103
  "readme",
1075
1104
  "license",
1076
1105
  "licence",
@@ -1091,17 +1120,17 @@ const Pr = (e) => e instanceof Error && Object.hasOwn(e, ht) && lt(e.reason), $r
1091
1120
  "jenkinsfile",
1092
1121
  "brewfile",
1093
1122
  "codeowners"
1094
- ]), xt = typeof ue.O_NOFOLLOW == "number" ? ue.O_NOFOLLOW : 0, kt = typeof ue.O_NONBLOCK == "number" ? ue.O_NONBLOCK : 0, it = (e) => `${e.size}-${e.mtimeNs}`, Un = (e) => e !== "" && e !== "." && e !== ".." && !e.includes(":") && !e.endsWith(".") && !e.endsWith(" "), ct = (e) => te(e) && e === e.normalize("NFC") && e.split("/").every(Un), Ot = (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) => {
1095
1124
  const t = e.toLowerCase(), r = t.lastIndexOf(".");
1096
1125
  return r < 0 ? "" : t.slice(r + 1);
1097
- }, Jn = (e) => {
1098
- const t = Ot(e);
1099
- if (Hn.has(t)) return { kind: "markdown" };
1100
- const r = Tt.get(t);
1126
+ }, Qn = (e) => {
1127
+ const t = At(e);
1128
+ if (Wn.has(t)) return { kind: "markdown" };
1129
+ const r = Ot.get(t);
1101
1130
  if (r !== void 0) return r.kind === "image" ? { kind: "image" } : { kind: "media", mediaType: r.mediaType };
1102
1131
  const n = e.toLowerCase();
1103
- return Bn.has(t) || !n.includes(".") && Fn.has(n) ? { kind: "text" } : { kind: "file" };
1104
- }, Ae = (e) => {
1132
+ return Kn.has(t) || !n.includes(".") && Vn.has(n) ? { kind: "text" } : { kind: "file" };
1133
+ }, Ne = (e) => {
1105
1134
  switch (typeof e == "object" && e !== null ? e.code : void 0) {
1106
1135
  case "ENOENT":
1107
1136
  case "ENOTDIR":
@@ -1117,34 +1146,34 @@ const Pr = (e) => e instanceof Error && Object.hasOwn(e, ht) && lt(e.reason), $r
1117
1146
  default:
1118
1147
  return null;
1119
1148
  }
1120
- }, Rt = (e) => {
1121
- const t = Ae(e);
1149
+ }, Nt = (e) => {
1150
+ const t = Ne(e);
1122
1151
  return t === null ? e : new Ee(t);
1123
- }, Xn = (e) => {
1152
+ }, qn = (e) => {
1124
1153
  const t = typeof e == "object" && e !== null ? e.code : void 0;
1125
1154
  return t === "EACCES" || t === "EPERM" || t === "ENOENT" || t === "ENOTDIR";
1126
- }, ut = async (e, t) => {
1155
+ }, ft = async (e, t) => {
1127
1156
  const r = [];
1128
1157
  for await (const n of e.createReadStream({ start: 0, end: t - 1, autoClose: !1 }))
1129
1158
  r.push(n);
1130
1159
  return Buffer.concat(r);
1131
- }, Gn = (e, t) => e !== null ? { start: e.offset, end: e.offset + e.length - 1 } : t === 0n ? {} : { start: 0, end: Number(t) - 1 }, Wn = 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) => {
1132
1161
  let a;
1133
1162
  try {
1134
- a = await mt(e, ue.O_RDONLY | xt | kt);
1135
- const E = await a.stat({ bigint: !0 });
1136
- if (!E.isFile() || E.ino !== t.ino || E.dev !== t.dev || E.size !== t.size || E.mtimeNs !== t.mtimeNs) throw new Ee("not-found");
1137
- } catch (E) {
1138
- throw await a?.close(), Rt(E);
1163
+ a = await ht(e, ue.O_RDONLY | _t | Rt);
1164
+ const y = await a.stat({ bigint: !0 });
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");
1166
+ } catch (y) {
1167
+ throw await a?.close(), Nt(y);
1139
1168
  }
1140
- const s = a.createReadStream(Gn(r, t.size)), c = fr.toWeb(s), f = () => {
1169
+ const s = a.createReadStream(eo(r, t.size)), c = yr.toWeb(s), f = () => {
1141
1170
  s.destroy(n.reason);
1142
1171
  };
1143
1172
  return n.aborted ? f() : n.addEventListener("abort", f, { once: !0 }), c;
1144
- }, Yn = (e, t) => {
1145
- const r = tr.compare(e, t);
1173
+ }, ro = (e, t) => {
1174
+ const r = ir.compare(e, t);
1146
1175
  return r !== 0 ? r : e === t ? 0 : e < t ? -1 : 1;
1147
- }, Kn = (e) => {
1176
+ }, no = (e) => {
1148
1177
  let t = 0;
1149
1178
  const r = [];
1150
1179
  return async (n) => {
@@ -1156,179 +1185,179 @@ const Pr = (e) => e instanceof Error && Object.hasOwn(e, ht) && lt(e.reason), $r
1156
1185
  a === void 0 ? t -= 1 : a();
1157
1186
  }
1158
1187
  };
1159
- }, Vn = (e, t) => {
1188
+ }, oo = (e, t) => {
1160
1189
  if (e.isSymbolicLink()) return "symbolic-link";
1161
1190
  if (!(e.isDirectory() || e.isFile())) return "special-file";
1162
1191
  const { name: r } = e;
1163
- 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";
1164
- }, Zn = /* @__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) => {
1165
1194
  if (t === void 0) return r;
1166
1195
  if (typeof t != "number" || !Number.isSafeInteger(t) || t <= 0) throw new RangeError(`[markdown-explorer] ${e} must be a positive integer; got ${String(t)}`);
1167
1196
  return t;
1168
- }, mo = (e) => {
1197
+ }, To = (e) => {
1169
1198
  if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] createFileSystemSource needs an options object");
1170
- for (const g of Object.keys(e))
1171
- if (!Zn.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)}`);
1172
1201
  const { id: t, label: r, root: n, parse: a } = e;
1173
1202
  if (typeof t != "string" || t === "") throw new TypeError("[markdown-explorer] a file-system source needs a non-empty id");
1174
1203
  if (typeof r != "string" || r.trim() === "") throw new TypeError("[markdown-explorer] a file-system source needs a non-blank label");
1175
1204
  if (typeof a != "function") throw new TypeError("[markdown-explorer] a file-system source needs a parse function");
1176
- if (typeof n != "string" || !ze(n)) throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);
1205
+ if (typeof n != "string" || !De(n)) throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);
1177
1206
  let s;
1178
1207
  try {
1179
- s = nr(n).isDirectory();
1180
- } catch (g) {
1181
- 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 });
1182
1211
  }
1183
1212
  if (!s) throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);
1184
- const c = or(n), f = e.pathPrefix;
1213
+ const c = lr(n), f = e.pathPrefix;
1185
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 "/"');
1186
- if (f !== "" && !(f.endsWith("/") && ct(f.slice(0, -1))))
1215
+ if (f !== "" && !(f.endsWith("/") && dt(f.slice(0, -1))))
1187
1216
  throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(f)}`);
1188
- const E = dt(e.deny), x = ge("maxEntries", e.maxEntries, he.maxEntries), p = 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;
1189
- if (_ !== "principal" && _ !== "shared") throw new RangeError(`[markdown-explorer] cacheScope must be "principal" or "shared"; got ${JSON.stringify(_)}`);
1190
- const M = e.reportSkipped;
1191
- if (M !== void 0 && typeof M != "function") throw new TypeError("[markdown-explorer] reportSkipped must be a function");
1192
- const R = M === void 0 ? (g) => {
1193
- console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(g.sourceId)} does not list ${JSON.stringify(g.path)}: ${g.reason}`);
1194
- } : M, k = /* @__PURE__ */ new Set(), j = (g) => {
1195
- const T = ir(c, ...g.split("/")), b = De(c, T);
1196
- return b === "" || b === ".." || b.startsWith(`..${Ce}`) || ze(b) ? null : T;
1197
- }, S = (g, T) => {
1198
- const b = `${T}\0${g}`;
1199
- k.has(b) || k.size >= x || (k.add(b), R({ sourceId: t, path: g, reason: T }));
1200
- }, A = async ({ signal: g }) => {
1201
- g.throwIfAborted();
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)}`);
1219
+ const v = e.reportSkipped;
1220
+ if (v !== void 0 && typeof v != "function") throw new TypeError("[markdown-explorer] reportSkipped must be a function");
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();
1202
1231
  const T = new AbortController(), b = () => {
1203
- T.abort(g.reason);
1232
+ T.abort(w.reason);
1204
1233
  };
1205
- g.addEventListener("abort", b, { once: !0 });
1206
- const N = Kn(O);
1234
+ w.addEventListener("abort", b, { once: !0 });
1235
+ const A = no(x);
1207
1236
  let P = 0;
1208
- const B = async (v, J) => {
1209
- const G = await N(async () => {
1237
+ const B = async (I, X) => {
1238
+ const W = await A(async () => {
1210
1239
  T.signal.throwIfAborted();
1211
1240
  try {
1212
- return await dr(v, { withFileTypes: !0 });
1213
- } catch (L) {
1214
- if (J === "" || !Xn(L)) throw L;
1241
+ return await gr(I, { withFileTypes: !0 });
1242
+ } catch (z) {
1243
+ if (X === "" || !qn(z)) throw z;
1215
1244
  return null;
1216
1245
  }
1217
1246
  });
1218
- if (T.signal.throwIfAborted(), G === null)
1219
- return S(`${f}${J}`, "unreadable-directory"), null;
1247
+ if (T.signal.throwIfAborted(), W === null)
1248
+ return S(`${f}${X}`, "unreadable-directory"), null;
1220
1249
  const U = [];
1221
- for (const L of G) {
1222
- if (E.deniesName(L.name)) continue;
1223
- const W = J === "" ? L.name : `${J}/${L.name}`, V = `${f}${W}`, Z = Vn(L, V);
1224
- if (Z !== null) {
1225
- S(V, Z);
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);
1226
1255
  continue;
1227
1256
  }
1228
- U.push({ dirent: L, relativePath: W, path: V });
1257
+ U.push({ dirent: z, relativePath: K, path: V });
1229
1258
  }
1230
- if (P += U.length, P > x) throw new Ee("too-large");
1231
- return U.sort((L, W) => Yn(L.dirent.name, W.dirent.name)), (await Promise.all(
1232
- U.map(async ({ dirent: L, relativePath: W, path: V }) => {
1233
- if (!L.isDirectory()) return { name: L.name, path: V, type: "file" };
1234
- const Z = await B(ar(v, L.name), W);
1235
- return Z === null ? null : { name: L.name, path: V, type: "directory", children: Z };
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 };
1236
1265
  })
1237
- )).filter((L) => L !== null);
1266
+ )).filter((z) => z !== null);
1238
1267
  };
1239
1268
  try {
1240
- const v = await B(c, "");
1241
- if (v === null) throw new Error("[markdown-explorer] the source's root could not be listed");
1242
- return v;
1243
- } catch (v) {
1244
- throw T.abort(), v;
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;
1245
1274
  } finally {
1246
- g.removeEventListener("abort", b);
1275
+ w.removeEventListener("abort", b);
1247
1276
  }
1248
- }, C = async (g) => {
1249
- if (!g.startsWith(f)) return { status: "refused", reason: "not-found" };
1250
- const T = g.slice(f.length);
1251
- if (!ct(T)) return { status: "refused", reason: "invalid" };
1252
- if (E.deniesPath(T)) return { status: "refused", reason: "forbidden" };
1253
- const b = j(T);
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" };
1281
+ if (y.deniesPath(T)) return { status: "refused", reason: "forbidden" };
1282
+ const b = L(T);
1254
1283
  if (b === null) return { status: "refused", reason: "forbidden" };
1255
- const N = await ur(b, { bigint: !0 });
1256
- if (N.isSymbolicLink()) return { status: "refused", reason: "forbidden" };
1257
- if (!N.isFile()) return { status: "refused", reason: "unsupported" };
1258
- const P = await lr(b);
1259
- return P !== b || E.deniesPath(De(c, P).split(Ce).join("/")) ? { status: "refused", reason: "forbidden" } : { status: "file", target: b, name: T.slice(T.lastIndexOf("/") + 1), stats: N };
1260
- }, H = async (g, T, b) => {
1261
- 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;
1262
1291
  try {
1263
- const P = await C(b);
1264
- if (P.status === "refused") return oe(P.reason);
1265
- const { target: B, name: v, stats: J } = P, G = Jn(v), U = it(J);
1266
- if (G.kind === "image") return { kind: "image", name: v, version: U };
1267
- if (G.kind === "media") return { kind: "media", name: v, mediaType: G.mediaType, version: U };
1268
- if (G.kind === "file") return { kind: "file", name: v, version: U };
1269
- N = await mt(B, ue.O_RDONLY | xt | kt);
1270
- const re = await N.stat({ bigint: !0 });
1271
- if (!re.isFile() || re.ino !== J.ino || re.dev !== J.dev) return oe("forbidden");
1272
- if (G.kind === "markdown") {
1273
- if (re.size > BigInt(p)) return oe("too-large");
1274
- const Z = await ut(N, p + 1);
1275
- if (Z.length > p) return oe("too-large");
1276
- const de = await a(new TextDecoder("utf-8").decode(Z), T);
1277
- return { kind: "markdown", name: v, 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 };
1278
1307
  }
1279
- const L = await ut(N, w);
1280
- if (L.includes(0)) return { kind: "file", name: v, version: U };
1281
- const W = re.size > BigInt(w), V = new TextDecoder("utf-8").decode(L, { stream: W });
1282
- return { kind: "text", name: v, text: V, 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 };
1283
1312
  } catch (P) {
1284
- const B = Ae(P);
1313
+ const B = Ne(P);
1285
1314
  if (B === null) throw P;
1286
- return oe(B);
1315
+ return te(B);
1287
1316
  } finally {
1288
- await N?.close();
1317
+ await A?.close();
1289
1318
  }
1290
- }, u = async (g, T, b) => {
1291
- let N;
1319
+ }, d = async (w, T, b) => {
1320
+ let A;
1292
1321
  try {
1293
- N = await C(b);
1322
+ A = await H(b);
1294
1323
  } catch (U) {
1295
- throw Rt(U);
1324
+ throw Nt(U);
1296
1325
  }
1297
- if (N.status === "refused") throw new Ee(N.reason);
1298
- const { target: P, name: B, stats: v } = N, J = Tt.get(Ot(B)), G = J === void 0 ? "" : J.contentType;
1299
- return { name: B, contentType: G, size: Number(v.size), version: it(v), open: (U) => Wn(P, v, U, g.signal) };
1300
- }, h = async (g, T, b) => {
1301
- 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;
1302
1331
  try {
1303
- N = await C(b);
1304
- } catch (v) {
1305
- if (Ae(v) !== null) return null;
1306
- throw v;
1332
+ A = await H(b);
1333
+ } catch (I) {
1334
+ if (Ne(I) !== null) return null;
1335
+ throw I;
1307
1336
  }
1308
- if (N.status === "refused") return null;
1337
+ if (A.status === "refused") return null;
1309
1338
  const P = b.slice(f.length).split("/");
1310
- if (P.some((v) => E.deniesName(v))) return null;
1339
+ if (P.some((I) => y.deniesName(I))) return null;
1311
1340
  const B = P.slice(0, -1);
1312
- return B.map((v, J) => `${f}${B.slice(0, J + 1).join("/")}`);
1341
+ return B.map((I, X) => `${f}${B.slice(0, X + 1).join("/")}`);
1313
1342
  };
1314
1343
  return Object.freeze({
1315
1344
  id: t,
1316
1345
  label: r,
1317
- cacheScope: _,
1318
- boundary: Object.freeze({ contains: (g) => g.startsWith(f) }),
1319
- tree: A,
1320
- ancestors: h,
1321
- document: H,
1322
- 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
1323
1352
  });
1324
1353
  };
1325
1354
  export {
1326
- ho as DEFAULT_DENIED_PATH_SEGMENTS,
1355
+ Oo as DEFAULT_DENIED_PATH_SEGMENTS,
1327
1356
  Ee as ExplorerError,
1328
- go as MAX_DOCUMENT_PATH_LENGTH,
1329
- lo as anonymousAccess,
1330
- mo as createFileSystemSource,
1331
- fo as createMarkdownExplorer,
1332
- te as isAcceptableDocumentPath,
1333
- yo 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
1334
1363
  };