@vite-hub/comments 0.0.0 → 0.3.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 (77) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +291 -0
  3. package/dist/anchor.d.ts +43 -0
  4. package/dist/anchor.js +133 -0
  5. package/dist/client-diagnostics-CcFpkbAk.js +40 -0
  6. package/dist/client.d.ts +176 -0
  7. package/dist/client.js +738 -0
  8. package/dist/console-h4KlhIik.d.ts +332 -0
  9. package/dist/context-BqIsmYP1.js +61 -0
  10. package/dist/database/postgres.d.ts +1402 -0
  11. package/dist/database/postgres.js +81 -0
  12. package/dist/database-CA1aHKN7.d.ts +1495 -0
  13. package/dist/database.d.ts +12 -0
  14. package/dist/database.js +2 -0
  15. package/dist/define-43mMR39K.js +89 -0
  16. package/dist/define-B3TF9zzn.d.ts +204 -0
  17. package/dist/errors-4gelGVmK.js +57 -0
  18. package/dist/errors-C6qptPoG.js +135 -0
  19. package/dist/errors-CyQyKAvy.d.ts +185 -0
  20. package/dist/fold-name-B7Zb3-MF.js +7 -0
  21. package/dist/identity-CBOzgxSf.js +39 -0
  22. package/dist/index-DNhy69Wt.d.ts +83 -0
  23. package/dist/index.d.ts +7 -0
  24. package/dist/index.js +196 -0
  25. package/dist/install-BcMPgPk_.js +1154 -0
  26. package/dist/install-W9ghhGoh.d.ts +36 -0
  27. package/dist/installed-B-PfERBU.js +30 -0
  28. package/dist/invariant-D8_xBqmZ.js +22 -0
  29. package/dist/migrate-B0k_0swk.d.ts +54 -0
  30. package/dist/migrate-BDQ8xqUs.js +289 -0
  31. package/dist/object-Da1zyPCR.js +11 -0
  32. package/dist/operations-D4A1Fcgf.d.ts +160 -0
  33. package/dist/operations-DMMIfYPW.js +1159 -0
  34. package/dist/operations-GLeOqgMt.d.ts +257 -0
  35. package/dist/operations.d.ts +3 -0
  36. package/dist/operations.js +3 -0
  37. package/dist/overlay/client-DmsSMOzi.js +4 -0
  38. package/dist/overlay/dist-BoHMOFax.js +14 -0
  39. package/dist/overlay/dist-yIZmvSaU.js +1 -0
  40. package/dist/overlay/overlay.js +201 -0
  41. package/dist/page/loader.js +142 -0
  42. package/dist/page-B41ozN63.js +40 -0
  43. package/dist/page-DtbMOEMd.d.ts +22 -0
  44. package/dist/page-tools-shared-NHUjKI8E.js +117 -0
  45. package/dist/path--zk6PEMz.js +18 -0
  46. package/dist/plugin-PS8PMYus.js +74 -0
  47. package/dist/realtime.d.ts +12 -0
  48. package/dist/realtime.js +47 -0
  49. package/dist/rpc-HBcWtg0T.d.ts +17 -0
  50. package/dist/rpc-RKPAusHp.js +153 -0
  51. package/dist/rpc.d.ts +2 -0
  52. package/dist/rpc.js +2 -0
  53. package/dist/runtime/auth.d.ts +8 -0
  54. package/dist/runtime/auth.js +18 -0
  55. package/dist/runtime/connect/node.d.ts +1 -0
  56. package/dist/runtime/connect/node.js +2 -0
  57. package/dist/runtime/connect.d.ts +1 -0
  58. package/dist/runtime/connect.js +2 -0
  59. package/dist/runtime/console.d.ts +5 -0
  60. package/dist/runtime/console.js +64 -0
  61. package/dist/runtime/index.d.ts +270 -0
  62. package/dist/runtime/index.js +1113 -0
  63. package/dist/server-D8k-0GXe.js +72 -0
  64. package/dist/server.d.ts +20 -0
  65. package/dist/server.js +7 -0
  66. package/dist/service-CFVm23k7.d.ts +158 -0
  67. package/dist/service-GHhhyQj4.js +609 -0
  68. package/dist/session-DVx-1Tym.d.ts +14 -0
  69. package/dist/session-EkudzUmm.js +503 -0
  70. package/dist/testing.d.ts +30 -0
  71. package/dist/testing.js +187 -0
  72. package/dist/tokens-DSbwkVSy.js +58 -0
  73. package/dist/types-BIS0hCEl.d.ts +124 -0
  74. package/dist/types-CZujrMFd.d.ts +322 -0
  75. package/dist/vite.d.ts +308 -0
  76. package/dist/vite.js +1660 -0
  77. package/package.json +153 -4
