@aiquants/markdown-explorer 0.35.0 → 0.37.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 (93) hide show
  1. package/CHANGELOG.md +165 -0
  2. package/README.md +105 -13
  3. package/dist/{EditSurface-D2j1kCEE.js → EditSurface-BQgwRUrR.js} +250 -245
  4. package/dist/EditSurface-Xvk5wZu7.cjs +6 -0
  5. package/dist/ExplorerSplit-C_3FChSt.cjs +2 -0
  6. package/dist/ExplorerSplit-C_kaEnyM.js +1619 -0
  7. package/dist/{MultiLayout-CxV5SI7f.cjs → MultiLayout-BZNj1GYo.cjs} +1 -1
  8. package/dist/{MultiLayout-BeJ5Lubb.js → MultiLayout-DROxkTdD.js} +24 -24
  9. package/dist/{NativeScrollBar-RWXpVhbI.cjs → NativeScrollBar-BDF9A1sc.cjs} +1 -1
  10. package/dist/{NativeScrollBar-BM5NULzg.js → NativeScrollBar-DvdOpwIW.js} +2 -2
  11. package/dist/TreeLayout-Cc-ykewY.js +103 -0
  12. package/dist/TreeLayout-D_DYV64_.cjs +1 -0
  13. package/dist/client/MarkdownExplorer.d.cts +4 -5
  14. package/dist/client/MarkdownExplorer.d.ts +4 -5
  15. package/dist/client/hostContract.d.cts +1 -8
  16. package/dist/client/hostContract.d.ts +1 -8
  17. package/dist/core/config.d.cts +6 -0
  18. package/dist/core/config.d.ts +6 -0
  19. package/dist/core/contracts.d.cts +21 -0
  20. package/dist/core/contracts.d.ts +21 -0
  21. package/dist/core/dataRoute.d.cts +5 -1
  22. package/dist/core/dataRoute.d.ts +5 -1
  23. package/dist/core/documentId.d.cts +6 -0
  24. package/dist/core/documentId.d.ts +6 -0
  25. package/dist/core/labels.d.cts +10 -9
  26. package/dist/core/labels.d.ts +10 -9
  27. package/dist/core/location.d.cts +21 -0
  28. package/dist/core/location.d.ts +21 -0
  29. package/dist/explorerCore-DivWkFQF.cjs +1 -0
  30. package/dist/explorerCore-EkU0mwdW.js +1085 -0
  31. package/dist/index-BmOU3xcK.cjs +18 -0
  32. package/dist/{index-C1YMH-yI.js → index-dtjghDWY.js} +2647 -2466
  33. package/dist/index.cjs +1 -1
  34. package/dist/index.d.cts +3 -2
  35. package/dist/index.d.ts +3 -2
  36. package/dist/index.js +49 -45
  37. package/dist/location-Dh6K-y7w.js +761 -0
  38. package/dist/location-DrOP6t1F.cjs +1 -0
  39. package/dist/{merge-DQUYEGCx.cjs → merge-BCFCL1cF.cjs} +1 -1
  40. package/dist/{merge-Bb_HpPhe.js → merge-DC_h-t31.js} +1 -1
  41. package/dist/ownUrls-BTPGNhBt.cjs +1 -0
  42. package/dist/ownUrls-DD0cSCsF.js +409 -0
  43. package/dist/{sanitizeJob-BYRk17nr.js → sanitizeJob-BYqzjFJC.js} +1 -1
  44. package/dist/{sanitizeJob-Cs9o3Vpl.cjs → sanitizeJob-CudE1RUP.cjs} +1 -1
  45. package/dist/{sanitizePolicy-CiQfnxyd.cjs → sanitizePolicy-C-ehd0J_.cjs} +1 -1
  46. package/dist/{sanitizePolicy-CEMdaLUB.js → sanitizePolicy-DAPnUUVm.js} +1 -1
  47. package/dist/sanitizeWorker.cjs +1 -1
  48. package/dist/sanitizeWorker.js +3 -3
  49. package/dist/{sanitizerService-KWXv7bPm.js → sanitizerService-B8v4ap9t.js} +1 -1
  50. package/dist/{sanitizerService-BY4CPCoA.cjs → sanitizerService-DomN7lwC.cjs} +1 -1
  51. package/dist/server/anonymous.d.cts +2 -2
  52. package/dist/server/anonymous.d.ts +2 -2
  53. package/dist/server/errors.d.cts +1 -1
  54. package/dist/server/errors.d.ts +1 -1
  55. package/dist/server/ports.d.cts +24 -2
  56. package/dist/server/ports.d.ts +24 -2
  57. package/dist/server.cjs +1 -1
  58. package/dist/server.d.cts +1 -1
  59. package/dist/server.d.ts +1 -1
  60. package/dist/server.js +16 -16
  61. package/dist/serverBrowser.cjs +1 -1
  62. package/dist/serverBrowser.js +3 -3
  63. package/dist/serverCore.cjs +1 -1
  64. package/dist/serverCore.d.cts +1 -1
  65. package/dist/serverCore.d.ts +1 -1
  66. package/dist/serverCore.js +4 -4
  67. package/dist/styles/markdown-explorer.css +1 -1
  68. package/dist/{tapScrollCircle-BEydRn0y.js → tapScrollCircle-CqMZzWjo.js} +1 -1
  69. package/dist/{tapScrollCircle-DdX0Wri0.cjs → tapScrollCircle-DVNlszeF.cjs} +1 -1
  70. package/dist/testing.cjs +1 -1
  71. package/dist/testing.d.cts +5 -0
  72. package/dist/testing.d.ts +5 -0
  73. package/dist/testing.js +80 -2
  74. package/dist/{useSplitPersistence-B2Fj508K.cjs → useSplitPersistence-BUa_KMsV.cjs} +1 -1
  75. package/dist/{useSplitPersistence-Fkqak8G8.js → useSplitPersistence-pnb21dsr.js} +1 -1
  76. package/docs/behavior/dom-hooks.md +11 -2
  77. package/docs/behavior/hosting.md +1 -1
  78. package/docs/behavior/localization.md +2 -2
  79. package/docs/behavior/security.md +24 -3
  80. package/docs/behavior/url-contract.md +26 -0
  81. package/package.json +6 -4
  82. package/dist/EditSurface-CLG70Vnn.cjs +0 -6
  83. package/dist/ExplorerSplit-CfP1smbT.js +0 -1589
  84. package/dist/ExplorerSplit-D_0VohOv.cjs +0 -2
  85. package/dist/TreeLayout-AxLw-36S.js +0 -103
  86. package/dist/TreeLayout-Bg2YH-EY.cjs +0 -1
  87. package/dist/explorerCore-DLpDuSev.js +0 -998
  88. package/dist/explorerCore-DYrxS9ez.cjs +0 -1
  89. package/dist/index-LQWQfpAf.cjs +0 -18
  90. package/dist/location--KvTA0Ri.js +0 -726
  91. package/dist/location-D8DyDkuA.cjs +0 -1
  92. package/dist/ownUrls-B259RGgd.cjs +0 -1
  93. package/dist/ownUrls-Dh5g6ZJi.js +0 -370
