@vite-hub/comments 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +4 -10
  2. package/dist/anchor.d.ts +1 -1
  3. package/dist/client-request-B1DCz3a9.js +29 -0
  4. package/dist/client.d.ts +20 -240
  5. package/dist/client.js +3 -421
  6. package/dist/database.d.ts +1 -2
  7. package/dist/database.js +1 -1
  8. package/dist/{define-BqPcuDhf.js → define-C-LUOouq.js} +1 -1
  9. package/dist/{errors-C0VwRHiy.js → errors-C5utwZ5H.js} +0 -24
  10. package/dist/{errors-CBvIpwbo.js → errors-DeSEHzRf.js} +0 -12
  11. package/dist/hosted/hosted-comments/frame.js +4 -1
  12. package/dist/hosted/hosted-comments/tools.js +65 -74
  13. package/dist/hosted/hosted-comments.js +1 -1
  14. package/dist/{index-D1T7RJ4R.d.ts → index-d6NsDxu9.d.ts} +4 -112
  15. package/dist/index.d.ts +4 -5
  16. package/dist/index.js +6 -20
  17. package/dist/{install-CqBWFmU7.js → install-BueV_fJY.js} +7 -771
  18. package/dist/{install-9L4ASzUC.d.ts → install-F-_O7zDr.d.ts} +5 -11
  19. package/dist/{installed-wUYjqk_k.js → installed-BqQKo6WC.js} +2 -7
  20. package/dist/{database-BuSNVwTx.js → migrate-oseJAYbm.js} +2 -46
  21. package/dist/{operations-kMPw-Cyb.js → operations-0llC5kKO.js} +46 -47
  22. package/dist/{operations-Qt8ASQqW.d.ts → operations-jaihyWw2.d.ts} +35 -3
  23. package/dist/operations.d.ts +3 -3
  24. package/dist/operations.js +2 -2
  25. package/dist/overlay/client-ZBsUybIe.js +4 -0
  26. package/dist/overlay/overlay.js +47 -43
  27. package/dist/page/loader.js +31 -27
  28. package/dist/page-BgvzzsJb.d.ts +32 -0
  29. package/dist/{page-2NzFladc.js → page-CDhmXO-y.js} +24 -1
  30. package/dist/{page-tools-shared-BNw-aWEH.js → page-tools-shared-BCdvqA4S.js} +40 -2
  31. package/dist/{plugin-ChOHe7vq.js → plugin-DGUqlc3C.js} +9 -9
  32. package/dist/realtime.d.ts +6 -8
  33. package/dist/realtime.js +2 -4
  34. package/dist/runtime/auth.d.ts +1 -2
  35. package/dist/runtime/auth.js +1 -1
  36. package/dist/runtime/client-request-plugin.d.ts +2 -0
  37. package/dist/runtime/client-request-plugin.js +21 -0
  38. package/dist/runtime/console.js +2 -2
  39. package/dist/runtime/index.d.ts +5 -8
  40. package/dist/runtime/index.js +23 -151
  41. package/dist/{server-8o9u8leM.js → server-CAMs6viR.js} +1 -1
  42. package/dist/server.d.ts +11 -7
  43. package/dist/server.js +7 -6
  44. package/dist/{store-DvNTDNgn.d.ts → service-CMVA_Ryv.d.ts} +67 -1
  45. package/dist/{service-XT2A8YEF.js → service-DaMq8TBw.js} +35 -33
  46. package/dist/{session-DGdFKWDB.js → session-B7GDrqsK.js} +204 -39
  47. package/dist/{session-CN4irEqf.d.ts → session-EzQqBeE8.d.ts} +2 -3
  48. package/dist/{table-names-BIHjuEFK.js → table-names-DUmWROM4.js} +1 -3
  49. package/dist/testing.js +1 -1
  50. package/dist/{define-B1jLSPe9.d.ts → types-qzJKgWYS.d.ts} +157 -4
  51. package/dist/vite.d.ts +2 -19
  52. package/dist/vite.js +15 -51
  53. package/package.json +8 -8
  54. package/dist/database-CPua6Q6_.d.ts +0 -573
  55. package/dist/overlay/client-CrnKCZXc.js +0 -4
  56. package/dist/overlay/dist-yIZmvSaU.js +0 -1
  57. package/dist/page-DE71P_gQ.d.ts +0 -11
  58. package/dist/request-origin-B-CPVAVk.js +0 -53
  59. package/dist/service-IvgrI4XM.d.ts +0 -71
  60. package/dist/types-l6GOb_yc.d.ts +0 -206