@@ -0,0 +1,503 @@
1
+ import { o as normalizeCommentPage } from "./page-B41ozN63.js";
2
+ import { c as viteHubPageToolsInlineStart, f as viteHubPageToolsWanted, l as viteHubPageToolsLoader, n as viteHubBasePath, o as viteHubPageToolsHintCookie, p as withViteHubBase, r as viteHubPageSessionPath, s as viteHubPageToolsInlineScript, t as readViteHubPageAccount, u as viteHubPageToolsMarker } from "./page-tools-shared-NHUjKI8E.js";
3
+ import { getStandardContext } from "@vite-hub/runtime/internal/h3";
4
+ //#region ../internal/src/runtime/page-tools-html.ts
5
+ /** The effective script-element directive is shared by HTTP and HTML meta policies. */
6
+ function scriptPolicyNonce(policy) {
7
+ const directives = policy.split(";").map((part) => part.trim());
8
+ const directive = [
9
+ "script-src-elem",
10
+ "script-src",
11
+ "default-src"
12
+ ].map((name) => directives.find((part) => part.toLowerCase().startsWith(`${name} `))).find(Boolean);
13
+ return directive ? /'nonce-([\w+/=-]+)'/.exec(directive)?.[1] : void 0;
14
+ }
15
+ function metaNonce(token) {
16
+ const attributes = /* @__PURE__ */ new Map();
17
+ for (const match of token.slice(5, -1).matchAll(/([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g)) {
18
+ const name = match[1].toLowerCase();
19
+ if (!attributes.has(name)) attributes.set(name, match[2] ?? match[3] ?? match[4] ?? "");
20
+ }
21
+ return attributes.get("http-equiv")?.toLowerCase() === "content-security-policy" ? scriptPolicyNonce(attributes.get("content") ?? "") : void 0;
22
+ }
23
+ function tagNonce(script) {
24
+ return / nonce="([\w+/=-]+)"/.exec(script.slice(0, script.indexOf(">")))?.[1];
25
+ }
26
+ function isGeneratedCheck(inline) {
27
+ const at = inline.indexOf("import(");
28
+ if (at === -1) return false;
29
+ try {
30
+ const path = JSON.parse(inline.slice(at + 7, -1));
31
+ const nonce = tagNonce(inline);
32
+ return typeof path === "string" && path.endsWith("/_vitehub/page/assets/loader.js?v=21") && viteHubPageToolsInlineScript(path.slice(0, -36), nonce) === `${inline}<\/script>`;
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+ /** A tag ends at an unquoted `>`, so markup quoted in an attribute stays untouched. */
38
+ function tagEnd(text) {
39
+ let quote = "";
40
+ for (let index = 1; index < text.length; index++) {
41
+ const character = text[index];
42
+ if (quote) {
43
+ if (character === quote) quote = "";
44
+ } else if (character === "\"" || character === "'") quote = character;
45
+ else if (character === ">") return index + 1;
46
+ }
47
+ return -1;
48
+ }
49
+ /** Scan HTML tokens across chunks; only active script elements can own the loader marker. */
50
+ function pageToolsHtmlTransform(loader) {
51
+ const decoder = new TextDecoder();
52
+ const encoder = new TextEncoder();
53
+ let pending = "";
54
+ let opaqueEnd;
55
+ let rawText = "";
56
+ let inline = "";
57
+ let templates = 0;
58
+ let present = false;
59
+ let done = false;
60
+ return new TransformStream({
61
+ transform(chunk, controller) {
62
+ pending += decoder.decode(chunk, { stream: true });
63
+ const emit = (text) => {
64
+ if (text) controller.enqueue(encoder.encode(text));
65
+ };
66
+ while (pending) {
67
+ if (done) {
68
+ emit(pending);
69
+ pending = "";
70
+ return;
71
+ }
72
+ if (opaqueEnd) {
73
+ const end = opaqueEnd.exec(pending);
74
+ const length = end ? end.index + end[0].length : Math.max(0, pending.length - 3);
75
+ emit(pending.slice(0, length));
76
+ pending = pending.slice(length);
77
+ if (!end) return;
78
+ opaqueEnd = void 0;
79
+ continue;
80
+ }
81
+ if (rawText) {
82
+ if (rawText === "plaintext") {
83
+ emit(pending);
84
+ pending = "";
85
+ return;
86
+ }
87
+ const end = new RegExp(`</${rawText}(?=[\\t\\n\\f\\r />])`, "i").exec(pending);
88
+ const length = end ? end.index : Math.max(0, pending.length - rawText.length - 3);
89
+ if (inline) inline += pending.slice(0, length);
90
+ else emit(pending.slice(0, length));
91
+ pending = pending.slice(length);
92
+ if (!end) return;
93
+ const finish = tagEnd(pending);
94
+ if (finish === -1) return;
95
+ if (inline) {
96
+ if (isGeneratedCheck(inline)) {
97
+ const nonce = tagNonce(inline);
98
+ emit(nonce && !tagNonce(loader) ? loader.replace(` ${viteHubPageToolsMarker}`, ` nonce="${nonce}" ${viteHubPageToolsMarker}`) : loader);
99
+ } else emit(inline + pending.slice(0, finish));
100
+ inline = "";
101
+ present = true;
102
+ } else emit(pending.slice(0, finish));
103
+ pending = pending.slice(finish);
104
+ rawText = "";
105
+ continue;
106
+ }
107
+ const start = pending.indexOf("<");
108
+ if (start === -1) {
109
+ emit(pending);
110
+ pending = "";
111
+ return;
112
+ }
113
+ emit(pending.slice(0, start));
114
+ pending = pending.slice(start);
115
+ if ("<!--".startsWith(pending) || "<![CDATA[".startsWith(pending)) return;
116
+ if (pending.startsWith("<!--") || pending.startsWith("<![CDATA[")) {
117
+ opaqueEnd = pending.startsWith("<!--") ? /--!?>/ : /\]\]>/;
118
+ const length = pending.startsWith("<!--") ? 4 : 9;
119
+ emit(pending.slice(0, length));
120
+ pending = pending.slice(length);
121
+ continue;
122
+ }
123
+ if (!/^<[a-z!/?]/i.test(pending)) {
124
+ emit("<");
125
+ pending = pending.slice(1);
126
+ continue;
127
+ }
128
+ const finish = tagEnd(pending);
129
+ if (finish === -1) return;
130
+ const token = pending.slice(0, finish);
131
+ pending = pending.slice(finish);
132
+ const match = /^<(\/?)([a-z][a-z0-9:-]*)(?=[\t\n\f\r />])/i.exec(token);
133
+ const name = match?.[2]?.toLowerCase();
134
+ const closing = match?.[1] === "/";
135
+ if (name === "template") templates = Math.max(0, templates + (closing ? -1 : 1));
136
+ if (name === "meta" && !closing && !templates && !tagNonce(loader)) {
137
+ const nonce = metaNonce(token);
138
+ if (nonce) loader = loader.replace(` ${viteHubPageToolsMarker}`, ` nonce="${nonce}" ${viteHubPageToolsMarker}`);
139
+ }
140
+ if (name === "body" && closing && !templates) {
141
+ if (!present) emit(loader);
142
+ done = true;
143
+ }
144
+ if (!closing && name && /^(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript|plaintext)$/.test(name)) {
145
+ rawText = name;
146
+ if (!templates && token.replace(/ nonce="[\w+/=-]+"/, "") === viteHubPageToolsInlineStart) {
147
+ inline = token;
148
+ present = true;
149
+ continue;
150
+ }
151
+ if (!templates && name === "script") {
152
+ const attributes = token.replace(/"[^"]*"|'[^']*'/g, "");
153
+ present ||= new RegExp(`\\s${viteHubPageToolsMarker}(?=[\\s=/>])`, "i").test(attributes);
154
+ }
155
+ }
156
+ emit(token);
157
+ }
158
+ },
159
+ flush(controller) {
160
+ const rest = inline + pending + decoder.decode();
161
+ controller.enqueue(encoder.encode(rest + (done || present ? "" : loader)));
162
+ }
163
+ });
164
+ }
165
+ //#endregion
166
+ //#region ../internal/src/runtime/request-origin.ts
167
+ function firstHeaderValue(headers, name) {
168
+ return headers.get(name)?.split(",", 1)[0]?.trim() || void 0;
169
+ }
170
+ /**
171
+ * The origin that the client used for `request`. A TLS-terminating proxy sends the client scheme in
172
+ * `X-Forwarded-Proto` and the client host in `X-Forwarded-Host`. Each proxy appends its value, so the first value wins.
173
+ * Without these headers, or with values that are not valid, the result is the origin of `request.url`.
174
+ */
175
+ function forwardedRequestOrigin(request) {
176
+ const url = new URL(request.url);
177
+ const forwardedProtocol = firstHeaderValue(request.headers, "x-forwarded-proto")?.toLowerCase();
178
+ const protocol = forwardedProtocol === "http" || forwardedProtocol === "https" ? forwardedProtocol : url.protocol.slice(0, -1);
179
+ const host = firstHeaderValue(request.headers, "x-forwarded-host") ?? url.host;
180
+ if (/[\u0000-\u001F\s/\\?#@]/.test(host)) return url.origin;
181
+ try {
182
+ return new URL(`${protocol}://${host}`).origin;
183
+ } catch {
184
+ return url.origin;
185
+ }
186
+ }
187
+ //#endregion
188
+ //#region ../internal/src/runtime/page-tools.ts
189
+ const stateKey = Symbol.for("vitehub.page-tools");
190
+ const scope = globalThis;
191
+ function state() {
192
+ return scope[stateKey] ??= {
193
+ installed: /* @__PURE__ */ new WeakSet(),
194
+ tools: /* @__PURE__ */ new WeakMap(),
195
+ apps: /* @__PURE__ */ new WeakMap(),
196
+ bases: /* @__PURE__ */ new WeakMap()
197
+ };
198
+ }
199
+ /** Registers a page tool for one Nitro app, before or after installation. The same id replaces only that app's tool. */
200
+ function registerViteHubPageTool(nitroApp, tool) {
201
+ if (nitroApp === null || typeof nitroApp !== "object") return;
202
+ const { tools } = state();
203
+ let registry = tools.get(nitroApp);
204
+ if (!registry) {
205
+ registry = /* @__PURE__ */ new Map();
206
+ tools.set(nitroApp, registry);
207
+ }
208
+ registry.set(tool.id, tool);
209
+ const grants = state().grants ??= /* @__PURE__ */ new Map();
210
+ for (const grant of tool.grants ?? []) grants.set(grant.id, grant);
211
+ }
212
+ /** The account of a visitor, or `undefined` without a reader, without a session, or when the reader fails. */
213
+ async function readAccount(nitroApp, request) {
214
+ const read = state().accounts?.get(nitroApp);
215
+ if (!read) return void 0;
216
+ try {
217
+ return readViteHubPageAccount(await read({ request }));
218
+ } catch (error) {
219
+ console.error("[vitehub] The page tools could not read the signed-in person. The pill shows no account for this request.", error);
220
+ return;
221
+ }
222
+ }
223
+ /** The reader of the Site access cookie, or undefined in an app where the Console did not install one. */
224
+ function viteHubSiteVisitorReader() {
225
+ return state().siteVisitor;
226
+ }
227
+ /** The path of a URL below the app base. A path outside the base stays as it is. */
228
+ function pathBelow(base, pathname) {
229
+ return base && (pathname === base || pathname.startsWith(`${base}/`)) ? pathname.slice(base.length) || "/" : pathname;
230
+ }
231
+ /** Whether a URL is an app page that can get the page tools: inside the app base, and not under `/_vitehub` or `/api`. */
232
+ function isPagePath(url, base) {
233
+ if (base && url.pathname !== base && !url.pathname.startsWith(`${base}/`)) return false;
234
+ const path = pathBelow(base, url.pathname);
235
+ return !(path.startsWith("/_vitehub") || path === "/api" || path.startsWith("/api/"));
236
+ }
237
+ /**
238
+ * What ViteHub adds to the page of this request: the loader for a request with the hint, the bootstrap for any other
239
+ * page, or nothing when no tool is registered or the path is not a page.
240
+ */
241
+ function pageAddition(nitroApp, request, base) {
242
+ const url = new URL(request.url);
243
+ if ((state().tools.get(nitroApp)?.size ?? 0) === 0 || !isPagePath(url, base)) return void 0;
244
+ return viteHubPageToolsWanted(url.search, request.headers.get("cookie") ?? "") ? "loader" : "bootstrap";
245
+ }
246
+ function loaderTag(base, nonce) {
247
+ return `<script type="module" src="${base}${viteHubPageToolsLoader}"${nonce ? ` nonce="${nonce}"` : ""} ${viteHubPageToolsMarker}><\/script>`;
248
+ }
249
+ function sessionResponse(value, init = {}) {
250
+ const headers = new Headers({
251
+ "cache-control": "private, no-store",
252
+ "content-type": "application/json; charset=utf-8"
253
+ });
254
+ if (init.cookie) headers.append("set-cookie", init.cookie);
255
+ return new Response(JSON.stringify(value), {
256
+ headers,
257
+ status: init.status ?? 200
258
+ });
259
+ }
260
+ /**
261
+ * Answers `GET <base>/_vitehub/page/session`: the tools whose `allowed` check passes for this visitor, in registration
262
+ * order. The app base is the part of the request path before the session path, as the Console finds its own base, and
263
+ * each tool `script` path gets it. When at least one tool is allowed, the answer also has the `account` of a signed-in
264
+ * visitor, from the reader of `registerViteHubPageAccount()`. An anonymous visitor never gets one. It sets the hint cookie to `1` when at least one tool is allowed, and to `0` when
265
+ * none is, so a signed-in person without access does not ask again on each page. A tool whose check throws is not
266
+ * allowed. Requests from other sites get 403 and run no check.
267
+ */
268
+ async function respondViteHubPageSession(nitroApp, request) {
269
+ if (request.method !== "GET" && request.method !== "HEAD") return sessionResponse({ error: {
270
+ code: "VITEHUB_PAGE_TOOLS_METHOD",
271
+ why: "The page tools session accepts GET only."
272
+ } }, { status: 405 });
273
+ const origin = request.headers.get("origin");
274
+ if (origin && origin !== forwardedRequestOrigin(request) || request.headers.get("sec-fetch-site") === "cross-site") return sessionResponse({ error: {
275
+ code: "VITEHUB_PAGE_TOOLS_CROSS_ORIGIN",
276
+ why: "The page tools session answers the site's own pages only."
277
+ } }, { status: 403 });
278
+ const registered = [...state().tools.get(nitroApp)?.values() ?? []];
279
+ const checks = await Promise.all(registered.map(async (tool) => {
280
+ try {
281
+ return await tool.allowed({ request });
282
+ } catch (error) {
283
+ console.error(`[vitehub] The visitor check of the page tool "${tool.id}" failed. The tool stays off for this request.`, error);
284
+ return false;
285
+ }
286
+ }));
287
+ const pathname = new URL(request.url).pathname;
288
+ const at = pathname.lastIndexOf(viteHubPageSessionPath);
289
+ const base = at > 0 ? pathname.slice(0, at) : "";
290
+ const tools = registered.flatMap(({ allowed: _allowed, grants: _grants, ...tool }, index) => checks[index] === true || checks[index] === "lazy" ? [{
291
+ ...tool,
292
+ ...checks[index] === "lazy" ? { lazy: true } : {},
293
+ script: withViteHubBase(base, tool.script)
294
+ }] : []);
295
+ const account = tools.length > 0 ? await readAccount(nitroApp, request) : void 0;
296
+ return sessionResponse(account ? {
297
+ tools,
298
+ account
299
+ } : { tools }, { cookie: viteHubPageToolsHintCookie(tools.length > 0) });
300
+ }
301
+ /**
302
+ * The route of `GET /_vitehub/page/session`: a Fetchable (https://fetchable.org). Nitro 3 binds each Request to its
303
+ * app in `installViteHubPageTools()`, so the route finds the tools of that app.
304
+ */
305
+ const viteHubPageSessionHandler = { async fetch(request) {
306
+ const nitroApp = state().apps.get(request);
307
+ if (!nitroApp) return sessionResponse({ error: {
308
+ code: "VITEHUB_PAGE_TOOLS_APP",
309
+ why: "The page tools session has no Nitro app."
310
+ } }, { status: 503 });
311
+ return await respondViteHubPageSession(nitroApp, request);
312
+ } };
313
+ /**
314
+ * The script nonce of a page's Content Security Policy. A policy with `'strict-dynamic'`, such as the one of
315
+ * nuxt-security, blocks a script without it, even from the same origin.
316
+ */
317
+ function scriptNonce(headers) {
318
+ return scriptPolicyNonce(headers.get("content-security-policy") ?? "");
319
+ }
320
+ /**
321
+ * Inserts the loader script tag before `</body>` of a streamed HTML body, or at its end when it has none. `base` is the
322
+ * path of the app base, such as `/portal`. A page that already has the loader, such as a single page app whose
323
+ * `index.html` Vite changed, gets no second one. The generated SPA inline check becomes the external loader, with
324
+ * the response policy's nonce when present. This supports header or meta policies that allow same-origin external
325
+ * scripts but block inline scripts. The page varies per person, so it drops `content-length` and sends
326
+ * `cache-control: private, no-store`. Other responses return unchanged, including compressed HTML. `policyHeaders`
327
+ * supplies the effective CSP when the host keeps it outside the Response.
328
+ */
329
+ function injectPageToolsLoader(response, base = "", policyHeaders) {
330
+ return transformPage(response, () => loaderTag(base, scriptNonce(policyHeaders ?? response.headers)), true);
331
+ }
332
+ /**
333
+ * Inserts the page tools bootstrap, `viteHubPageToolsInlineScript()`, before `</body>` of an HTML page for a request
334
+ * without the hint, with the response policy's nonce when present. The bootstrap is the same for every visitor, so the
335
+ * page keeps its cache policy. Body validators are removed because they describe the upstream HTML. A page that
336
+ * already has a page tools script, such as a prerendered page, gets no second one. Other responses return unchanged,
337
+ * including compressed HTML and pages without an explicit UTF-8 charset.
338
+ */
339
+ function injectPageToolsBootstrap(response, base = "", policyHeaders) {
340
+ return transformPage(response, () => viteHubPageToolsInlineScript(base, scriptNonce(policyHeaders ?? response.headers)), false);
341
+ }
342
+ const pageBodyHeaders = [
343
+ "content-length",
344
+ "etag",
345
+ "last-modified"
346
+ ];
347
+ const pageConditions = ["if-none-match", "if-modified-since"];
348
+ function hasPageConditions(request) {
349
+ return pageConditions.some((name) => request.headers.has(name));
350
+ }
351
+ /** Whether a request is a page navigation with validators, which must reach the app without them. */
352
+ function revalidatesPage(request) {
353
+ if (request.method !== "GET" && request.method !== "HEAD") return false;
354
+ return request.headers.get("accept")?.split(",").some((range) => {
355
+ const [type, ...parameters] = range.split(";").map((part) => part.trim());
356
+ if (type?.toLowerCase() !== "text/html") return false;
357
+ const quality = parameters.find((part) => /^q\s*=/i.test(part))?.split("=")[1]?.trim();
358
+ return quality === void 0 || Number(quality) > 0 && Number(quality) <= 1;
359
+ }) === true && hasPageConditions(request);
360
+ }
361
+ /** The headers of the Node.js request that srvx keeps under `runtime.node.req`, when there is one. */
362
+ function nodeRequestHeaders(request) {
363
+ const runtime = Reflect.get(request, "runtime");
364
+ if (typeof runtime !== "object" || runtime === null) return void 0;
365
+ const node = Reflect.get(runtime, "node");
366
+ if (typeof node !== "object" || node === null) return void 0;
367
+ const req = Reflect.get(node, "req");
368
+ if (typeof req !== "object" || req === null) return void 0;
369
+ const headers = Reflect.get(req, "headers");
370
+ return typeof headers === "object" && headers !== null ? headers : void 0;
371
+ }
372
+ function withoutPageConditions(request) {
373
+ try {
374
+ for (const name of pageConditions) request.headers.delete(name);
375
+ const nodeHeaders = nodeRequestHeaders(request);
376
+ if (nodeHeaders) for (const name of pageConditions) delete nodeHeaders[name];
377
+ return request;
378
+ } catch {
379
+ const headers = new Headers(request.headers);
380
+ for (const name of pageConditions) headers.delete(name);
381
+ return new Request(request, { headers });
382
+ }
383
+ }
384
+ function htmlCharset(type) {
385
+ return /;\s*charset\s*=\s*"?([^";]*)/i.exec(type)?.[1]?.trim();
386
+ }
387
+ /** Whether a response is an HTML page that can get a page tools script. It reads the status and type, not the body. */
388
+ function isHtmlPage(response) {
389
+ return response.status === 200 && (response.headers.get("content-type") ?? "").toLowerCase().startsWith("text/html");
390
+ }
391
+ function transformPage(response, tag, personal) {
392
+ if (!isHtmlPage(response) || !response.body) return response;
393
+ const type = response.headers.get("content-type") ?? "";
394
+ const encoding = response.headers.get("content-encoding");
395
+ if (encoding && encoding.toLowerCase() !== "identity") return response;
396
+ const charset = htmlCharset(type);
397
+ if (!/^utf-?8$/i.test(charset ?? "")) return response;
398
+ const headers = new Headers(response.headers);
399
+ for (const name of pageBodyHeaders) headers.delete(name);
400
+ if (personal) headers.set("cache-control", "private, no-store");
401
+ return new Response(response.body.pipeThrough(pageToolsHtmlTransform(tag())), {
402
+ headers,
403
+ status: response.status,
404
+ statusText: response.statusText
405
+ });
406
+ }
407
+ /**
408
+ * Adds the page tools to the HTML pages of a Nitro app when at least one tool is registered. A request with the hint
409
+ * gets the loader script, and the page is sent with `cache-control: private, no-store`. Every other page gets the
410
+ * bootstrap, a short inline script that loads the loader in the browser only when the hint appears there. The
411
+ * bootstrap is in prerendered pages too, so a host that serves them as static files, such as Cloudflare Workers
412
+ * static assets, still shows the pill. Call it from each owner's Nitro plugin: it installs once per app, whatever the
413
+ * number of calls. It reads that app's registry and configured base on each request, so plugin order does not matter.
414
+ * It wraps `nitroApp.fetch`, the Web entry that every preset and the prerenderer call. The tag uses `options.base`.
415
+ */
416
+ function installViteHubPageTools(nitroApp, options = {}) {
417
+ if (nitroApp === null || typeof nitroApp !== "object") return;
418
+ const { installed, bases } = state();
419
+ if (options.base !== void 0) bases.set(nitroApp, viteHubBasePath(options.base));
420
+ if (installed.has(nitroApp)) return;
421
+ installed.add(nitroApp);
422
+ const fetch = Reflect.get(nitroApp, "fetch");
423
+ if (fetch instanceof Function) {
424
+ Reflect.set(nitroApp, "fetch", async (request, ...rest) => {
425
+ const base = state().bases.get(nitroApp) ?? "";
426
+ const conditional = request instanceof Request && hasPageConditions(request);
427
+ const early = conditional ? pageAddition(nitroApp, request, base) : void 0;
428
+ if (early && revalidatesPage(request)) request = withoutPageConditions(request);
429
+ if (request instanceof Request) state().apps.set(request, nitroApp);
430
+ const response = await Reflect.apply(fetch, nitroApp, [request, ...rest]);
431
+ if (!(response instanceof Response) || !(request instanceof Request) || !isHtmlPage(response)) return response;
432
+ const addition = conditional ? early : pageAddition(nitroApp, request, base);
433
+ if (addition === "loader") return injectPageToolsLoader(response, base);
434
+ return addition === "bootstrap" ? injectPageToolsBootstrap(response, base) : response;
435
+ });
436
+ return;
437
+ }
438
+ }
439
+ //#endregion
440
+ //#region src/runtime/session.ts
441
+ /**
442
+ * The person that Site access in the Console signed in to an app without Auth, with their roles in `role`, as
443
+ * `commentsRoleAllows()` reads them. A Console member has `comments-*` roles, a guest the roles of the invite.
444
+ */
445
+ async function siteUser(event) {
446
+ const read = viteHubSiteVisitorReader();
447
+ if (!read) return null;
448
+ const visitor = await read(getStandardContext(event).req).catch(() => void 0);
449
+ if (!visitor) return null;
450
+ const { roles, ...person } = visitor;
451
+ return {
452
+ ...person,
453
+ role: roles.join(",")
454
+ };
455
+ }
456
+ /**
457
+ * The user of a request, shared by the overlay API, Realtime presence, the MCP tools, and the comment operations.
458
+ * With `identify`, the app decides: `identify` names the user, `null` is anonymous, and `authorize` decides what they may do. Without
459
+ * `identify`, it is the user of `session`, the ViteHub Auth user. Then, when there is none, the person of the Site
460
+ * access cookie, and last the person signed in with GitHub.
461
+ */
462
+ async function resolveCommentsIdentity(comments, event, options = {}) {
463
+ if (comments.options.identify) {
464
+ getStandardContext(event);
465
+ return {
466
+ user: await comments.options.identify({ event }) ?? null,
467
+ gate: {}
468
+ };
469
+ }
470
+ return {
471
+ user: await options.session?.(event).catch(() => null) ?? await siteUser(event) ?? await options.githubLogin?.user(event).catch(() => null) ?? null,
472
+ gate: {}
473
+ };
474
+ }
475
+ /**
476
+ * The subject of an app page: what `page` of `defineComments()` gives for its URL, else `{ kind: "page", id }` with the
477
+ * normalized path. The overlay API, the page tools gate, and Realtime presence all check `authorize` on it.
478
+ */
479
+ async function resolveCommentsPage(comments, event, request, path) {
480
+ const id = normalizeCommentPage(path);
481
+ if (!comments.options.page) return { subject: {
482
+ kind: "page",
483
+ id
484
+ } };
485
+ getStandardContext(event);
486
+ const mapped = await comments.options.page({
487
+ url: new URL(id, forwardedRequestOrigin(request)),
488
+ event
489
+ });
490
+ if (!mapped) return { subject: {
491
+ kind: "page",
492
+ id
493
+ } };
494
+ return {
495
+ subject: {
496
+ kind: mapped.kind,
497
+ id: mapped.id
498
+ },
499
+ ...mapped.revision === void 0 ? {} : { revision: mapped.revision }
500
+ };
501
+ }
502
+ //#endregion
503
+ export { viteHubPageSessionHandler as a, registerViteHubPageTool as i, resolveCommentsPage as n, forwardedRequestOrigin as o, installViteHubPageTools as r, resolveCommentsIdentity as t };
@@ -0,0 +1,30 @@
1
+ import { E as CommentsTransport, S as CommentThread, w as CommentUser, x as CommentSubject } from "./types-CZujrMFd.js";
2
+ //#region src/operations-core/testing.d.ts
3
+ export interface MemoryTransportOptions {
4
+ /** The signed-in user. Every call acts as this user. */
5
+ user: CommentUser;
6
+ /** People that `users()` can find, for @mentions. */
7
+ users?: CommentUser[];
8
+ /** Threads to start with. */
9
+ threads?: CommentThread[];
10
+ /** The numbering scope of a subject. Defaults to one scope for the whole site. */
11
+ scope?: (subject: CommentSubject) => string;
12
+ now?: () => number;
13
+ }
14
+ export interface MemoryTransport extends CommentsTransport {
15
+ readonly user: CommentUser;
16
+ /** A copy of every thread in the store. */
17
+ readonly threads: CommentThread[];
18
+ subscribe: NonNullable<CommentsTransport["subscribe"]>;
19
+ /** Another person on the same store, to test what each one sees and may change. */
20
+ as: (user: CommentUser) => MemoryTransport;
21
+ /** Tells every listener that the connection came back, as a Realtime transport does after it reconnects. */
22
+ reconnect: () => void;
23
+ }
24
+ /**
25
+ * A transport that keeps threads in memory. Use it in tests, in docs examples, and to try the UI
26
+ * before the server half exists. It follows the access rules of the real operations: authors edit
27
+ * and delete their own messages, and everyone can resolve.
28
+ */
29
+ export declare function createMemoryTransport(options: MemoryTransportOptions): MemoryTransport;
30
+ //#endregion