@vite-hub/comments 0.1.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 (87) hide show
  1. package/README.md +79 -31
  2. package/dist/anchor.d.ts +7 -4
  3. package/dist/anchor.js +10 -5
  4. package/dist/client-diagnostics-CcFpkbAk.js +40 -0
  5. package/dist/client.d.ts +78 -3
  6. package/dist/client.js +198 -13
  7. package/dist/{console-BIz9t2cO.d.ts → console-h4KlhIik.d.ts} +97 -8
  8. package/dist/context-BqIsmYP1.js +61 -0
  9. package/dist/database/postgres.d.ts +738 -347
  10. package/dist/database/postgres.js +28 -7
  11. package/dist/{database-Cb2xjC1V.d.ts → database-CA1aHKN7.d.ts} +675 -276
  12. package/dist/database.d.ts +6 -98
  13. package/dist/database.js +2 -3
  14. package/dist/define-43mMR39K.js +89 -0
  15. package/dist/define-B3TF9zzn.d.ts +204 -0
  16. package/dist/errors-4gelGVmK.js +57 -0
  17. package/dist/errors-C6qptPoG.js +135 -0
  18. package/dist/errors-CyQyKAvy.d.ts +185 -0
  19. package/dist/fold-name-B7Zb3-MF.js +7 -0
  20. package/dist/{identity-3qtVC4rF.js → identity-CBOzgxSf.js} +7 -2
  21. package/dist/index-DNhy69Wt.d.ts +83 -0
  22. package/dist/index.d.ts +7 -7
  23. package/dist/index.js +196 -5
  24. package/dist/install-BcMPgPk_.js +1154 -0
  25. package/dist/install-W9ghhGoh.d.ts +36 -0
  26. package/dist/installed-B-PfERBU.js +30 -0
  27. package/dist/invariant-D8_xBqmZ.js +22 -0
  28. package/dist/migrate-B0k_0swk.d.ts +54 -0
  29. package/dist/migrate-BDQ8xqUs.js +289 -0
  30. package/dist/object-Da1zyPCR.js +11 -0
  31. package/dist/{operations-0B0QTVWX.d.ts → operations-D4A1Fcgf.d.ts} +37 -15
  32. package/dist/operations-DMMIfYPW.js +1159 -0
  33. package/dist/operations-GLeOqgMt.d.ts +257 -0
  34. package/dist/operations.d.ts +3 -7
  35. package/dist/operations.js +3 -2
  36. package/dist/overlay/client-DmsSMOzi.js +4 -0
  37. package/dist/overlay/dist-BoHMOFax.js +14 -0
  38. package/dist/overlay/dist-yIZmvSaU.js +1 -0
  39. package/dist/overlay/overlay.js +183 -177
  40. package/dist/page/loader.js +138 -18
  41. package/dist/{page-BuroSMXO.js → page-B41ozN63.js} +8 -6
  42. package/dist/{page-BtXADR6d.d.ts → page-DtbMOEMd.d.ts} +6 -5
  43. package/dist/page-tools-shared-NHUjKI8E.js +117 -0
  44. package/dist/path--zk6PEMz.js +18 -0
  45. package/dist/plugin-PS8PMYus.js +74 -0
  46. package/dist/realtime.d.ts +6 -12
  47. package/dist/realtime.js +23 -24
  48. package/dist/rpc-HBcWtg0T.d.ts +17 -0
  49. package/dist/rpc-RKPAusHp.js +153 -0
  50. package/dist/rpc.d.ts +2 -29
  51. package/dist/rpc.js +2 -75
  52. package/dist/runtime/auth.d.ts +5 -3
  53. package/dist/runtime/auth.js +8 -5
  54. package/dist/runtime/console.d.ts +1 -1
  55. package/dist/runtime/console.js +26 -21
  56. package/dist/runtime/index.d.ts +108 -60
  57. package/dist/runtime/index.js +684 -236
  58. package/dist/{server-BomGg3Gb.js → server-D8k-0GXe.js} +16 -7
  59. package/dist/server.d.ts +14 -88
  60. package/dist/server.js +7 -326
  61. package/dist/service-CFVm23k7.d.ts +158 -0
  62. package/dist/service-GHhhyQj4.js +609 -0
  63. package/dist/session-DVx-1Tym.d.ts +14 -0
  64. package/dist/session-EkudzUmm.js +503 -0
  65. package/dist/testing.d.ts +1 -1
  66. package/dist/testing.js +14 -2
  67. package/dist/tokens-DSbwkVSy.js +58 -0
  68. package/dist/types-BIS0hCEl.d.ts +124 -0
  69. package/dist/types-CZujrMFd.d.ts +322 -0
  70. package/dist/vite.d.ts +91 -87
  71. package/dist/vite.js +535 -796
  72. package/package.json +24 -27
  73. package/dist/database-BSnVrwHn.js +0 -60
  74. package/dist/database-C-ktS9Do.js +0 -95
  75. package/dist/define-BzW2Ychn.d.ts +0 -46
  76. package/dist/define-Cbhl6QVJ.js +0 -32
  77. package/dist/errors-BAQYcy3_.d.ts +0 -89
  78. package/dist/errors-DeD6wTCl.js +0 -77
  79. package/dist/h3-v1-request-DDGXJ9E7.js +0 -166
  80. package/dist/index-DklG2Etf.d.ts +0 -111
  81. package/dist/operations-NZG5dB8y.js +0 -732
  82. package/dist/page-tools-shared-D-amu6sx.js +0 -53
  83. package/dist/plugin-QElKQYkA.js +0 -725
  84. package/dist/request-DVc3M_AG.js +0 -14
  85. package/dist/src-CRTwnaEG.js +0 -1362
  86. package/dist/types-Cj8K7Vx7.d.ts +0 -176
  87. package/dist/types-Un2dcJWD.d.ts +0 -288