@@ -1,9 +1,9 @@
1
1
  import { t as replyMessageId } from "./reply-id-Cm9FGOBs.js";
2
2
  import { t as isPagePath } from "./path-8yqMd8zR.js";
3
- import { t as commentsErrorDiagnostics } from "./errors-CBvIpwbo.js";
3
+ import { t as commentsErrorDiagnostics } from "./errors-DeSEHzRf.js";
4
4
  import { t as foldName } from "./fold-name-g-xg0mQk.js";
5
5
  import { r as guestIdPrefix } from "./identity-CT7-UGmS.js";
6
- import { i as defaultPolicy, o as deniedForMissingPolicy, t as builtinCommentSubjects } from "./define-BqPcuDhf.js";
6
+ import { i as defaultPolicy, o as deniedForMissingPolicy, t as builtinCommentSubjects } from "./define-C-LUOouq.js";
7
7
  import { t as logFailure } from "./request-log-DllKQXj7.js";
8
8
  import * as v from "valibot";
9
9
  // ../internal/src/runtime/client-rate-limit.ts
@@ -228,7 +228,13 @@ function peopleOf(runtime, reader, gate, console) {
228
228
  }
229
229
  /** People that `@` suggests to `user`, without the ones that may not be mentioned in the thread. */
230
230
  async function suggest(runtime, input) {
231
- const found = await peopleOf(runtime, input.user, input.gate, input.console).search(input.query, input.limit * 2);
231
+ const subject = input.subject ?? input.thread?.subject;
232
+ const context = {
233
+ user: input.user,
234
+ ...input.thread ? { thread: input.thread } : {},
235
+ ...subject ? { subject } : {}
236
+ };
237
+ const found = await peopleOf(runtime, input.user, input.gate, input.console).search(input.query, input.limit * 2, context);
232
238
  const needle = foldName(input.query.trim());
233
239
  const people = [];
234
240
  for (const person of found) {
@@ -338,17 +344,34 @@ function newId(prefix) {
338
344
  return `${prefix}_${crypto.randomUUID()}`;
339
345
  }
340
346
  /**
341
- * Runs `onComment` before the answer and `onMention` after it, for one saved message. A failure is logged and never
342
- * fails the comment.
347
+ * Runs `onComment` before the answer and `onMention` after it, for one saved message. Work that `onComment` gives to
348
+ * `waitUntil` also runs after the answer. A failure is logged and never fails the comment.
343
349
  */
344
350
  async function announce(runtime, thread, message, mentions, fresh, options) {
345
351
  if (!message) return;
346
352
  const { onComment, onMention } = runtime.definition;
353
+ const keep = (promise) => {
354
+ options.waitUntil?.(promise);
355
+ runtime.background?.(promise);
356
+ };
357
+ const failedLater = (hook) => (error) => {
358
+ logFailure({
359
+ field: "comments",
360
+ fields: {
361
+ hook,
362
+ thread: thread.id
363
+ },
364
+ message: `Comments ${hook} failed`,
365
+ error,
366
+ waitUntil: keep
367
+ }, () => globalThis.console.error(`[vitehub] Comments ${hook} failed:`, error));
368
+ };
347
369
  if (options.comment && onComment) try {
348
370
  await onComment({
349
371
  mentions,
350
372
  message,
351
- thread
373
+ thread,
374
+ waitUntil: (promise) => keep(promise.catch(failedLater("onComment")))
352
375
  });
353
376
  } catch (error) {
354
377
  logFailure({
@@ -364,33 +387,12 @@ async function announce(runtime, thread, message, mentions, fresh, options) {
364
387
  }
365
388
  if (!onMention || !fresh.length) return;
366
389
  const link = subjectDefinition(runtime, thread.subject.kind)?.link?.(thread);
367
- const keep = (promise) => {
368
- options.waitUntil?.(promise);
369
- runtime.background?.(promise);
370
- };
371
- const task = (async () => {
372
- try {
373
- await onMention({
374
- message,
375
- thread,
376
- users: fresh,
377
- ...link ? { link } : {}
378
- });
379
- } catch (error) {
380
- logFailure({
381
- field: "comments",
382
- fields: {
383
- hook: "onMention",
384
- thread: thread.id
385
- },
386
- message: "Comments onMention failed",
387
- error,
388
- waitUntil: keep
389
- }, () => globalThis.console.error("[vitehub] Comments onMention failed:", error));
390
- }
391
- })();
392
- options.waitUntil?.(task);
393
- runtime.background?.(task);
390
+ keep((async () => onMention({
391
+ message,
392
+ thread,
393
+ users: fresh,
394
+ ...link ? { link } : {}
395
+ }))().catch(failedLater("onMention")));
394
396
  }
395
397
  /** The thread that an earlier `createThread` with this `requestId` stored. A retry gets it back before the create checks. */
396
398
  async function earlierThread(runtime, input) {
@@ -1,6 +1,6 @@
1
- import { 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-BNw-aWEH.js";
2
- import { r as matchesPublicOrigin, t as applicationRequestOrigin } from "./request-origin-B-CPVAVk.js";
3
- import { c as normalizeCommentPage } from "./page-2NzFladc.js";
1
+ import { a as viteHubPageSessionPath, c as viteHubPageToolsHintCookie, d as viteHubPageToolsLoader, f as viteHubPageToolsMarker, h as withViteHubBase, i as viteHubPageSessionHandoffScript, l as viteHubPageToolsInlineScript, m as viteHubPageToolsWanted, n as readViteHubPageSession, p as viteHubPageToolsQuery, r as viteHubBasePath, t as readViteHubPageAccount } from "./page-tools-shared-BCdvqA4S.js";
2
+ import { t as clientRequest } from "./client-request-B1DCz3a9.js";
3
+ import { p as normalizeCommentPage } from "./page-CDhmXO-y.js";
4
4
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
5
5
  // ../internal/src/runtime/page-tools-html.ts
6
6
  /** The effective script-element directive is shared by HTTP and HTML meta policies. */
@@ -30,7 +30,7 @@ function isGeneratedCheck(inline) {
30
30
  try {
31
31
  const path = JSON.parse(inline.slice(at + 7, -1));
32
32
  const nonce = tagNonce(inline);
33
- return typeof path === "string" && path.endsWith("/_vitehub/page/assets/loader.js?v=25") && viteHubPageToolsInlineScript(path.slice(0, -36), nonce) === `${inline}<\/script>`;
33
+ return typeof path === "string" && path.endsWith("/_vitehub/page/assets/loader.js?v=28") && viteHubPageToolsInlineScript(path.slice(0, -36), nonce) === `${inline}<\/script>`;
34
34
  } catch {
35
35
  return false;
36
36
  }
@@ -47,8 +47,12 @@ function tagEnd(text) {
47
47
  }
48
48
  return -1;
49
49
  }
50
- /** Scan HTML tokens across chunks; only active script elements can own the loader marker. */
51
- function pageToolsHtmlTransform(loader) {
50
+ /**
51
+ * Scan HTML tokens across chunks; only active script elements can own the loader marker. `late` gives more markup for
52
+ * the end of the body, with the nonce of the loader tag. It is called once, when the transform reaches `</body>` or the
53
+ * end of the page, so it can give what became known while the page streamed.
54
+ */
55
+ function pageToolsHtmlTransform(loader, late) {
52
56
  const decoder = new TextDecoder();
53
57
  const encoder = new TextEncoder();
54
58
  let pending = "";
@@ -58,6 +62,7 @@ function pageToolsHtmlTransform(loader) {
58
62
  let templates = 0;
59
63
  let present = false;
60
64
  let done = false;
65
+ const ending = () => late?.(tagNonce(loader)) ?? "";
61
66
  return new TransformStream({
62
67
  transform(chunk, controller) {
63
68
  pending += decoder.decode(chunk, { stream: true });
@@ -139,6 +144,7 @@ function pageToolsHtmlTransform(loader) {
139
144
  if (nonce) loader = loader.replace(` ${viteHubPageToolsMarker}`, ` nonce="${nonce}" ${viteHubPageToolsMarker}`);
140
145
  }
141
146
  if (name === "body" && closing && !templates) {
147
+ emit(ending());
142
148
  if (!present) emit(loader);
143
149
  done = true;
144
150
  }
@@ -159,10 +165,54 @@ function pageToolsHtmlTransform(loader) {
159
165
  },
160
166
  flush(controller) {
161
167
  const rest = inline + pending + decoder.decode();
162
- controller.enqueue(encoder.encode(rest + (done || present ? "" : loader)));
168
+ controller.enqueue(encoder.encode(rest + (done ? "" : ending()) + (done || present ? "" : loader)));
163
169
  }
164
170
  });
165
171
  }
172
+ // ../internal/src/runtime/request-origin.ts
173
+ function firstHeaderValue(headers, name) {
174
+ return headers.get(name)?.split(",", 1)[0]?.trim() || void 0;
175
+ }
176
+ const applicationOriginKey = Symbol.for("vitehub.request.application-origin");
177
+ const requestGlobals = globalThis;
178
+ function setApplicationRequestOrigin(request, origin) {
179
+ (requestGlobals[applicationOriginKey] ??= /* @__PURE__ */ new WeakMap()).set(request, origin);
180
+ }
181
+ function applicationRequestOrigin(request) {
182
+ return requestGlobals[applicationOriginKey]?.get(request) ?? forwardedRequestOrigin(request);
183
+ }
184
+ /**
185
+ * The origin that the client used for `request`. A TLS-terminating proxy sends the client scheme in
186
+ * `X-Forwarded-Proto` and the client host in `X-Forwarded-Host`. Each proxy appends its value, so the first value wins.
187
+ * Without these headers, or with values that are not valid, the result is the origin of `request.url`.
188
+ */
189
+ function forwardedRequestOrigin(request) {
190
+ const url = new URL(request.url);
191
+ const forwardedProtocol = firstHeaderValue(request.headers, "x-forwarded-proto")?.toLowerCase();
192
+ const protocol = forwardedProtocol === "http" || forwardedProtocol === "https" ? forwardedProtocol : url.protocol.slice(0, -1);
193
+ const host = firstHeaderValue(request.headers, "x-forwarded-host") ?? url.host;
194
+ if (/[\u0000-\u001F\s/\\?#@]/.test(host)) return url.origin;
195
+ try {
196
+ return new URL(`${protocol}://${host}`).origin;
197
+ } catch {
198
+ return url.origin;
199
+ }
200
+ }
201
+ /**
202
+ * Whether a request came in on one of the public `origins` of the app, such as the origin of `vitehub({ publicUrl })`.
203
+ * It compares the host that the client used, so a proxy that does not forward the scheme still matches. A loopback
204
+ * host, such as `localhost:3000` for a preview or a proxy that does not forward the host, also matches: it cannot be a
205
+ * second public hostname. Every request matches when `origins` is empty.
206
+ */
207
+ function matchesPublicOrigin(request, origins) {
208
+ if (origins.length === 0) return true;
209
+ const { host, hostname } = new URL(forwardedRequestOrigin(request));
210
+ return isLoopbackHostname(hostname) || origins.some((origin) => new URL(origin).host === host);
211
+ }
212
+ /** `localhost`, `[::1]`, or an IPv4 address in `127.0.0.0/8`. URL parsing writes IPv4 addresses as four decimal parts. */
213
+ function isLoopbackHostname(hostname) {
214
+ return hostname === "localhost" || hostname === "[::1]" || /^127(?:\.\d{1,3}){3}$/.test(hostname);
215
+ }
166
216
  // ../internal/src/runtime/page-tools.ts
167
217
  const stateKey = Symbol.for("vitehub.page-tools");
168
218
  const scope = globalThis;
@@ -187,15 +237,16 @@ function registerViteHubPageTool(nitroApp, tool) {
187
237
  const grants = state().grants ??= /* @__PURE__ */ new Map();
188
238
  for (const grant of tool.grants ?? []) grants.set(grant.id, grant);
189
239
  }
190
- /** The account of a visitor, or `undefined` without a reader, without a session, or when the reader fails. */
240
+ /** The account of a visitor, none without a reader or a session, and `failed` when the reader throws. */
191
241
  async function readAccount(nitroApp, request) {
192
242
  const read = state().accounts?.get(nitroApp);
193
- if (!read) return void 0;
243
+ if (!read) return {};
194
244
  try {
195
- return readViteHubPageAccount(await read({ request }));
245
+ const account = readViteHubPageAccount(await read({ request }));
246
+ return account ? { account } : {};
196
247
  } catch (error) {
197
248
  console.error("[vitehub] The page tools could not read the signed-in person. The pill shows no account for this request.", error);
198
- return;
249
+ return { failed: true };
199
250
  }
200
251
  }
201
252
  /**
@@ -237,12 +288,14 @@ function pageAddition(nitroApp, request, base) {
237
288
  function loaderTag(base, nonce) {
238
289
  return `<script type="module" src="${base}${viteHubPageToolsLoader}"${nonce ? ` nonce="${nonce}"` : ""} ${viteHubPageToolsMarker}><\/script>`;
239
290
  }
291
+ const sessionCompleteHeader = "x-vitehub-page-session";
240
292
  function sessionResponse(value, init = {}) {
241
293
  const headers = new Headers({
242
294
  "cache-control": "private, no-store",
243
295
  "content-type": "application/json; charset=utf-8"
244
296
  });
245
297
  if (init.cookie) headers.append("set-cookie", init.cookie);
298
+ if (init.complete) headers.set(sessionCompleteHeader, "complete");
246
299
  return new Response(JSON.stringify(value), {
247
300
  headers,
248
301
  status: init.status ?? 200
@@ -254,7 +307,8 @@ function sessionResponse(value, init = {}) {
254
307
  * each tool `script` path gets it. When at least one tool is allowed, the answer also has the `account` of a signed-in
255
308
  * 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
256
309
  * none is, so a signed-in person without access does not ask again on each page. A tool whose check throws is not
257
- * allowed. Requests from other sites get 403 and run no check. An origin that the app does not serve its page tools on
310
+ * allowed. The answer has `x-vitehub-page-session: complete` when every check and the account reader answered without
311
+ * throwing, so a denied tool or a missing account is the decision for this visitor and not a failure. Requests from other sites get 403 and run no check. An origin that the app does not serve its page tools on
258
312
  * gets 404.
259
313
  */
260
314
  async function respondViteHubPageSession(nitroApp, request) {
@@ -277,7 +331,7 @@ async function respondViteHubPageSession(nitroApp, request) {
277
331
  return await tool.allowed({ request });
278
332
  } catch (error) {
279
333
  console.error(`[vitehub] The visitor check of the page tool "${tool.id}" failed. The tool stays off for this request.`, error);
280
- return false;
334
+ return null;
281
335
  }
282
336
  }));
283
337
  const pathname = new URL(request.url).pathname;
@@ -288,11 +342,14 @@ async function respondViteHubPageSession(nitroApp, request) {
288
342
  ...checks[index] === "lazy" ? { lazy: true } : {},
289
343
  script: withViteHubBase(base, tool.script)
290
344
  }] : []);
291
- const account = tools.length > 0 ? await readAccount(nitroApp, request) : void 0;
345
+ const { account, failed } = tools.length > 0 ? await readAccount(nitroApp, request) : {};
292
346
  return sessionResponse(account ? {
293
347
  tools,
294
348
  account
295
- } : { tools }, { cookie: viteHubPageToolsHintCookie(tools.length > 0) });
349
+ } : { tools }, {
350
+ cookie: viteHubPageToolsHintCookie(tools.length > 0),
351
+ complete: !failed && !checks.includes(null)
352
+ });
296
353
  }
297
354
  /**
298
355
  * The route of `GET /_vitehub/page/tools`: a Fetchable (https://fetchable.org). `installViteHubPageTools()` binds
@@ -313,17 +370,109 @@ const viteHubPageSessionHandler = { async fetch(request) {
313
370
  function scriptNonce(headers) {
314
371
  return scriptPolicyNonce(headers.get("content-security-policy") ?? "");
315
372
  }
316
- /**
317
- * Inserts the loader script tag before `</body>` of a streamed HTML body, or at its end when it has none. `base` is the
318
- * path of the app base, such as `/portal`. A page that already has the loader, such as a single page app whose
319
- * `index.html` Vite changed, gets no second one. The generated SPA inline check becomes the external loader, with
320
- * the response policy's nonce when present. This supports header or meta policies that allow same-origin external
321
- * scripts but block inline scripts. The page varies per person, so it drops `content-length` and sends
322
- * `cache-control: private, no-store`. Other responses return unchanged, including compressed HTML. `policyHeaders`
323
- * supplies the effective CSP when the host keeps it outside the Response.
324
- */
325
- function injectPageToolsLoader(response, base = "", policyHeaders) {
326
- return transformPage(response, () => loaderTag(base, scriptNonce(policyHeaders ?? response.headers)), true);
373
+ function attribute(value) {
374
+ return value.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;");
375
+ }
376
+ function handoffMarkup(handoff, nonce) {
377
+ const preloads = handoff.session.tools.filter((tool) => !tool.lazy).map((tool) => `<link rel="modulepreload" href="${attribute(tool.script)}"${nonce ? ` nonce="${nonce}"` : ""}>`);
378
+ return `${viteHubPageSessionHandoffScript(handoff, nonce)}${preloads.join("")}`;
379
+ }
380
+ const sharedCacheHeader = /^(?:(?:[a-z0-9-]+-)?cdn-cache-control|surrogate-control)$/;
381
+ const sharedCacheRules = [
382
+ "isr",
383
+ "swr",
384
+ "cache",
385
+ "prerender"
386
+ ];
387
+ function sharedCacheMayStore(request, response) {
388
+ const control = response.headers.get("cache-control")?.toLowerCase() ?? "";
389
+ if (/(?:^|[\s,])(?:public|s-maxage)(?:[\s,=]|$)/.test(control)) return true;
390
+ for (const [name] of response.headers) if (sharedCacheHeader.test(name)) return true;
391
+ const context = Reflect.get(request, "context");
392
+ if (context === null || typeof context !== "object" || !Reflect.get(context, "nitro")) return true;
393
+ const rules = Reflect.get(context, "routeRules");
394
+ if (rules === void 0) return false;
395
+ if (rules === null || typeof rules !== "object") return true;
396
+ return sharedCacheRules.some((name) => {
397
+ const rule = Reflect.get(rules, name);
398
+ return rule !== void 0 && rule !== null && rule !== false;
399
+ });
400
+ }
401
+ function acceptsHtml(request) {
402
+ return request.headers.get("accept")?.split(",").some((range) => {
403
+ const [type, ...parameters] = range.split(";").map((part) => part.trim());
404
+ if (type?.toLowerCase() !== "text/html") return false;
405
+ const quality = parameters.find((part) => /^q\s*=/i.test(part))?.split("=")[1]?.trim();
406
+ return quality === void 0 || Number(quality) > 0 && Number(quality) <= 1;
407
+ }) === true;
408
+ }
409
+ function mayHandOffSession(request) {
410
+ return request.method === "GET" && !request.headers.has("x-nitro-prerender") && acceptsHtml(request) && (request.headers.has("cookie") || request.headers.has("authorization"));
411
+ }
412
+ function sessionRequestFor(request, base) {
413
+ const url = new URL(request.url);
414
+ const forwarded = request.headers.get("x-forwarded-proto")?.split(",", 1)[0]?.trim().toLowerCase();
415
+ if (forwarded && `${forwarded}:` !== url.protocol) return void 0;
416
+ const target = new URL(`${base}${viteHubPageSessionPath}`, url);
417
+ target.searchParams.set("page", url.pathname);
418
+ const activation = url.searchParams.get(viteHubPageToolsQuery);
419
+ if (activation) target.searchParams.set("open", activation);
420
+ const headers = new Headers(request.headers);
421
+ for (const name of [
422
+ ...pageConditions,
423
+ "origin",
424
+ "content-length",
425
+ "content-type",
426
+ "upgrade-insecure-requests",
427
+ "sec-fetch-user"
428
+ ]) headers.delete(name);
429
+ headers.set("accept", "application/json");
430
+ headers.set("sec-fetch-site", "same-origin");
431
+ headers.set("sec-fetch-mode", "cors");
432
+ headers.set("sec-fetch-dest", "empty");
433
+ const inner = new Request(target, { headers });
434
+ const runtime = Reflect.get(request, "runtime");
435
+ if (runtime !== null && typeof runtime === "object") Reflect.set(inner, "runtime", Object.fromEntries(Object.entries(runtime).filter(([key]) => key !== "node")));
436
+ for (const field of [
437
+ "ip",
438
+ "waitUntil",
439
+ "cf"
440
+ ]) {
441
+ const value = Reflect.get(request, field);
442
+ if (value === void 0) continue;
443
+ try {
444
+ Object.defineProperty(inner, field, {
445
+ configurable: true,
446
+ enumerable: true,
447
+ value
448
+ });
449
+ } catch {}
450
+ if (Reflect.get(inner, field) !== value) return void 0;
451
+ }
452
+ setApplicationRequestOrigin(inner, applicationRequestOrigin(request));
453
+ return inner;
454
+ }
455
+ function startHandoff(send, request, base) {
456
+ const inner = sessionRequestFor(request, base);
457
+ if (!inner) return void 0;
458
+ const pending = {};
459
+ const route = `${base}${viteHubPageSessionPath}`;
460
+ const page = new URL(request.url).pathname;
461
+ (async () => {
462
+ try {
463
+ const response = await send(inner);
464
+ if (!(response instanceof Response) || response.status !== 200 || response.headers.get(sessionCompleteHeader) !== "complete") return;
465
+ const session = readViteHubPageSession(await response.json());
466
+ const open = new URL(inner.url).searchParams.get("open");
467
+ if (session.tools.length > 0) pending.current = {
468
+ route,
469
+ page,
470
+ ...open ? { open } : {},
471
+ session
472
+ };
473
+ } catch {}
474
+ })();
475
+ return pending;
327
476
  }
328
477
  /**
329
478
  * Inserts the page tools bootstrap, `viteHubPageToolsInlineScript()`, before `</body>` of an HTML page for a request
@@ -347,12 +496,7 @@ function hasPageConditions(request) {
347
496
  /** Whether a request is a page navigation with validators, which must reach the app without them. */
348
497
  function revalidatesPage(request) {
349
498
  if (request.method !== "GET" && request.method !== "HEAD") return false;
350
- return request.headers.get("accept")?.split(",").some((range) => {
351
- const [type, ...parameters] = range.split(";").map((part) => part.trim());
352
- if (type?.toLowerCase() !== "text/html") return false;
353
- const quality = parameters.find((part) => /^q\s*=/i.test(part))?.split("=")[1]?.trim();
354
- return quality === void 0 || Number(quality) > 0 && Number(quality) <= 1;
355
- }) === true && hasPageConditions(request);
499
+ return acceptsHtml(request) && hasPageConditions(request);
356
500
  }
357
501
  /** The headers of the Node.js request that srvx keeps under `runtime.node.req`, when there is one. */
358
502
  function nodeRequestHeaders(request) {
@@ -384,7 +528,7 @@ function htmlCharset(type) {
384
528
  function isHtmlPage(response) {
385
529
  return response.status === 200 && (response.headers.get("content-type") ?? "").toLowerCase().startsWith("text/html");
386
530
  }
387
- function transformPage(response, tag, personal) {
531
+ function transformPage(response, tag, personal, late) {
388
532
  if (!isHtmlPage(response) || !response.body) return response;
389
533
  const type = response.headers.get("content-type") ?? "";
390
534
  const encoding = response.headers.get("content-encoding");
@@ -394,7 +538,7 @@ function transformPage(response, tag, personal) {
394
538
  const headers = new Headers(response.headers);
395
539
  for (const name of pageBodyHeaders) headers.delete(name);
396
540
  if (personal) headers.set("cache-control", "private, no-store");
397
- return new Response(response.body.pipeThrough(pageToolsHtmlTransform(tag())), {
541
+ return new Response(response.body.pipeThrough(pageToolsHtmlTransform(tag(), late)), {
398
542
  headers,
399
543
  status: response.status,
400
544
  statusText: response.statusText
@@ -410,12 +554,25 @@ function transformPage(response, tag, personal) {
410
554
  * It wraps `nitroApp.fetch`, the Web entry that every preset and the prerenderer call. The tag uses `options.base`.
411
555
  * It binds each request to the app in Nitro's `request` hook too, since another wrapper of `fetch` may pass a copy of
412
556
  * the request inward, such as the `security` policy of `vite-hub` on Node.js.
557
+ *
558
+ * With `sessionHandoff` enabled, it asks the session route beside the render for a navigation with credentials and puts a
559
+ * complete answer with at least one tool in the page: every visitor check and the account reader answered without
560
+ * throwing, so the tools and the account that it leaves out are the decision for this visitor. A page that a shared cache may
561
+ * store gets none: its headers say so (`public`, `s-maxage`, `Surrogate-Control`, any `*CDN-Cache-Control`), or the
562
+ * route rules that Nitro set on `request.context` have `isr`, `swr`, `cache` or `prerender`, which some presets turn
563
+ * into CDN headers after this point. A request without Nitro's `context.nitro`, such as a copy that another wrapper
564
+ * passed inward, has unknown rules and gets none. The server's request keeps the credentials and the host's request
565
+ * context (`runtime` without the Node.js request, `ip`, `waitUntil`, Cloudflare's `cf`). An app must not opt in if a
566
+ * browser-only input can change the session, or if a CDN can override the private cache policy. A proxy scheme that
567
+ * differs from the URL is left to the loader, since a `trustProxy`
568
+ * hook changes the URL of a real Node.js request and not of a copy.
413
569
  */
414
570
  function installViteHubPageTools(nitroApp, options = {}) {
415
571
  if (nitroApp === null || typeof nitroApp !== "object") return;
416
572
  const { installed, bases } = state();
417
573
  if (options.base !== void 0) bases.set(nitroApp, viteHubBasePath(options.base));
418
574
  if (options.origins !== void 0) (state().origins ??= /* @__PURE__ */ new WeakMap()).set(nitroApp, options.origins);
575
+ if (options.sessionHandoff === true) (state().sessionHandoffs ??= /* @__PURE__ */ new WeakSet()).add(nitroApp);
419
576
  if (installed.has(nitroApp)) return;
420
577
  installed.add(nitroApp);
421
578
  const hooks = Reflect.get(nitroApp, "hooks");
@@ -428,13 +585,21 @@ function installViteHubPageTools(nitroApp, options = {}) {
428
585
  Reflect.set(nitroApp, "fetch", async (request, ...rest) => {
429
586
  const base = state().bases.get(nitroApp) ?? "";
430
587
  const conditional = request instanceof Request && hasPageConditions(request);
431
- const early = conditional ? pageAddition(nitroApp, request, base) : void 0;
588
+ const handing = state().sessionHandoffs?.has(nitroApp) === true && request instanceof Request && mayHandOffSession(request);
589
+ const early = conditional || handing ? pageAddition(nitroApp, request, base) : void 0;
590
+ const pending = handing && early === "loader" ? startHandoff(async (inner) => {
591
+ state().apps.set(inner, nitroApp);
592
+ return await Reflect.apply(fetch, nitroApp, [inner]);
593
+ }, request, base) : void 0;
432
594
  if (early && revalidatesPage(request)) request = withoutPageConditions(request);
433
595
  if (request instanceof Request) state().apps.set(request, nitroApp);
434
596
  const response = await Reflect.apply(fetch, nitroApp, [request, ...rest]);
435
597
  if (!(response instanceof Response) || !(request instanceof Request) || !isHtmlPage(response)) return response;
436
- const addition = conditional ? early : pageAddition(nitroApp, request, base);
437
- if (addition === "loader") return injectPageToolsLoader(response, base);
598
+ const addition = conditional || handing ? early : pageAddition(nitroApp, request, base);
599
+ if (addition === "loader") {
600
+ const handoff = pending && !sharedCacheMayStore(request, response) ? pending : void 0;
601
+ return transformPage(response, () => loaderTag(base, scriptNonce(response.headers)), true, handoff && ((nonce) => handoff.current ? handoffMarkup(handoff.current, nonce) : ""));
602
+ }
438
603
  return addition === "bootstrap" ? injectPageToolsBootstrap(response, base) : response;
439
604
  });
440
605
  return;
@@ -495,7 +660,7 @@ async function resolveCommentsPage(comments, event, request, path) {
495
660
  } };
496
661
  getStandardContext(event);
497
662
  const mapped = await comments.options.page({
498
- url: new URL(id, applicationRequestOrigin(request)),
663
+ url: new URL(id, applicationRequestOrigin(clientRequest(request))),
499
664
  event
500
665
  });
501
666
  if (!mapped) return { subject: {
@@ -510,4 +675,4 @@ async function resolveCommentsPage(comments, event, request, path) {
510
675
  ...mapped.revision === void 0 ? {} : { revision: mapped.revision }
511
676
  };
512
677
  }
513
- export { registerViteHubPageTool as a, installViteHubSiteVisitor as i, resolveCommentsPage as n, viteHubPageSessionHandler as o, installViteHubPageTools as r, resolveCommentsIdentity as t };
678
+ export { registerViteHubPageTool as a, installViteHubSiteVisitor as i, resolveCommentsPage as n, viteHubPageSessionHandler as o, installViteHubPageTools as r, applicationRequestOrigin as s, resolveCommentsIdentity as t };
@@ -1,6 +1,5 @@
1
- import "./index-D1T7RJ4R.js";
2
- import { g as CommentsUser } from "./define-B1jLSPe9.js";
3
- import { f as CommentsRequestEvent } from "./types-l6GOb_yc.js";
1
+ import "./index-d6NsDxu9.js";
2
+ import { j as CommentsUser, s as CommentsRequestEvent } from "./types-qzJKgWYS.js";
4
3
  interface CommentsSessionOptions {
5
4
  /** Reads the ViteHub Auth user only when no custom `identify` is configured. */
6
5
  session?: (event: CommentsRequestEvent) => Promise<CommentsUser | null | undefined>;
@@ -10,6 +10,4 @@ const commentsTableNames = {
10
10
  vitehubCommentCounters: "vitehub_comment_counters",
11
11
  vitehubCommentForge: "vitehub_comment_forge"
12
12
  };
13
- /** The tables of `commentSendsSchema`: each schema key and its SQL name. Comments adds them when `send` is on. */
14
- const commentSendsTableNames = { commentSends: "vitehub_comment_sends" };
15
- export { commentsTableNames as n, commentSendsTableNames as t };
13
+ export { commentsTableNames as t };
package/dist/testing.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as replyMessageId } from "./reply-id-Cm9FGOBs.js";
2
- import { t as commentsErrorDiagnostics } from "./errors-CBvIpwbo.js";
2
+ import { t as commentsErrorDiagnostics } from "./errors-DeSEHzRf.js";
3
3
  // src/operations-core/testing.ts
4
4
  function checkOutboxAccount(input, user) {
5
5
  if (input.outbox && input.outbox.account !== user.id) throw Object.assign(commentsErrorDiagnostics.COMMENTS_OUTBOX_ACCOUNT_CHANGED(), { status: 401 });