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