@@ -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 };
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as CommentUser, g as CommentThread, h as CommentSubject, y as CommentsTransport } from "./types-Cj8K7Vx7.js";
1
+ import { E as CommentsTransport, S as CommentThread, w as CommentUser, x as CommentSubject } from "./types-CZujrMFd.js";
2
2
  //#region src/operations-core/testing.d.ts
3
3
  export interface MemoryTransportOptions {
4
4
  /** The signed-in user. Every call acts as this user. */
package/dist/testing.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as commentsErrorDiagnostics } from "./errors-DeD6wTCl.js";
1
+ import { t as commentsErrorDiagnostics } from "./errors-C6qptPoG.js";
2
2
  //#region src/operations-core/testing.ts
3
3
  function copy(value) {
4
4
  return JSON.parse(JSON.stringify(value));
@@ -16,6 +16,7 @@ function createMemoryTransport(options) {
16
16
  threads: /* @__PURE__ */ new Map(),
17
17
  listeners: /* @__PURE__ */ new Set(),
18
18
  counters: /* @__PURE__ */ new Map(),
19
+ requests: /* @__PURE__ */ new Map(),
19
20
  users: options.users ?? [],
20
21
  scope: options.scope ?? (() => "site"),
21
22
  now: options.now ?? Date.now
@@ -36,7 +37,7 @@ function thread(store, id) {
36
37
  }
37
38
  function message(store, user, input) {
38
39
  const body = input.body.trim();
39
- if (!body) throw commentsErrorDiagnostics.COMMENTS_R0005();
40
+ if (!body && !input.attachments?.length) throw commentsErrorDiagnostics.COMMENTS_R0005();
40
41
  return {
41
42
  id: `message-${crypto.randomUUID()}`,
42
43
  threadId: input.threadId,
@@ -61,10 +62,12 @@ function view(store, user) {
61
62
  };
62
63
  const matches = (item, query) => {
63
64
  if (query.subject && !sameSubject(item.subject, query.subject)) return false;
65
+ if (query.subjectKind !== void 0 && item.subject.kind !== query.subjectKind) return false;
64
66
  if (query.page !== void 0 && !sameSubject(item.subject, {
65
67
  kind: "page",
66
68
  id: query.page
67
69
  })) return false;
70
+ if (query.revision && (item.revision === void 0 || item.revision > query.revision.lte)) return false;
68
71
  if (query.status && item.status !== query.status) return false;
69
72
  if (query.mine && item.author.id !== user.id) return false;
70
73
  if (query.mentions && !item.messages.some((entry) => entry.mentions.includes(user.id))) return false;
@@ -91,6 +94,12 @@ function view(store, user) {
91
94
  },
92
95
  async create(input) {
93
96
  const scope = store.scope(input.subject);
97
+ const request = input.requestId === void 0 ? void 0 : JSON.stringify([scope, input.requestId]);
98
+ const earlier = request === void 0 ? void 0 : store.threads.get(store.requests.get(request) ?? "");
99
+ if (earlier) {
100
+ if (earlier.author.id !== user.id || earlier.subject.kind !== input.subject.kind || earlier.subject.id !== input.subject.id) throw commentsErrorDiagnostics.COMMENTS_R0022();
101
+ return copy(earlier);
102
+ }
94
103
  const n = (store.counters.get(scope) ?? 0) + 1;
95
104
  const id = `thread-${crypto.randomUUID()}`;
96
105
  const first = message(store, user, {
@@ -98,11 +107,14 @@ function view(store, user) {
98
107
  threadId: id
99
108
  });
100
109
  store.counters.set(scope, n);
110
+ if (request !== void 0) store.requests.set(request, id);
101
111
  return save({
102
112
  id,
103
113
  scope,
104
114
  n,
105
115
  subject: copy(input.subject),
116
+ ...input.metadata === void 0 ? {} : { metadata: copy(input.metadata) },
117
+ ...input.revision === void 0 ? {} : { revision: input.revision },
106
118
  anchor: copy(input.anchor),
107
119
  status: "open",
108
120
  author: copy(user),
@@ -0,0 +1,58 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ //#region ../internal/src/runtime/cloudflare-env-lookup.ts
3
+ /** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
4
+ const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
5
+ let activeEnv;
6
+ /** The store of the current `runWithActiveCloudflareEnv()` call, or undefined outside one. */
7
+ function getScopedCloudflareEnv() {
8
+ return globalThis[activeEnvStorageKey]?.getStore();
9
+ }
10
+ function getActiveCloudflareEnv() {
11
+ const scoped = getScopedCloudflareEnv();
12
+ if (scoped) return scoped.env;
13
+ const host = globalThis;
14
+ return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
15
+ }
16
+ //#endregion
17
+ //#region ../internal/src/runtime/cloudflare-env.ts
18
+ const runtimeGlobal = globalThis;
19
+ const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
20
+ function runWithActiveCloudflareEnv(env, callback) {
21
+ return activeEnvStorage.run({ env }, callback);
22
+ }
23
+ function getActiveCloudflareBinding(name) {
24
+ const env = getActiveCloudflareEnv();
25
+ return env && Object.hasOwn(env, name) ? env[name] : void 0;
26
+ }
27
+ //#endregion
28
+ //#region src/forge/tokens.ts
29
+ /** How long the GitHub token of a person's last request stays usable for the pull request sync that it started. */
30
+ const tokenLifetime = 6e5;
31
+ const tokens = /* @__PURE__ */ new Map();
32
+ /**
33
+ * Keeps the GitHub token of a person who signed in with GitHub, so the pull request sync that runs after their request
34
+ * can post as them. The token lives in their session cookie; this copy stays in memory for ten minutes.
35
+ */
36
+ function rememberGitHubToken(authorId, token) {
37
+ const now = Date.now();
38
+ if (tokens.size > 1e3) {
39
+ for (const [id, entry] of tokens) if (entry.until <= now) tokens.delete(id);
40
+ }
41
+ tokens.set(authorId, {
42
+ token,
43
+ until: now + tokenLifetime
44
+ });
45
+ }
46
+ /** The GitHub token of a person's request in the last ten minutes. */
47
+ function recentGitHubToken(authorId) {
48
+ const entry = tokens.get(authorId);
49
+ if (!entry) return;
50
+ if (entry.until > Date.now()) return entry.token;
51
+ tokens.delete(authorId);
52
+ }
53
+ /** Drops the token of a person who signs out. */
54
+ function forgetGitHubToken(authorId) {
55
+ tokens.delete(authorId);
56
+ }
57
+ //#endregion
58
+ export { runWithActiveCloudflareEnv as a, getActiveCloudflareBinding as i, recentGitHubToken as n, rememberGitHubToken as r, forgetGitHubToken as t };