@@ -0,0 +1,1085 @@
1
+ import { accessFailureResponse as rt } from "@aiquants/auth-core";
2
+ import { crossOriginRefusal as ke, NO_CROSS_ORIGIN_NAVIGATION as Te } from "@aiquants/request-isolation";
3
+ import { redirect as Fe, data as Ue } from "react-router";
4
+ import { t as cr, b as tt, w as nt, o as st, f as ot, g as at, i as it, h as ct, e as dt, j as ut, p as lt, k as dr } from "./location-Dh6K-y7w.js";
5
+ import { h as ur, j as ft, k as se, s as pt, b as ht, m as wt, n as mt, o as yt, p as gt, E as lr, q as ee, t as bt, u as Et, i as F, v as kt, w as Tt, x as Rt, y as Ot, z as vt, f as xt, A as fr, B as At, C as ce, F as St, G as It, H as Pt, I as _t, J as M, K as pr, L as Dt, g as V, e as He, N as $t, O as Nt } from "./ownUrls-DD0cSCsF.js";
6
+ import { d as x, i as Lt } from "./describeValue-CLlVRO8d.js";
7
+ import { c as jt, i as Mt, M as Ct } from "./lru-DC8GBmkX.js";
8
+ const hr = "application/octet-stream", wr = "application/pdf", zt = /* @__PURE__ */ new Set([
9
+ "image/png",
10
+ "image/apng",
11
+ "image/jpeg",
12
+ "image/gif",
13
+ "image/webp",
14
+ "image/avif",
15
+ "image/bmp",
16
+ "image/x-icon",
17
+ "image/vnd.microsoft.icon",
18
+ "audio/mpeg",
19
+ "audio/mp4",
20
+ "audio/aac",
21
+ "audio/ogg",
22
+ "audio/opus",
23
+ "audio/wav",
24
+ "audio/wave",
25
+ "audio/x-wav",
26
+ "audio/webm",
27
+ "audio/flac",
28
+ "audio/x-flac",
29
+ "audio/x-m4a",
30
+ "video/mp4",
31
+ "video/webm",
32
+ "video/ogg",
33
+ "video/quicktime",
34
+ wr
35
+ ]), Xe = "default-src 'none'; media-src 'self'; style-src 'unsafe-inline'", ye = Object.freeze({
36
+ sandboxed: `${Xe}; sandbox`,
37
+ mediaDocument: `${Xe}; sandbox allow-same-origin`
38
+ }), Be = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u, Ft = /^[\t\n\r ]+|[\t\n\r ]+$/gu, ge = /^[\t ]+|[\t ]+$/gu, Ut = (e) => {
39
+ const r = [];
40
+ let t = "", o = 0;
41
+ for (; ; ) {
42
+ for (; o < e.length && e[o] !== '"' && e[o] !== ","; )
43
+ t += e[o], o += 1;
44
+ if (o < e.length && e[o] === '"') {
45
+ const c = o;
46
+ for (o += 1; o < e.length && e[o] !== '"'; )
47
+ o += e[o] === "\\" ? 2 : 1;
48
+ if (o = Math.min(o + 1, e.length), t += e.slice(c, o), o < e.length) continue;
49
+ }
50
+ if (r.push(t.replace(ge, "")), t = "", o >= e.length) return r;
51
+ o += 1;
52
+ }
53
+ }, Ht = (e) => {
54
+ const r = e.replace(Ft, ""), t = r.indexOf("/");
55
+ if (t < 0) return null;
56
+ const o = r.slice(0, t), c = r.indexOf(";", t + 1), u = r.slice(t + 1, c < 0 ? r.length : c).replace(/[\t\n\r ]+$/u, "");
57
+ return Be.test(o) && Be.test(u) ? `${o}/${u}`.toLowerCase() : null;
58
+ }, Xt = (e) => {
59
+ let r = null;
60
+ for (const t of Ut(e)) {
61
+ const o = Ht(t);
62
+ o !== null && o !== "*/*" && (r = o);
63
+ }
64
+ return r;
65
+ }, Bt = /['()*]/gu, mr = (e) => encodeURIComponent(e).replace(Bt, (r) => `%${r.charCodeAt(0).toString(16).toUpperCase()}`), Re = Object.freeze({
66
+ "Cache-Control": "private, max-age=60, stale-while-revalidate=600, no-transform",
67
+ Vary: "Cookie"
68
+ }), yr = (e, r) => {
69
+ const t = Xt(e), o = t !== null && zt.has(t), c = o && (t.startsWith("audio/") || t.startsWith("video/"));
70
+ return {
71
+ contentType: t === null ? hr : t,
72
+ inline: o,
73
+ headers: {
74
+ "X-Content-Type-Options": "nosniff",
75
+ "Content-Disposition": `${o ? "inline" : "attachment"}; filename*=UTF-8''${mr(r)}`,
76
+ ...t === wr ? {} : { "Content-Security-Policy": c ? ye.mediaDocument : ye.sandboxed },
77
+ "Cross-Origin-Resource-Policy": "same-origin"
78
+ }
79
+ };
80
+ }, ne = 64 * 1024, gr = (e) => `text/plain; charset=${e}`, Vt = (e) => ({
81
+ "X-Content-Type-Options": "nosniff",
82
+ "Content-Disposition": `inline; filename*=UTF-8''${mr(e)}`,
83
+ "Content-Security-Policy": ye.sandboxed,
84
+ "Cross-Origin-Resource-Policy": "same-origin"
85
+ }), Gt = (e, r) => `${r === null ? "" : r};${e}`, Wt = /^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu, re = Object.freeze({ kind: "whole" }), Ve = Object.freeze({ kind: "unsatisfiable" }), br = (e, r, t, o) => {
86
+ const c = e.get("Range");
87
+ if (c === null) return re;
88
+ const u = e.get("If-Range");
89
+ if (u !== null && u !== t) return re;
90
+ const f = Wt.exec(c);
91
+ if (f === null) return re;
92
+ const [, p, h, T] = f;
93
+ if (T !== void 0) {
94
+ const E = Number(T);
95
+ if (E === 0) return Ve;
96
+ const O = Math.max(0, r - E);
97
+ return Ge(O, r - O, o);
98
+ }
99
+ const m = Number(p), b = h === "" ? Number.POSITIVE_INFINITY : Number(h);
100
+ return b < m ? re : m >= r ? Ve : Ge(m, Math.min(b, r - 1) - m + 1, o);
101
+ }, Ge = (e, r, t) => ({ kind: "partial", range: { offset: e, length: t === null ? r : Math.min(r, t) } }), We = "W/", Yt = (e) => {
102
+ const r = [];
103
+ let t = 0, o = !1;
104
+ for (let c = 0; c < e.length; c += 1)
105
+ e[c] === '"' ? o = !o : e[c] === "," && !o && (r.push(e.slice(t, c).replace(ge, "")), t = c + 1);
106
+ return r.push(e.slice(t).replace(ge, "")), r;
107
+ }, Ye = (e) => e.startsWith(We) ? e.slice(We.length) : e, Oe = (e, r) => {
108
+ if (e === null) return !1;
109
+ const t = Yt(e);
110
+ if (t.length === 1 && t[0] === "*") return !0;
111
+ const o = Ye(r);
112
+ return t.some((c) => Ye(c) === o);
113
+ }, Jt = (e, r) => {
114
+ let t = r;
115
+ return e.pipeThrough(
116
+ new TransformStream({
117
+ transform: (o, c) => {
118
+ const u = o.byteLength > t ? o.subarray(0, t) : o;
119
+ t -= u.byteLength, c.enqueue(u), t === 0 && c.terminate();
120
+ },
121
+ flush: (o) => {
122
+ t > 0 && o.error(new RangeError("[markdown-explorer] the asset ended before its declared length"));
123
+ }
124
+ })
125
+ );
126
+ }, W = (e, r, t, o, c) => (c !== null && t.set("Content-Length", String(c)), { head: e.method.toUpperCase() === "HEAD", status: r, headers: t, range: o, length: c }), q = ({ head: e, status: r, headers: t, range: o, length: c }) => e ? { kind: "respond", response: new Response(null, { status: r, headers: t }) } : { kind: "stream", status: r, headers: t, range: o, length: c }, oe = async (e, r) => {
127
+ if (e.kind === "respond") return e.response;
128
+ const t = await r(e.range);
129
+ return new Response(e.length === null ? t : Jt(t, e.length), { status: e.status, headers: e.headers });
130
+ }, Er = (e, r) => {
131
+ const t = new Headers(e);
132
+ for (const [o, c] of Object.entries({ "Accept-Ranges": "bytes", "Content-Range": `bytes */${r}`, "Cache-Control": "private, no-store", "X-Content-Type-Options": "nosniff" })) t.set(o, c);
133
+ return new Response(null, { status: 416, headers: t });
134
+ }, kr = (e, r, t, o) => {
135
+ const c = `"${r.version}"`, u = yr(r.contentType, r.name), f = new Headers(t);
136
+ for (const [T, m] of Object.entries({ ...u.headers, ...Re, ETag: c })) f.set(T, m);
137
+ if (Oe(e.headers.get("If-None-Match"), c)) return { kind: "respond", response: new Response(null, { status: 304, headers: f }) };
138
+ if (f.set("Content-Type", u.contentType), r.size === null) return q(W(e, 200, f, null, null));
139
+ if (r.size === 0)
140
+ return f.set("Content-Length", "0"), { kind: "respond", response: new Response(null, { status: 200, headers: f }) };
141
+ f.set("Accept-Ranges", "bytes");
142
+ const p = br(e.headers, r.size, c, o);
143
+ if (p.kind === "unsatisfiable") return { kind: "respond", response: Er(t, r.size) };
144
+ if (p.kind === "whole") return q(W(e, 200, f, null, r.size));
145
+ const { range: h } = p;
146
+ return f.set("Content-Range", `bytes ${h.offset}-${h.offset + h.length - 1}/${r.size}`), q(W(e, 206, f, h, h.length));
147
+ }, Kt = async (e, r, t, o) => oe(kr(e, r, t, o), (c) => r.open(c)), Qt = (e, r) => {
148
+ const t = new Uint8Array(r);
149
+ let o = 0;
150
+ for (const c of e) {
151
+ if (o === r) break;
152
+ const u = c.subarray(0, r - o);
153
+ t.set(u, o), o += u.byteLength;
154
+ }
155
+ return t;
156
+ }, Zt = (e, r, t) => new ReadableStream(
157
+ {
158
+ start: (o) => {
159
+ for (const c of e) o.enqueue(c);
160
+ r && o.close();
161
+ },
162
+ pull: async (o) => {
163
+ const { done: c, value: u } = await t.read();
164
+ c ? o.close() : o.enqueue(u);
165
+ },
166
+ cancel: (o) => t.cancel(o)
167
+ },
168
+ { highWaterMark: 0 }
169
+ ), Tr = async (e, r, t) => {
170
+ const o = e.getReader(), c = r === null ? ne : Math.min(r, ne), u = r === null ? c + 1 : c, f = [];
171
+ let p = 0, h = !1;
172
+ try {
173
+ for (; p < u; ) {
174
+ const { done: b, value: E } = await o.read();
175
+ if (b) {
176
+ h = !0;
177
+ break;
178
+ }
179
+ f.push(E), p += E.byteLength;
180
+ }
181
+ if (h && r !== null && p < c) throw new RangeError("[markdown-explorer] the asset ended before its declared length");
182
+ const T = r === null ? h : r <= ne;
183
+ return { encoding: cr(Qt(f, Math.min(p, c)), T, t), body: Zt(f, h, o) };
184
+ } catch (T) {
185
+ throw o.cancel(T).catch(() => {
186
+ }), T;
187
+ }
188
+ }, Rr = async (e, r) => {
189
+ const t = await Tr(await e.open(e.size === null ? null : { offset: 0, length: Math.min(e.size, ne) }), e.size, r);
190
+ return t.body.cancel().catch(() => {
191
+ }), t.encoding;
192
+ }, Or = (e, r, t, o, c) => {
193
+ const u = `"${Gt(r.version, o)}"`, f = new Headers(t);
194
+ for (const [T, m] of Object.entries({ ...Vt(r.name), ...Re, ETag: u })) f.set(T, m);
195
+ if (Oe(e.headers.get("If-None-Match"), u)) return { kind: "respond", response: new Response(null, { status: 304, headers: f }) };
196
+ if (r.size === 0)
197
+ return f.set("Content-Type", gr(cr(new Uint8Array(0), !0, o))), f.set("Content-Length", "0"), { kind: "respond", response: new Response(null, { status: 200, headers: f }) };
198
+ if (r.size === null) return { kind: "needs-encoding", selection: W(e, 200, f, null, null) };
199
+ f.set("Accept-Ranges", "bytes");
200
+ const p = br(e.headers, r.size, u, c);
201
+ if (p.kind === "unsatisfiable") return { kind: "respond", response: Er(t, r.size) };
202
+ if (p.kind === "whole") return { kind: "needs-encoding", selection: W(e, 200, f, null, r.size) };
203
+ const { range: h } = p;
204
+ return f.set("Content-Range", `bytes ${h.offset}-${h.offset + h.length - 1}/${r.size}`), { kind: "needs-encoding", selection: W(e, 206, f, h, h.length) };
205
+ }, be = (e, r) => {
206
+ const t = new Headers(e.headers);
207
+ return t.set("Content-Type", gr(r)), q({ ...e, headers: t });
208
+ }, qt = async (e, r, t, o, c) => {
209
+ const u = Or(e, r, t, o, c);
210
+ if (u.kind === "respond") return u.response;
211
+ const { selection: f } = u;
212
+ if (f.head || f.range !== null) return oe(be(f, await Rr(r, o)), (h) => r.open(h));
213
+ const p = await Tr(await r.open(null), r.size, o);
214
+ return oe(be(f, p.encoding), async () => p.body);
215
+ }, en = (e) => `workbook;${e}`, rn = async (e, r, t) => {
216
+ const o = `"${en(r.version)}"`, c = yr(hr, r.name), u = new Headers(t);
217
+ for (const [f, p] of Object.entries({ ...c.headers, ...Re, ETag: o })) u.set(f, p);
218
+ return Oe(e.headers.get("If-None-Match"), o) ? new Response(null, { status: 304, headers: u }) : (u.set("Content-Type", c.contentType), oe(q(W(e, 200, u, null, r.size)), (f) => r.open(f)));
219
+ }, tn = Object.freeze({
220
+ "Cache-Control": "private, no-store",
221
+ "Referrer-Policy": "no-referrer"
222
+ }), nn = (e, r) => {
223
+ const t = new Headers(r);
224
+ for (const [o, c] of Object.entries(tn)) t.set(o, c);
225
+ return t.set("Location", e), new Response(null, { status: 302, headers: t });
226
+ }, pe = (e, r) => {
227
+ const t = new AbortController(), o = r(AbortSignal.any([e.signal, t.signal]));
228
+ return new Promise((c) => {
229
+ let u;
230
+ const f = setTimeout(() => {
231
+ c(e.late), u = setTimeout(() => t.abort(), e.handOverMs);
232
+ }, e.timeoutMs), p = () => {
233
+ clearTimeout(f), clearTimeout(u);
234
+ };
235
+ o.then(
236
+ (h) => {
237
+ p(), c(h);
238
+ },
239
+ () => {
240
+ p(), c(e.late);
241
+ }
242
+ );
243
+ });
244
+ }, sn = Object.freeze({
245
+ error: (e, r) => {
246
+ console.error(e, r);
247
+ }
248
+ }), vr = /* @__PURE__ */ Symbol.for("@aiquants/markdown-explorer:ExplorerError");
249
+ class us extends Error {
250
+ reason;
251
+ code;
252
+ constructor(r, t = {}) {
253
+ if (!ur(r)) throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${x(r)}`);
254
+ if (t.code !== void 0 && !ft(t.code)) throw new RangeError(`[markdown-explorer] an ExplorerError code must be 1 to 64 lowercase letters, digits or hyphens; got ${x(t.code)}`);
255
+ super(`[markdown-explorer] ${r}`, t.cause === void 0 ? void 0 : { cause: t.cause }), this.name = "ExplorerError", this.reason = r, this.code = t.code, Object.defineProperty(this, vr, { value: !0 });
256
+ }
257
+ }
258
+ const on = (e) => e instanceof Error && Object.hasOwn(e, vr) && ur(e.reason), an = (e) => typeof e == "object" && e !== null && e.name === "AbortError", ve = (e, r, t) => {
259
+ try {
260
+ e.error(r, t);
261
+ } catch (o) {
262
+ console.error("[markdown-explorer] the logger threw while reporting a failure", { operation: t.operation, error: o });
263
+ }
264
+ }, $ = (e, r) => ve(e, `[markdown-explorer] ${r.operation} failed`, r), cn = (e, r) => ve(e, `[markdown-explorer] ${r.operation} left out an entry`, r), Z = (e, r) => ve(e, `[markdown-explorer] ${r.operation} refused a path the deny rules match`, { ...r, error: new RangeError("[markdown-explorer] the path matches a deny rule") }), Je = (e, r) => {
265
+ e === null || typeof e != "object" && typeof e != "function" || Promise.resolve(e).then(void 0, r);
266
+ }, v = (e, r, t, o) => on(e) ? se(e.reason, e.code) : (an(e) || t.aborted || $(o, { ...r, error: e }), { reason: "failed" }), Ke = 2 * 1024 * 1024, Qe = 256 * 1024 * 1024, dn = async (e, r) => {
267
+ const t = e.getReader(), o = new Uint8Array(r);
268
+ let c = 0;
269
+ for (; c < r; ) {
270
+ const { done: u, value: f } = await t.read();
271
+ if (u) return o.subarray(0, c);
272
+ const p = f.subarray(0, r - c);
273
+ o.set(p, c), c += p.byteLength;
274
+ }
275
+ return t.cancel().catch(() => {
276
+ }), o;
277
+ }, un = async (e, r, t) => {
278
+ if (e.size === 0) return { text: "", truncated: !1 };
279
+ const o = e.size !== null && e.size > r, c = e.size === null ? r + 1 : Math.min(e.size, r), u = await dn(await e.open(o ? { offset: 0, length: r } : null), c);
280
+ if (e.size !== null && u.byteLength < c) throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");
281
+ const f = o || u.byteLength > r, p = f ? u.subarray(0, r) : u, h = tt(p, !f, t);
282
+ return h.includes("\0") ? null : { text: h, truncated: f };
283
+ }, ae = (e) => ({ result: e, json: JSON.stringify(e) }), he = Object.freeze(ae(Object.freeze({ status: "error", failure: Object.freeze({ reason: "failed" }) }))), ln = (e) => e.status === "ok" && e.entries.length > 0, fn = ({ ttlMs: e, maxEntries: r, maxBytes: t, now: o }) => {
284
+ const c = jt(r, { max: t, of: (m, b) => 2 * b.tree.json.length }), u = /* @__PURE__ */ new Map(), f = /* @__PURE__ */ new Map(), p = (m, b) => {
285
+ const E = new AbortController(), O = { waiters: 0, superseded: !1, started: !1, loadTree: b }, P = f.get(m), U = (j, de) => {
286
+ const K = ae(j);
287
+ return !(O.superseded || E.signal.aborted) && ln(j) && c.set(m, { tree: K, loadedAt: de }), K;
288
+ }, z = (async () => {
289
+ if (P !== void 0 && await P, E.signal.aborted) return he;
290
+ const j = o();
291
+ return O.started = !0, U(await O.loadTree(E.signal, j), j);
292
+ })().finally(() => {
293
+ u.get(m) === X && u.delete(m);
294
+ }), X = { promise: z, controller: E, state: O };
295
+ u.set(m, X);
296
+ const N = z.then(
297
+ () => {
298
+ },
299
+ () => {
300
+ }
301
+ );
302
+ return f.set(m, N), N.then(() => {
303
+ f.get(m) === N && f.delete(m);
304
+ }), X;
305
+ }, h = (m, b, E) => {
306
+ b.state.waiters += 1;
307
+ const O = () => {
308
+ b.state.waiters -= 1, !(b.state.waiters > 0) && (u.get(m) === b && u.delete(m), b.controller.abort());
309
+ };
310
+ return E.addEventListener("abort", O, { once: !0 }), b.promise.finally(() => {
311
+ E.removeEventListener("abort", O);
312
+ });
313
+ }, T = (m) => {
314
+ c.delete(m);
315
+ const b = u.get(m);
316
+ b?.state.started && (b.state.superseded = !0, u.delete(m));
317
+ };
318
+ return {
319
+ load: (m, b, E) => {
320
+ if (b.aborted) return Promise.resolve(he);
321
+ const O = c.get(m);
322
+ if (O !== void 0) {
323
+ if (o() - O.loadedAt < e) return Promise.resolve(O.tree);
324
+ c.delete(m);
325
+ }
326
+ const P = u.get(m);
327
+ return h(m, P === void 0 ? p(m, E) : P, b);
328
+ },
329
+ refresh: (m, b, E) => {
330
+ if (b.aborted) return Promise.resolve(he);
331
+ T(m);
332
+ const O = u.get(m);
333
+ return O === void 0 ? h(m, p(m, E), b) : (O.state.loadTree = E, h(m, O, b));
334
+ },
335
+ forget: T
336
+ };
337
+ }, pn = (e) => ({
338
+ load: (r, t, o) => o(t, e()).then(ae),
339
+ refresh: (r, t, o) => o(t, e()).then(ae),
340
+ forget: () => {
341
+ }
342
+ }), g = (e) => {
343
+ throw new TypeError(`[markdown-explorer] ${e}`);
344
+ }, hn = (e) => {
345
+ if (e === null || typeof e != "object") return null;
346
+ const { name: r, path: t } = e;
347
+ return typeof r != "string" || typeof t != "string" ? null : r === "" ? { path: t, reason: "an empty name" } : F(t) ? null : { path: t, reason: "a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)" };
348
+ }, wn = (e, r, t, o) => {
349
+ if (e === null) return null;
350
+ if (!Array.isArray(e)) throw new TypeError(`[markdown-explorer] a source's ancestors must be null or an array of folder paths; got ${x(e)}`);
351
+ const c = /* @__PURE__ */ new Set();
352
+ for (const u of e) {
353
+ if (typeof u != "string" || !F(u)) throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");
354
+ if (t.deniesPath(u)) throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");
355
+ if (!o(u)) throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");
356
+ if (u === r) throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");
357
+ if (c.has(u)) throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");
358
+ c.add(u);
359
+ }
360
+ return Object.freeze([...c]);
361
+ }, mn = (e, r, t, o, c) => {
362
+ const u = /* @__PURE__ */ new Set(), f = (h) => {
363
+ if (!Array.isArray(h)) return g("a source returned entries that are not an array");
364
+ const T = [];
365
+ for (const m of h) {
366
+ const b = p(m);
367
+ b !== null && T.push(b);
368
+ }
369
+ return T;
370
+ }, p = (h) => {
371
+ const T = hn(h);
372
+ if (T !== null)
373
+ return o(T), null;
374
+ const m = Tt(h);
375
+ if (m !== null) return g(m);
376
+ const b = h;
377
+ if (u.has(b)) return g("a source returned entries that contain themselves");
378
+ const { name: E, path: O, type: P, mimeType: U, modifiedAt: H, children: z, lazy: X } = b;
379
+ if (r.deniesName(E) || r.deniesPath(O)) return null;
380
+ if (!c(O))
381
+ return o({ path: O, reason: "a path outside the source's boundary" }), null;
382
+ const N = { name: E, path: O, ...U === void 0 ? {} : { mimeType: U }, ...H === void 0 ? {} : { modifiedAt: H } };
383
+ if (P === "file") return { ...N, type: P };
384
+ if (X === !0)
385
+ return t ? { ...N, type: P, lazy: !0, children: [] } : g("a lazy directory came from a source without a children function");
386
+ if (z === void 0) return { ...N, type: P };
387
+ u.add(b);
388
+ const j = f(z);
389
+ return u.delete(b), { ...N, type: P, children: j };
390
+ };
391
+ return f(e);
392
+ }, yn = /^[\x21\x23-\x7E]{1,256}$/u, xr = (e) => typeof e == "string" && yn.test(e), gn = /* @__PURE__ */ new Set(["text", "image", "media", "spreadsheet", "file"]), bn = (e) => typeof e == "string" && gn.has(e), En = (e, r, t) => {
393
+ if (e !== null && typeof e == "object") {
394
+ const u = e, { kind: f } = u;
395
+ if (bn(f)) {
396
+ if (Object.hasOwn(u, "url")) return g(`a ${f} document carries its version, not a url`);
397
+ if (typeof u.name != "string") return g("a document needs a name string");
398
+ if (!xr(u.version)) return g(`a ${f} document needs a version of 1 to 256 visible ASCII characters other than '"'`);
399
+ const p = r(u.version);
400
+ switch (f) {
401
+ case "image": {
402
+ const { imageType: h } = u;
403
+ return yt(h) ? { kind: f, name: u.name, url: p, imageType: h } : g(`unknown image type ${x(h)}`);
404
+ }
405
+ case "file":
406
+ return { kind: f, name: u.name, url: p };
407
+ case "media": {
408
+ const { mediaType: h } = u;
409
+ return mt(h) ? { kind: f, name: u.name, url: p, mediaType: h } : g(`unknown media type ${x(h)}`);
410
+ }
411
+ case "text": {
412
+ const { text: h, truncated: T, lang: m } = u;
413
+ return typeof h != "string" || typeof T != "boolean" ? g("a text document needs text and truncated") : ht(m) ? { kind: f, name: u.name, text: h, truncated: T, lang: m, url: p } : g(wt(f, m));
414
+ }
415
+ case "spreadsheet": {
416
+ const h = pt(u);
417
+ if (h !== null) return g(h);
418
+ const { format: T, firstSheetText: m, edit: b } = u;
419
+ return { kind: f, name: u.name, url: p, format: T, firstSheetText: m, edit: Tn(b) };
420
+ }
421
+ }
422
+ }
423
+ }
424
+ const o = gt(e);
425
+ if (o !== null) return g(o);
426
+ const c = e;
427
+ switch (c.kind) {
428
+ case "failure": {
429
+ const { reason: u, code: f } = c.failure;
430
+ return { kind: "failure", failure: se(u, f) };
431
+ }
432
+ case "markdown":
433
+ return c.headings.length > lr ? { kind: "failure", failure: se("too-large") } : (c.edit?.kind === "inline" || c.edit?.kind === "draft") && !t ? g(`a markdown document offers ${c.edit.kind} editing, but the server has no edit ports`) : { kind: "unsanitized-markdown", name: c.name, html: c.htmlContent, headings: c.headings.map(({ text: u, depth: f, id: p }) => ({ text: u, depth: f, id: p })), lang: c.lang, edit: kn(c.edit) };
434
+ }
435
+ }, kn = (e) => {
436
+ if (e === null) return null;
437
+ switch (e.kind) {
438
+ case "inline":
439
+ return { kind: "inline" };
440
+ case "draft":
441
+ return { kind: "draft" };
442
+ case "external":
443
+ return { kind: "external", href: e.href };
444
+ }
445
+ }, Tn = (e) => e === null ? null : { kind: "external", href: e.href }, ie = (e, r, t) => typeof e != "string" ? g(`${t} needs a text string`) : e.includes("\0") ? g(`${t} holds NUL, which no text editor can keep`) : new TextEncoder().encode(e).byteLength > r ? g(`${t} is over editMaxBytes (${r} bytes); refuse a longer source with ExplorerError "too-large"`) : e, Ar = (e) => kt(e.href) ? { kind: "grant", href: e.href } : g("a grant needs a root-relative href"), Rn = (e, r) => {
446
+ if (e === null || typeof e != "object") return g("an edit source must be an object");
447
+ const t = e;
448
+ return t.kind === "grant" ? Ar(t) : t.kind === "draft" ? { kind: "draft", text: ie(t.text, r, "a draft source") } : t.kind !== "edit" ? g(`an edit source's kind must be "edit", "draft" or "grant"`) : ee(t.version) ? typeof t.history != "boolean" ? g("an edit source needs history") : { kind: "edit", text: ie(t.text, r, "an edit source"), version: t.version, history: t.history } : g("an edit source needs a version of 1 to 1024 characters");
449
+ }, On = (e, r) => {
450
+ if (e === null || typeof e != "object") return g("a save result must be an object");
451
+ const t = e;
452
+ switch (t.kind) {
453
+ case "grant":
454
+ return Ar(t);
455
+ case "saved":
456
+ return ee(t.version) ? { kind: "saved", version: t.version } : g("a saved result needs a version of 1 to 1024 characters");
457
+ case "conflict":
458
+ return ee(t.version) ? { kind: "conflict", version: t.version, text: ie(t.text, r, "a conflict's current text") } : g("a conflict needs the current version of 1 to 1024 characters");
459
+ default:
460
+ return g(`a save result's kind must be "saved", "conflict" or "grant"`);
461
+ }
462
+ }, vn = (e) => {
463
+ if (e === null || typeof e != "object") return g("a preview must be an object");
464
+ const { htmlContent: r, headings: t } = e;
465
+ if (typeof r != "string" || !Array.isArray(t)) return g("a preview needs htmlContent and headings");
466
+ if (t.length > lr) return { kind: "failure", failure: se("too-large") };
467
+ for (const o of t) {
468
+ const c = Et(o);
469
+ if (c !== null) return g(c);
470
+ }
471
+ return { html: r, headings: t.map(({ text: o, depth: c, id: u }) => ({ text: o, depth: c, id: u })) };
472
+ }, xn = (e) => {
473
+ if (!Array.isArray(e)) return g("revisions must be an array");
474
+ const r = /* @__PURE__ */ new Set();
475
+ return e.map((t) => {
476
+ const o = bt(t);
477
+ if (o !== null) return g(o);
478
+ const { id: c, modifiedAt: u, size: f, author: p, kept: h, current: T } = t;
479
+ return r.has(c) ? g(`two revisions share the id ${x(c)}`) : (r.add(c), { id: c, modifiedAt: u, size: f, author: p, kept: h, current: T });
480
+ });
481
+ }, An = (e, r) => ie(e, r, "a revision"), Ee = (e) => {
482
+ if (e === null || typeof e != "object") return g("an asset file must be an object");
483
+ const { name: r, contentType: t, size: o, version: c, open: u, kind: f, bridge: p } = e;
484
+ if (f !== void 0) return g(f === "redirect" ? "an asset redirect answers only a request for the stored file (options.delivery file), never one that reads the bytes" : 'an asset file has no kind (the only kind is "redirect")');
485
+ if (typeof r != "string" || r === "") return g("an asset file needs a non-empty name");
486
+ if (typeof t != "string") return g("an asset file needs a contentType string ('' when unknown)");
487
+ if (o !== null && !(typeof o == "number" && Number.isSafeInteger(o) && o >= 0)) return g("an asset file's size must be null or a non-negative safe integer");
488
+ if (!xr(c)) return g(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`);
489
+ if (typeof u != "function") return g("an asset file needs an open function");
490
+ const h = { name: r, contentType: t, size: o, version: c, open: u };
491
+ return Object.freeze(p === void 0 ? h : { ...h, bridge: Sn(p) });
492
+ }, Sn = (e) => {
493
+ if (e === null || typeof e != "object") return g("an asset file's bridge must be an object when present");
494
+ const { uri: r, storageVersion: t, readFailure: o } = e;
495
+ return typeof r != "string" || r === "" ? g("an asset file's bridge needs a non-empty uri") : t !== null && (typeof t != "string" || t === "") ? g("an asset file's bridge needs a storageVersion that is a non-empty string, or null when the storage keeps none") : typeof o != "function" ? g("an asset file's bridge needs a readFailure function") : Object.freeze({ uri: r, storageVersion: t, readFailure: o });
496
+ }, Ze = (e) => {
497
+ if (e === null || typeof e != "object" || e.kind !== "redirect") return Ee(e);
498
+ const { url: r } = e;
499
+ if (typeof r != "string" || !URL.canParse(r)) return g("an asset redirect needs an absolute https URL");
500
+ const t = new URL(r);
501
+ return t.protocol !== "https:" || t.username !== "" || t.password !== "" ? g("an asset redirect's URL must be https and carry no credentials") : Object.freeze({ kind: "redirect", url: t.href });
502
+ }, In = (e) => Array.isArray(e) ? e.map((r) => {
503
+ if (r === null || typeof r != "object") return g("a notice must be an object");
504
+ const { id: t, tone: o, title: c, body: u, action: f } = r;
505
+ if (typeof t != "string" || t === "" || typeof c != "string") return g("a notice needs an id and a title");
506
+ if (!Rt(o)) return g(`unknown notice tone ${x(o)}`);
507
+ if (u !== void 0 && typeof u != "string") return g("a notice body must be a string");
508
+ const h = { id: t, tone: o, title: c, ...u === void 0 ? {} : { body: u } };
509
+ if (f === void 0) return h;
510
+ if (f === null || typeof f != "object") return g("a notice action must be an object");
511
+ const { label: T, href: m } = f;
512
+ return typeof T != "string" || !Ot(m, vt) ? g("a notice action needs a label and an http(s), mailto or relative href") : { ...h, action: { label: T, href: m } };
513
+ }) : g("notices must be an array"), Pn = 4e3, te = Object.freeze({ ttlMs: 3e5, maxEntries: 64, maxBytes: 64 * 1024 * 1024 }), Sr = "private, no-store", _n = Object.freeze({
514
+ "Content-Type": "application/json; charset=utf-8",
515
+ "Cache-Control": Sr,
516
+ "X-Content-Type-Options": "nosniff",
517
+ "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'; sandbox",
518
+ "Cross-Origin-Resource-Policy": "same-origin"
519
+ }), we = Object.freeze([]), Dn = Object.freeze({ status: "ok", source: null, ancestors: null }), qe = Object.freeze(["contains", "confirm"]), er = Object.freeze({ readOnly: !1 }), $n = Object.freeze({ readOnly: !0 }), Nn = /* @__PURE__ */ new Set(["file", "text", "workbook"]), Ln = /* @__PURE__ */ new Set(["file", "text"]), jn = Object.freeze({ status: "error", failure: Object.freeze({ reason: "invalid" }) }), I = (e, r, t) => {
520
+ if (!(t && r === void 0) && typeof r != "function")
521
+ throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${x(r)}`);
522
+ }, G = (e, r, t) => {
523
+ if (typeof r != "number") throw new TypeError(`[markdown-explorer] ${e} must be a number; got ${x(r)}`);
524
+ if (!Number.isSafeInteger(r) || r <= 0 || r > t) throw new RangeError(`[markdown-explorer] ${e} must be an integer in 1..${String(t)}; got ${x(r)}`);
525
+ return r;
526
+ }, Mn = (e) => {
527
+ if (e === null || typeof e != "object" || !Object.isFrozen(e)) throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");
528
+ return at(e);
529
+ }, me = (e) => {
530
+ try {
531
+ return new Headers(e);
532
+ } catch {
533
+ throw new TypeError("[markdown-explorer] authenticate returned headers that are not a valid headers init (their values are not logged)");
534
+ }
535
+ }, rr = (e) => e instanceof Response ? new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`) : e, Cn = (e, r) => {
536
+ if (!Lt(r)) throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);
537
+ for (const t of Object.keys(r))
538
+ if (!qe.includes(t)) throw new RangeError(`[markdown-explorer] ${e}.boundary.${t} is not an option; expected ${qe.join(", ")}`);
539
+ I(`${e}.boundary.contains`, r.contains, !1), I(`${e}.boundary.confirm`, r.confirm, !0);
540
+ }, zn = (e) => {
541
+ if (!Array.isArray(e)) throw new TypeError("[markdown-explorer] sources must be an array");
542
+ const r = e;
543
+ if (r.length === 0) throw new RangeError("[markdown-explorer] sources must hold at least one source");
544
+ const t = /* @__PURE__ */ new Set();
545
+ for (const [o, c] of r.entries()) {
546
+ if (c === null || typeof c != "object") throw new TypeError(`[markdown-explorer] sources[${String(o)}] must be an object`);
547
+ const { id: u, label: f, boundary: p, tree: h, children: T, ancestors: m, cacheScope: b } = c;
548
+ if (!it(u))
549
+ throw new RangeError(`[markdown-explorer] sources[${String(o)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${x(u)}`);
550
+ const E = `source ${x(u)}`;
551
+ if (t.has(u)) throw new RangeError(`[markdown-explorer] source ids must be unique; ${x(u)} repeats at sources[${String(o)}]`);
552
+ if (t.add(u), typeof f != "string" && typeof f != "function") throw new TypeError(`[markdown-explorer] ${E}.label must be a string or a function`);
553
+ if (typeof f == "string" && f.trim() === "") throw new RangeError(`[markdown-explorer] ${E}.label must not be blank`);
554
+ if (Cn(E, p), I(`${E}.tree`, h, !1), I(`${E}.children`, T, !0), I(`${E}.ancestors`, m, !0), b !== void 0 && b !== "principal" && b !== "shared") throw new RangeError(`[markdown-explorer] ${E}.cacheScope must be "principal" or "shared"; got ${x(b)}`);
555
+ }
556
+ return r;
557
+ }, Fn = (e) => {
558
+ if (e === !1) return !1;
559
+ if (e === void 0) return te;
560
+ if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] treeCache must be { ttlMs, maxEntries, maxBytes } or false");
561
+ const { ttlMs: r, maxEntries: t, maxBytes: o } = e;
562
+ return {
563
+ ttlMs: r === void 0 ? te.ttlMs : G("treeCache.ttlMs", r, Number.MAX_SAFE_INTEGER),
564
+ maxEntries: t === void 0 ? te.maxEntries : G("treeCache.maxEntries", t, Number.MAX_SAFE_INTEGER),
565
+ maxBytes: o === void 0 ? te.maxBytes : G("treeCache.maxBytes", o, Number.MAX_SAFE_INTEGER)
566
+ };
567
+ }, tr = (e) => {
568
+ if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] authenticate must resolve to { status, ... }");
569
+ const { status: r } = e;
570
+ if (r !== "signed-in" && r !== "signed-out" && r !== "forbidden") throw new TypeError(`[markdown-explorer] authenticate resolved to an unknown status ${x(r)}`);
571
+ return e;
572
+ }, Un = (e, r) => {
573
+ if (!(r instanceof Response)) throw new TypeError(`[markdown-explorer] ${e} must return a Response`);
574
+ return r;
575
+ }, nr = (e, r) => {
576
+ if (typeof r != "string" || r === "") throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");
577
+ const t = e(r);
578
+ if (!Mt(t)) throw new TypeError("[markdown-explorer] the platform's scope must be 22 base64url characters");
579
+ return t;
580
+ }, Hn = (e, r) => {
581
+ try {
582
+ return e(r);
583
+ } catch (t) {
584
+ return t;
585
+ }
586
+ }, Xn = (e, r) => {
587
+ const t = e(r);
588
+ if (t !== void 0 && typeof t != "string") throw new TypeError(`[markdown-explorer] readSettings must return a string or undefined; got ${t === null ? "null" : typeof t}`);
589
+ return t;
590
+ }, Bn = (e) => e.view === "multi" ? e.docs : e.doc === null ? [] : [e.doc], C = (e, r) => {
591
+ const t = e.getAll(r), [o] = t;
592
+ return t.length === 1 && o !== void 0 && o !== "" ? o : null;
593
+ }, S = (e, r, t, o = {}) => {
594
+ const c = new Headers(t);
595
+ for (const [u, f] of Object.entries({ ..._n, ...o })) c.set(u, f);
596
+ return new Response(r, { status: e, headers: c });
597
+ }, R = (e, r, t) => S(fr[e.reason], JSON.stringify({ failure: e }), r, t), Vn = /* @__PURE__ */ new Set(["refresh", "save", "preview", "issue-id"]), Gn = /* @__PURE__ */ new Set(["issue-id", "resolve-id"]), sr = 4, Wn = /* @__PURE__ */ new Set(["edit", "save", "preview", "revisions", "revision"]), or = (e, r) => {
598
+ const t = Vn.has(r) ? ["POST"] : ["GET", "HEAD"];
599
+ return t.includes(e.method.toUpperCase()) ? null : S(405, JSON.stringify({ failure: { reason: "invalid" } }), void 0, { Allow: t.join(", ") });
600
+ }, ar = (e) => e.headers.get(ce) === St && ke(e, Te) === void 0, Yn = (e) => e.headers.get(ce) === It && ke(e, Te) === void 0, Jn = (e) => e.headers.get(ce) === Pt && ke(e, Te) === void 0, Kn = async (e, r) => {
601
+ const [t, ...o] = (e.headers.get("Content-Type") ?? "").split(";").map((E) => E.trim().toLowerCase()), c = o.find((E) => E.startsWith("charset="));
602
+ if (t !== Nt || c !== void 0 && c !== "charset=utf-8") return { status: "error", failure: { reason: "invalid" } };
603
+ const u = Number(e.headers.get("Content-Length") ?? "0");
604
+ if (Number.isFinite(u) && u > r) return { status: "error", failure: { reason: "too-large" } };
605
+ if (e.body === null) return { status: "ok", text: "" };
606
+ const f = e.body.getReader(), p = [];
607
+ let h = 0;
608
+ for (; ; ) {
609
+ const { done: E, value: O } = await f.read();
610
+ if (E) break;
611
+ if (h += O.byteLength, h > r)
612
+ return await f.cancel(), { status: "error", failure: { reason: "too-large" } };
613
+ p.push(O);
614
+ }
615
+ const T = new Uint8Array(h);
616
+ let m = 0;
617
+ for (const E of p)
618
+ T.set(E, m), m += E.byteLength;
619
+ let b;
620
+ try {
621
+ b = new TextDecoder("utf-8", { fatal: !0 }).decode(T);
622
+ } catch {
623
+ return { status: "error", failure: { reason: "invalid" } };
624
+ }
625
+ return b.includes("\0") ? { status: "error", failure: { reason: "invalid" } } : { status: "ok", text: b };
626
+ }, Qn = (e) => {
627
+ if (e === void 0) return;
628
+ if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] edit must be an object of the editor's ports");
629
+ const r = e;
630
+ for (const t of ["source", "save", "preview", "revisions", "revision"]) I(`edit.${t}`, r[t], !1);
631
+ return e;
632
+ }, Zn = (e, r) => {
633
+ if (e.documentIds === null != (r === void 0)) throw new TypeError("[markdown-explorer] documentIds in defineExplorerConfig and the server's documentIds ports go together; give both or neither");
634
+ if (r === void 0) return;
635
+ if (r === null || typeof r != "object") throw new TypeError("[markdown-explorer] documentIds must be an object of the registry's ports");
636
+ const t = r;
637
+ for (const o of ["issue", "resolve"]) I(`documentIds.${o}`, t[o], !1);
638
+ return r;
639
+ }, qn = (e) => {
640
+ if (e === null || typeof e != "object") return null;
641
+ const { kind: r, id: t } = e;
642
+ return r === "issued" || r === "taken" ? { kind: r } : r === "existing" && pr(t) ? { kind: r, id: t } : null;
643
+ }, es = (e) => {
644
+ if (e === null || typeof e != "object") return;
645
+ const { kind: r, path: t } = e;
646
+ return r === "unbound" ? null : r === "bound" && typeof t == "string" && dr(t) ? t : void 0;
647
+ }, ir = (e, r) => e.status === "ok" ? S(200, JSON.stringify(e), r) : R(e.failure, r), rs = ({ parentHeaders: e, loaderHeaders: r, errorHeaders: t }) => {
648
+ const o = new Headers(), c = t === void 0 ? [e, r] : [e, r, t];
649
+ for (const u of c)
650
+ for (const [f, p] of u)
651
+ f !== "set-cookie" && o.set(f, p);
652
+ return o;
653
+ }, ls = (e, r) => {
654
+ if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] the server configuration must be an object");
655
+ const t = Mn(e.config), o = r.prepareScope();
656
+ I("authenticate", e.authenticate, !1), I("principalKey", e.principalKey, !1), I("document", e.document, !1), I("asset", e.asset, !1), I("signedOutPage", e.signedOutPage, !1), I("notices", e.notices, !0), I("onTreeRefreshed", e.onTreeRefreshed, !0), I("readSettings", e.readSettings, !1);
657
+ const c = zn(e.sources), u = nt(
658
+ t,
659
+ c.map((n) => n.id)
660
+ ), f = e.logger;
661
+ if (f !== void 0 && (f === null || typeof f != "object" || typeof f.error != "function"))
662
+ throw new TypeError("[markdown-explorer] logger must be an object with an error function");
663
+ const p = e.logger === void 0 ? sn : e.logger, h = xt(e.deny), T = e.deferredTimeoutMs === void 0 ? Pn : G("deferredTimeoutMs", e.deferredTimeoutMs, Ct), m = e.textMaxBytes === void 0 ? Ke : G("textMaxBytes", e.textMaxBytes, Qe), b = Qn(e.edit);
664
+ if (b === void 0 && e.editMaxBytes !== void 0) throw new TypeError("[markdown-explorer] editMaxBytes needs the edit ports");
665
+ const E = e.editMaxBytes === void 0 ? Ke : G("editMaxBytes", e.editMaxBytes, Qe), O = Zn(t, e.documentIds), P = Fn(e.treeCache), U = () => Date.now(), H = P === !1 ? pn(U) : fn({ ...P, now: U }), z = r.createSanitizer({ options: e.sanitizer, maxPanels: t.multiView.maxPanels, iframeHosts: t.iframeHosts, dataPath: t.dataPath, ownUrls: st(t) }), X = e.readSettings, N = e.assetMaxRangeBytes === null ? null : G("assetMaxRangeBytes", e.assetMaxRangeBytes, Number.MAX_SAFE_INTEGER), j = new Map(c.map((n) => [n.id, n])), de = ot(t), { authenticate: K, principalKey: xe, signedOutPage: Ir, onTreeRefreshed: Ae } = e, Pr = (n, a) => {
666
+ if (typeof n.label == "string") return n.label;
667
+ const s = n.label(a);
668
+ if (typeof s != "string" || s.trim() === "") throw new TypeError(`[markdown-explorer] the label of source ${x(n.id)} must be a non-blank string`);
669
+ return s;
670
+ }, ue = (n, a) => n.cacheScope === "shared" ? n.id : `${n.id}\0${a}`, Y = (n, a) => {
671
+ const s = (d) => $(p, { operation: "boundary", sourceId: n.id, path: a, error: d });
672
+ let i;
673
+ try {
674
+ i = n.boundary.contains(a);
675
+ } catch (d) {
676
+ return s(d), !1;
677
+ }
678
+ return typeof i == "boolean" ? i : (Je(i, s), s(new TypeError(`[markdown-explorer] boundary.contains of source ${x(n.id)} must return a boolean; got ${x(i)}`)), !1);
679
+ }, le = async (n, a, s) => {
680
+ const { confirm: i } = n.boundary;
681
+ if (i === void 0) return { status: "inside", readPath: s };
682
+ let d;
683
+ try {
684
+ d = await i(a, s);
685
+ } catch (k) {
686
+ return { status: "error", failure: v(k, { operation: "boundary", sourceId: n.id, path: s }, a.signal, p) };
687
+ }
688
+ const l = (k) => ($(p, { operation: "boundary", sourceId: n.id, path: s, error: new TypeError(`[markdown-explorer] boundary.confirm of source ${x(n.id)} ${k}`) }), { status: "outside" });
689
+ if (d === null || typeof d != "object") return l(`must resolve to { inside, readPath? }; got ${d === null ? "null" : typeof d}`);
690
+ const { inside: w, readPath: y } = d;
691
+ return w === !1 ? { status: "outside" } : w !== !0 || typeof y != "string" ? l("must resolve to { inside: false } or { inside: true, readPath: string }") : !F(y) || h.deniesPath(y) ? ($(p, { operation: "boundary", sourceId: n.id, path: s, error: new RangeError(`[markdown-explorer] boundary.confirm of source ${x(n.id)} answered a readPath the explorer does not serve (unacceptable or denied)`) }), { status: "error", failure: { reason: "failed" } }) : { status: "inside", readPath: y };
692
+ }, J = async (n, a) => {
693
+ const s = c.filter((l) => Y(l, a));
694
+ if (s.length === 0) return { status: "error", failure: { reason: "forbidden" } };
695
+ const i = s.find((l) => l.boundary.confirm === void 0);
696
+ if (i !== void 0) return { status: "inside", readPath: a, sourceId: i.id };
697
+ let d = null;
698
+ for (const l of s) {
699
+ const w = await le(l, n, a);
700
+ if (w.status === "inside") return { status: "inside", readPath: w.readPath, sourceId: l.id };
701
+ w.status === "error" && d === null && (d = w.failure);
702
+ }
703
+ return { status: "error", failure: d === null ? { reason: "forbidden" } : d };
704
+ }, Se = async (n, a, s) => {
705
+ try {
706
+ return Ze(await e.asset(n, a, s, { delivery: "file" })), null;
707
+ } catch (i) {
708
+ return v(i, { operation: "asset", path: a }, n.signal, p);
709
+ }
710
+ }, Ie = async (n, a, s) => {
711
+ let i;
712
+ try {
713
+ i = await n.resolve(a, s);
714
+ } catch (y) {
715
+ return { status: "error", failure: v(y, { operation: "resolve-id" }, a.signal, p) };
716
+ }
717
+ const d = es(i);
718
+ if (d === void 0)
719
+ return $(p, { operation: "resolve-id", error: new TypeError('[markdown-explorer] documentIds.resolve must resolve to { kind: "unbound" } or { kind: "bound", path } with a document path that has a URL') }), { status: "error", failure: { reason: "failed" } };
720
+ if (d === null) return { status: "error", failure: { reason: "not-found" } };
721
+ if (h.deniesPath(d))
722
+ return Z(p, { operation: "resolve-id", path: d }), { status: "error", failure: { reason: "forbidden" } };
723
+ const l = await J(a, d);
724
+ if (l.status === "error") return l;
725
+ const w = await Se(a, d, l.readPath);
726
+ return w !== null ? { status: "error", failure: w } : { status: "resolved", path: d, sourceId: l.sourceId };
727
+ }, _r = async (n, a, s) => {
728
+ if (h.deniesPath(s))
729
+ return Z(p, { operation: "issue-id", path: s }), { status: "error", failure: { reason: "forbidden" } };
730
+ const i = await J(a, s);
731
+ if (i.status === "error") return i;
732
+ const d = await Se(a, s, i.readPath);
733
+ if (d !== null) return { status: "error", failure: d };
734
+ for (let l = 0; l < sr; l += 1) {
735
+ const w = $t((_) => crypto.getRandomValues(_));
736
+ let y;
737
+ try {
738
+ y = await n.issue(a, s, w);
739
+ } catch (_) {
740
+ return { status: "error", failure: v(_, { operation: "issue-id", path: s }, a.signal, p) };
741
+ }
742
+ const k = qn(y);
743
+ if (k === null)
744
+ return $(p, { operation: "issue-id", path: s, error: new TypeError('[markdown-explorer] documentIds.issue must resolve to { kind: "issued" }, { kind: "existing", id } with an ID in its canonical form, or { kind: "taken" }') }), { status: "error", failure: { reason: "failed" } };
745
+ if (k.kind === "issued") return { status: "ok", id: w };
746
+ if (k.kind === "existing") return { status: "ok", id: k.id };
747
+ }
748
+ return $(p, { operation: "issue-id", path: s, error: new Error(`[markdown-explorer] documentIds.issue answered taken for ${String(sr)} candidates in a row`) }), { status: "error", failure: { reason: "failed" } };
749
+ }, Pe = (n, a, s) => {
750
+ const i = ({ path: d, reason: l }) => cn(p, { operation: s.operation, sourceId: s.sourceId, path: d, error: new TypeError(`[markdown-explorer] an entry with ${l} was left out`) });
751
+ try {
752
+ return { status: "ok", entries: mn(n, h, a.children !== void 0, i, (d) => Y(a, d)) };
753
+ } catch (d) {
754
+ return $(p, { ...s, error: d }), { status: "error", failure: { reason: "failed" } };
755
+ }
756
+ }, Dr = async (n, a, s) => {
757
+ let i;
758
+ try {
759
+ i = await n.tree(a);
760
+ } catch (l) {
761
+ return { status: "error", failure: v(l, { operation: "tree", sourceId: n.id }, a.signal, p) };
762
+ }
763
+ const d = Pe(i, n, { operation: "tree", sourceId: n.id });
764
+ return d.status === "ok" ? { status: "ok", entries: d.entries, loadedAt: s } : d;
765
+ }, _e = (n, a, s, i) => (d, l) => Dr(n, { principal: a, request: s, signal: d, refresh: i }, l), De = (n, a, s, i, d) => H.load(ue(n, s), d, _e(n, a, i, !1)), $r = (n, a, s, i) => H.refresh(ue(n, s), i.signal, _e(n, a, i, !0)), Nr = (n, a) => {
766
+ if (Ae === void 0) return;
767
+ const s = (i) => $(p, { operation: "refresh", sourceId: n.id, error: i });
768
+ try {
769
+ Je(Ae(a), s);
770
+ } catch (i) {
771
+ s(i);
772
+ }
773
+ }, Lr = async (n, a, s, i) => {
774
+ if (h.deniesPath(i) || !Y(n, i)) return { status: "error", failure: { reason: "forbidden" } };
775
+ const d = await le(n, s, i);
776
+ if (d.status === "outside") return { status: "error", failure: { reason: "forbidden" } };
777
+ if (d.status === "error") return { status: "error", failure: d.failure };
778
+ let l;
779
+ try {
780
+ l = await a(s, i, d.readPath);
781
+ } catch (w) {
782
+ return { status: "error", failure: v(w, { operation: "children", sourceId: n.id, path: i }, s.signal, p) };
783
+ }
784
+ return Pe(l, n, { operation: "children", sourceId: n.id, path: i });
785
+ }, $e = async (n, a, s, i) => {
786
+ const d = await le(n, s, i);
787
+ if (d.status === "outside") return { status: "ok", ancestors: null };
788
+ if (d.status === "error") return { status: "error", failure: d.failure };
789
+ let l;
790
+ try {
791
+ l = await a(s, i, d.readPath, { maxDepth: t.revealDocument.maxDepth });
792
+ } catch (w) {
793
+ return { status: "error", failure: v(w, { operation: "ancestors", sourceId: n.id, path: i }, s.signal, p) };
794
+ }
795
+ if (Array.isArray(l) && l.length > t.revealDocument.maxDepth) return { status: "ok", ancestors: null };
796
+ try {
797
+ return { status: "ok", ancestors: wn(l, i, h, (w) => Y(n, w)) };
798
+ } catch (w) {
799
+ return $(p, { operation: "ancestors", sourceId: n.id, path: i, error: w }), { status: "error", failure: { reason: "failed" } };
800
+ }
801
+ }, jr = async (n, a, s, i) => h.deniesPath(i) ? { status: "error", failure: { reason: "forbidden" } } : Y(n, i) ? $e(n, a, s, i) : { status: "ok", ancestors: null }, Mr = async (n, a, s) => {
802
+ if (h.deniesPath(s)) return { status: "error", failure: { reason: "forbidden" } };
803
+ for (const i of [n, ...c.filter((d) => d !== n)]) {
804
+ if (a.signal.aborted) break;
805
+ const d = i.ancestors;
806
+ if (d === void 0 || !Y(i, s)) continue;
807
+ const l = await $e(i, d, a, s);
808
+ if (l.status === "ok" && l.ancestors !== null) return { status: "ok", source: i.id, ancestors: l.ancestors };
809
+ }
810
+ return Dn;
811
+ }, Ne = async (n, a, s) => {
812
+ if (h.deniesPath(s)) return V("forbidden");
813
+ const i = await J(n, s);
814
+ if (i.status === "error") return { kind: "failure", failure: i.failure };
815
+ let d;
816
+ try {
817
+ d = await e.document(n, s, i.readPath);
818
+ } catch (y) {
819
+ return { kind: "failure", failure: v(y, { operation: "document", path: s }, n.signal, p) };
820
+ }
821
+ let l;
822
+ try {
823
+ l = En(d, (y) => He(t.dataPath, s, y), b !== void 0);
824
+ } catch (y) {
825
+ return $(p, { operation: "document", path: s, error: y }), V("failed");
826
+ }
827
+ if (l.kind !== "unsanitized-markdown") return l;
828
+ const w = await z(l.html, { scope: a, signal: n.signal });
829
+ return w.status === "sanitized" ? { kind: "markdown", name: l.name, htmlContent: w.html, headings: l.headings, lang: l.lang, edit: l.edit } : (w.cause !== null && $(p, { operation: "document", path: s, error: w.cause }), V(w.reason));
830
+ }, Cr = async (n) => {
831
+ if (e.notices === void 0) return we;
832
+ try {
833
+ return In(await e.notices(n));
834
+ } catch (a) {
835
+ return v(a, { operation: "notices" }, n.signal, p), we;
836
+ }
837
+ }, Le = async (n, a, s, i) => {
838
+ const d = C(a, M.path);
839
+ if (d === null || !F(d)) return { status: "answered", response: R({ reason: "invalid" }, s) };
840
+ const l = Dt(a);
841
+ if (l === null || !i.has(l)) return { status: "answered", response: R({ reason: "invalid" }, s) };
842
+ if (h.deniesPath(d))
843
+ return Z(p, { operation: "asset", path: d }), { status: "answered", response: R({ reason: "forbidden" }, s) };
844
+ const w = await J(n, d);
845
+ if (w.status === "error") return { status: "answered", response: R(w.failure, s) };
846
+ try {
847
+ const y = await e.asset(n, d, w.readPath, { delivery: l }), k = l === "file" ? Ze(y) : Ee(y);
848
+ return "kind" in k ? { status: "answered", response: nn(k.url, s) } : { status: "admitted", path: d, display: l, file: k };
849
+ } catch (y) {
850
+ return { status: "answered", response: R(v(y, { operation: "asset", path: d }, n.signal, p), s) };
851
+ }
852
+ }, zr = async (n, a, s) => {
853
+ const i = await Le(n, a, s, Nn);
854
+ if (i.status === "answered") return i.response;
855
+ const { path: d, display: l, file: w } = i;
856
+ try {
857
+ return l === "text" ? await qt(n.request, w, s, t.legacyTextEncoding, N) : l === "workbook" ? await rn(n.request, w, s) : await Kt(n.request, w, s, N);
858
+ } catch (y) {
859
+ return R(v(y, { operation: "asset", path: d }, n.signal, p), s);
860
+ }
861
+ }, Fr = async (n, a, s) => {
862
+ const i = Or(n, a, s, t.legacyTextEncoding, N);
863
+ return i.kind === "respond" ? i : be(i.selection, await Rr(a, t.legacyTextEncoding));
864
+ }, Ur = async (n, a, s) => {
865
+ const i = await Le(n, a, s, Ln);
866
+ if (i.status === "answered") return { kind: "response", response: i.response };
867
+ const { path: d, display: l, file: w } = i, y = (D) => R(v(D, { operation: "asset", path: d }, n.signal, p), s);
868
+ let k;
869
+ try {
870
+ k = l === "text" ? await Fr(n.request, w, s) : kr(n.request, w, s, N);
871
+ } catch (D) {
872
+ return { kind: "response", response: y(D) };
873
+ }
874
+ if (k.kind === "respond") return { kind: "response", response: k.response };
875
+ const { bridge: _ } = w;
876
+ return _ === void 0 ? ($(p, { operation: "asset", path: d, error: new TypeError("[markdown-explorer] the asset port must attach a bridge to a file the host streams itself") }), { kind: "response", response: R({ reason: "failed" }, s) }) : { kind: "file", status: k.status, headers: k.headers, bridge: { uri: _.uri, storageVersion: _.storageVersion }, range: k.range, length: k.length, fail: (D) => y(Hn(_.readFailure, D)) };
877
+ }, Hr = async (n, a) => {
878
+ if (h.deniesPath(a))
879
+ return Z(p, { operation: "text", path: a }), V("forbidden");
880
+ const s = await J(n, a);
881
+ if (s.status === "error") return { kind: "failure", failure: s.failure };
882
+ try {
883
+ const i = Ee(await e.asset(n, a, s.readPath, { delivery: "text" })), d = await un(i, m, t.legacyTextEncoding);
884
+ return d === null ? V("unsupported") : { kind: "text", name: i.name, text: d.text, truncated: d.truncated, url: He(t.dataPath, a, i.version) };
885
+ } catch (i) {
886
+ return { kind: "failure", failure: v(i, { operation: "text", path: a }, n.signal, p) };
887
+ }
888
+ }, Q = async (n, a, s) => h.deniesPath(s) ? (Z(p, { operation: a, path: s }), { status: "error", failure: { reason: "forbidden" } }) : J(n, s), Xr = async (n, a, s) => {
889
+ const i = await Q(a, "edit", s);
890
+ if (i.status === "error") return { kind: "failure", failure: i.failure };
891
+ try {
892
+ return Rn(await n.source(a, s, i.readPath), E);
893
+ } catch (d) {
894
+ return { kind: "failure", failure: v(d, { operation: "edit", path: s }, a.signal, p) };
895
+ }
896
+ }, Br = async (n, a, s, i, d) => {
897
+ const l = await Q(a, "save", s);
898
+ if (l.status === "error") return { kind: "failure", failure: l.failure };
899
+ try {
900
+ return On(await n.save(a, s, l.readPath, { text: d, baseVersion: i }), E);
901
+ } catch (w) {
902
+ return { kind: "failure", failure: v(w, { operation: "save", path: s }, a.signal, p) };
903
+ }
904
+ }, Vr = async (n, a, s, i, d) => {
905
+ const l = await Q(a, "preview", i);
906
+ if (l.status === "error") return { kind: "failure", failure: l.failure };
907
+ let w;
908
+ try {
909
+ w = vn(await n.preview(a, i, l.readPath, d));
910
+ } catch (k) {
911
+ return { kind: "failure", failure: v(k, { operation: "preview", path: i }, a.signal, p) };
912
+ }
913
+ if ("kind" in w) return w.kind === "failure" ? w : V("failed");
914
+ const y = await z(w.html, { scope: s, signal: a.signal });
915
+ return y.status === "sanitized" ? { kind: "preview", htmlContent: y.html, headings: w.headings } : (y.cause !== null && $(p, { operation: "preview", path: i, error: y.cause }), V(y.reason));
916
+ }, Gr = async (n, a, s) => {
917
+ const i = await Q(a, "revisions", s);
918
+ if (i.status === "error") return { kind: "failure", failure: i.failure };
919
+ try {
920
+ return { kind: "revisions", revisions: xn(await n.revisions(a, s, i.readPath)) };
921
+ } catch (d) {
922
+ return { kind: "failure", failure: v(d, { operation: "revisions", path: s }, a.signal, p) };
923
+ }
924
+ }, Wr = async (n, a, s, i) => {
925
+ const d = await Q(a, "revision", s);
926
+ if (d.status === "error") return { kind: "failure", failure: d.failure };
927
+ try {
928
+ return { kind: "revision", id: i, text: An(await n.revision(a, s, d.readPath, i), E) };
929
+ } catch (l) {
930
+ return { kind: "failure", failure: v(l, { operation: "revision", path: s }, a.signal, p) };
931
+ }
932
+ }, Yr = async (n, a, s, i, d, l) => {
933
+ const w = C(d, M.path);
934
+ if (w === null || !F(w)) return R({ reason: "invalid" }, l);
935
+ if (a === "edit") return S(200, JSON.stringify(await Xr(n, s, w)), l);
936
+ if (a === "revisions") return S(200, JSON.stringify(await Gr(n, s, w)), l);
937
+ if (a === "revision") {
938
+ const _ = C(d, M.revision);
939
+ return ee(_) ? S(200, JSON.stringify(await Wr(n, s, w, _)), l) : R({ reason: "invalid" }, l);
940
+ }
941
+ const y = C(d, M.base);
942
+ if (a === "save" && !ee(y)) return R({ reason: "invalid" }, l);
943
+ const k = await Kn(s.request, E);
944
+ return k.status === "error" ? R(k.failure, l) : a === "preview" ? S(200, JSON.stringify(await Vr(n, s, i, w, k.text)), l) : S(200, JSON.stringify(await Br(n, s, w, y, k.text)), l);
945
+ }, Jr = async ({ request: n, url: a, params: s }) => {
946
+ const i = tr(await K(n, er));
947
+ if (i.status === "forbidden") throw rt("forbidden", { headers: me(i.headers) });
948
+ const d = me(i.headers);
949
+ if (d.set("Cache-Control", Sr), i.status === "signed-out") throw Un("signedOutPage", Ir({ request: n, url: a }, d));
950
+ const l = ct(u, s["*"], a.searchParams);
951
+ if (l.kind === "redirect") throw Fe(l.href, { headers: d });
952
+ const { principal: w } = i, y = nr(o, xe(w));
953
+ if (l.kind === "document-id") {
954
+ if (O === void 0) throw new TypeError("[markdown-explorer] an ID URL was resolved without the documentIds ports");
955
+ const k = l.id === null ? jn : await Ie(O, { principal: w, request: n, signal: n.signal, refresh: !1 }, l.id);
956
+ if (k.status === "resolved") throw Fe(Kr(l.opens, k), { headers: d });
957
+ return Ue(je(w, y, n, l.location, { id: l.id, failure: k.failure }), { status: fr[k.failure.reason], headers: d });
958
+ }
959
+ return Ue(je(w, y, n, l.location, null), { headers: d });
960
+ }, Kr = (n, a) => dt(u, ut(n, a.path, a.sourceId)), je = (n, a, s, i, d) => {
961
+ const l = j.get(i.source);
962
+ if (l === void 0) throw new RangeError(`[markdown-explorer] no source for ${x(i.source)}`);
963
+ const w = { signal: s.signal, timeoutMs: T, late: null, handOverMs: T };
964
+ return {
965
+ scope: a,
966
+ sources: c.map((y) => ({ id: y.id, label: Pr(y, n) })),
967
+ settings: lt(Xn(X, s), de),
968
+ tree: i.view === "single" ? null : {
969
+ sourceId: i.source,
970
+ result: pe(w, (y) => De(l, n, a, s, y).then((k) => k.result))
971
+ },
972
+ documents: Bn(i).map((y) => ({ path: y, document: pe(w, (k) => Ne({ principal: n, request: s, signal: k, refresh: !1 }, a, y)) })),
973
+ notices: pe({ signal: s.signal, timeoutMs: T, late: we, handOverMs: 0 }, (y) => Cr({ principal: n, request: s, signal: y, refresh: !1 })),
974
+ documentId: d
975
+ };
976
+ }, Me = async (n, a) => {
977
+ const s = tr(await K(n, a));
978
+ return { authentication: s, headers: me(s.headers) };
979
+ }, Ce = async (n) => {
980
+ let a;
981
+ try {
982
+ a = await Me(n, er);
983
+ } catch (d) {
984
+ return { status: "answered", response: R(v(rr(d), { operation: "authenticate" }, n.signal, p)) };
985
+ }
986
+ const { authentication: s, headers: i } = a;
987
+ return s.status === "signed-out" ? { status: "answered", response: R({ reason: "unauthorized" }, i) } : s.status === "forbidden" ? { status: "answered", response: R({ reason: "forbidden" }, i) } : { status: "signed-in", principal: s.principal, headers: i };
988
+ }, Qr = async (n, a, s) => {
989
+ const i = await Ce(a);
990
+ if (i.status === "answered") return i.response;
991
+ const { principal: d, headers: l } = i;
992
+ if (n === "asset") return zr({ principal: d, request: a, signal: a.signal, refresh: !1 }, s, l);
993
+ const w = nr(o, xe(d));
994
+ l.set(_t, w);
995
+ const y = { principal: d, request: a, signal: a.signal, refresh: !1 }, k = () => R({ reason: "invalid" }, l);
996
+ if (n === "document") {
997
+ const A = C(s, M.path);
998
+ if (A === null || !F(A)) return k();
999
+ const B = a.headers.has(ce);
1000
+ return B && !ar(a) ? R({ reason: "forbidden" }, l) : S(200, JSON.stringify(await Ne({ ...y, refresh: B }, w, A)), l);
1001
+ }
1002
+ if (n === "text") {
1003
+ const A = C(s, M.path);
1004
+ return A === null || !F(A) ? k() : S(200, JSON.stringify(await Hr(y, A)), l);
1005
+ }
1006
+ if (n === "edit" || n === "save" || n === "preview" || n === "revisions" || n === "revision")
1007
+ return b === void 0 ? R({ reason: "not-found" }, l) : Yr(b, n, y, w, s, l);
1008
+ if (n === "issue-id") {
1009
+ if (O === void 0) return R({ reason: "not-found" }, l);
1010
+ const A = C(s, M.path);
1011
+ return A === null || !dr(A) ? k() : ir(await _r(O, y, A), l);
1012
+ }
1013
+ if (n === "resolve-id") {
1014
+ if (O === void 0) return R({ reason: "not-found" }, l);
1015
+ const A = C(s, M.id);
1016
+ if (A === null || !pr(A)) return k();
1017
+ const B = await Ie(O, y, A);
1018
+ return ir(B.status === "resolved" ? { status: "ok", path: B.path, source: B.sourceId } : B, l);
1019
+ }
1020
+ const _ = C(s, M.source), D = C(s, M.path);
1021
+ if (_ === null || (n === "children" || n === "ancestors" || n === "reveal") && (D === null || !F(D))) return k();
1022
+ const L = j.get(_);
1023
+ if (L === void 0) return R({ reason: "not-found" }, l);
1024
+ if (n === "tree") return S(200, (await De(L, d, w, a, a.signal)).json, l);
1025
+ if (n === "refresh") {
1026
+ const A = await $r(L, d, w, a);
1027
+ return a.signal.aborted || Nr(L, ue(L, w)), S(200, A.json, l);
1028
+ }
1029
+ return n === "ancestors" ? L.ancestors === void 0 || D === null ? R({ reason: "not-found" }, l) : S(200, JSON.stringify(await jr(L, L.ancestors, y, D)), l) : n === "reveal" ? D === null ? k() : S(200, JSON.stringify(await Mr(L, y, D)), l) : L.children === void 0 || D === null ? R({ reason: "not-found" }, l) : S(200, JSON.stringify(await Lr(L, L.children, y, D)), l);
1030
+ }, Zr = async (n) => {
1031
+ const { authentication: a, headers: s } = await Me(n, $n);
1032
+ if (!s.keys().next().done) throw new TypeError("[markdown-explorer] authenticate returned headers in read-only mode; a read-only authentication must only read the session (none was forwarded)");
1033
+ return a.status === "signed-in";
1034
+ }, ze = t.embeds.linkCardEndpoint === null ? null : r.createLinkCardHandler({ authorize: Zr }), qr = async (n, a) => {
1035
+ try {
1036
+ return await n(a);
1037
+ } catch (s) {
1038
+ return R(v(rr(s), { operation: "authenticate" }, a.signal, p));
1039
+ }
1040
+ }, fe = async (n, a, s) => {
1041
+ if (new URL(n.url).pathname.endsWith(".data")) return R({ reason: "not-found" });
1042
+ if (!At(s)) return R({ reason: "not-found" });
1043
+ if (s === "link-card") {
1044
+ if (ze === null) return R({ reason: "not-found" });
1045
+ const d = or(n, s);
1046
+ return d !== null ? d : qr(ze, n);
1047
+ }
1048
+ if (Wn.has(s) && b === void 0) return R({ reason: "not-found" });
1049
+ if (Gn.has(s) && O === void 0) return R({ reason: "not-found" });
1050
+ const i = or(n, s);
1051
+ if (i !== null) return i;
1052
+ if (s === "refresh" && !ar(n)) return R({ reason: "forbidden" });
1053
+ if ((s === "save" || s === "preview") && !Yn(n)) return R({ reason: "forbidden" });
1054
+ if (s === "issue-id" && !Jn(n)) return R({ reason: "forbidden" });
1055
+ try {
1056
+ return await Qr(s, n, a.searchParams);
1057
+ } catch (d) {
1058
+ return R(v(d, { operation: s }, n.signal, p));
1059
+ }
1060
+ }, et = async (n, a, s) => {
1061
+ if (s !== "asset" || n.method.toUpperCase() !== "GET" || new URL(n.url).pathname.endsWith(".data")) return { kind: "response", response: await fe(n, a, s) };
1062
+ try {
1063
+ const i = await Ce(n);
1064
+ return i.status === "answered" ? { kind: "response", response: i.response } : await Ur({ principal: i.principal, request: n, signal: n.signal, refresh: !1 }, a.searchParams, i.headers);
1065
+ } catch (i) {
1066
+ return { kind: "response", response: R(v(i, { operation: "asset" }, n.signal, p)) };
1067
+ }
1068
+ };
1069
+ return Object.freeze({
1070
+ loader: Jr,
1071
+ headers: rs,
1072
+ dataLoader: ({ request: n, url: a, params: s }) => fe(n, a, s["*"]),
1073
+ dataAction: ({ request: n, url: a, params: s }) => fe(n, a, s["*"]),
1074
+ planData: ({ request: n, url: a, params: s }) => et(n, a, s["*"]),
1075
+ forgetTree: (n) => {
1076
+ if (typeof n != "string") throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${x(n)}`);
1077
+ H.forget(n);
1078
+ }
1079
+ });
1080
+ };
1081
+ export {
1082
+ ye as A,
1083
+ us as E,
1084
+ ls as c
1085
+ };