@vercel/geistdocs 2.14.5 → 2.14.7-canary.6ce58a6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/assets/icons/icon-share.d.ts +13 -0
  2. package/dist/assets/icons/icon-share.d.ts.map +1 -0
  3. package/dist/assets/icons/icon-share.js +12 -0
  4. package/dist/assets/icons/index.d.ts +1 -0
  5. package/dist/assets/icons/index.d.ts.map +1 -1
  6. package/dist/assets/icons/index.js +1 -0
  7. package/dist/cli/index.js +5 -5
  8. package/dist/config.d.ts +38 -3
  9. package/dist/config.d.ts.map +1 -1
  10. package/dist/controls.d.ts +3 -40
  11. package/dist/controls.d.ts.map +1 -1
  12. package/dist/controls.js +5 -96
  13. package/dist/internal/chat/share-chat.d.ts +7 -0
  14. package/dist/internal/chat/share-chat.d.ts.map +1 -0
  15. package/dist/internal/chat/share-chat.js +76 -0
  16. package/dist/internal/chat/sharing.d.ts +24 -0
  17. package/dist/internal/chat/sharing.d.ts.map +1 -0
  18. package/dist/internal/chat/sharing.js +117 -0
  19. package/dist/internal/chat/shell.d.ts.map +1 -1
  20. package/dist/internal/chat/shell.js +2 -1
  21. package/dist/internal/chat-retrieval.d.ts +10 -9
  22. package/dist/internal/chat-retrieval.d.ts.map +1 -1
  23. package/dist/internal/chat-retrieval.js +32 -68
  24. package/dist/internal/controls-client.d.ts +40 -0
  25. package/dist/internal/controls-client.d.ts.map +1 -0
  26. package/dist/internal/controls-client.js +87 -0
  27. package/dist/internal/language-selector.d.ts +2 -0
  28. package/dist/internal/language-selector.d.ts.map +1 -0
  29. package/dist/internal/language-selector.js +12 -0
  30. package/dist/internal/mixedbread-store.d.ts +53 -0
  31. package/dist/internal/mixedbread-store.d.ts.map +1 -0
  32. package/dist/internal/mixedbread-store.js +129 -0
  33. package/dist/internal/navbar/mobile-menu.js +1 -1
  34. package/dist/internal/page-action-options.d.ts +37 -0
  35. package/dist/internal/page-action-options.d.ts.map +1 -0
  36. package/dist/internal/page-action-options.js +39 -0
  37. package/dist/internal/page-actions-client.d.ts +1 -31
  38. package/dist/internal/page-actions-client.d.ts.map +1 -1
  39. package/dist/internal/page-actions-client.js +5 -103
  40. package/dist/internal/page-actions-gate.d.ts +3 -0
  41. package/dist/internal/page-actions-gate.d.ts.map +1 -0
  42. package/dist/internal/page-actions-gate.js +15 -0
  43. package/dist/internal/provider-client.d.ts.map +1 -1
  44. package/dist/internal/provider-client.js +26 -1
  45. package/dist/internal/relative-docs-link.d.ts +7 -0
  46. package/dist/internal/relative-docs-link.d.ts.map +1 -0
  47. package/dist/internal/relative-docs-link.js +22 -0
  48. package/dist/internal/sidebar.d.ts.map +1 -1
  49. package/dist/internal/sidebar.js +1 -1
  50. package/dist/internal/toc-actions-client.d.ts +9 -0
  51. package/dist/internal/toc-actions-client.d.ts.map +1 -0
  52. package/dist/internal/toc-actions-client.js +78 -0
  53. package/dist/mdx.d.ts.map +1 -1
  54. package/dist/mdx.js +5 -2
  55. package/dist/navbar.js +1 -1
  56. package/dist/pages/changelog.js +1 -1
  57. package/dist/pages/docs.d.ts.map +1 -1
  58. package/dist/pages/docs.js +4 -3
  59. package/dist/routes/chat.d.ts +4 -4
  60. package/dist/routes/chat.d.ts.map +1 -1
  61. package/dist/routes/chat.js +19 -34
  62. package/dist/routes/openapi.d.ts.map +1 -1
  63. package/dist/routes/openapi.js +13 -5
  64. package/dist/routes/search-export.d.ts +1 -1
  65. package/dist/routes/search-export.d.ts.map +1 -1
  66. package/dist/routes/search-export.js +5 -2
  67. package/dist/routes/search.d.ts +10 -2
  68. package/dist/routes/search.d.ts.map +1 -1
  69. package/dist/routes/search.js +215 -55
  70. package/docs/agents.md +3 -3
  71. package/docs/llms.txt +237 -32
  72. package/docs/manifest.json +5 -5
  73. package/docs/pages/ask-ai.md +17 -1
  74. package/docs/pages/configuration.md +33 -3
  75. package/docs/pages/env.md +5 -5
  76. package/docs/pages/index.md +1 -1
  77. package/docs/pages/llms-txt.md +1 -1
  78. package/docs/pages/mixedbread-retrieval.md +174 -18
  79. package/docs/pages/provider.md +3 -0
  80. package/docs/sitemap.md +2 -2
  81. package/package.json +6 -6
  82. package/template/.env.example +1 -0
  83. package/template/AGENTS.md +11 -7
  84. package/template/content/docs/ask-ai.mdx +17 -1
  85. package/template/content/docs/configuration.mdx +33 -3
  86. package/template/content/docs/env.mdx +5 -5
  87. package/template/content/docs/index.mdx +1 -1
  88. package/template/content/docs/llms-txt.mdx +1 -1
  89. package/template/content/docs/mixedbread-retrieval.mdx +174 -18
  90. package/template/content/docs/provider.mdx +3 -0
  91. package/template/geistdocs.tsx +6 -1
  92. package/template/lib/geistdocs/config.tsx +2 -0
  93. package/template/package.json +1 -1
@@ -0,0 +1,117 @@
1
+ import { getPublicPath } from "../../config.js";
2
+ const DEFAULT_SHARE_PATH = "/ai-chat";
3
+ const INVALID_PATH_CHARACTERS = /[\s?#\\]/;
4
+ const MAX_ERROR_DETAILS_LENGTH = 500;
5
+ const MAX_SUMMARY_LENGTH = 512;
6
+ export class ChatShareError extends Error {
7
+ details;
8
+ status;
9
+ constructor(message, options = {}) {
10
+ super(message);
11
+ this.name = "ChatShareError";
12
+ this.details = options.details;
13
+ this.status = options.status;
14
+ }
15
+ }
16
+ const resolveAppLocalPath = (value, option) => {
17
+ if (typeof value !== "string" ||
18
+ !value.startsWith("/") ||
19
+ value.startsWith("//") ||
20
+ value === "/" ||
21
+ INVALID_PATH_CHARACTERS.test(value)) {
22
+ throw new Error(`${option} must be a root-relative path without a query string, fragment, whitespace, or backslashes. Received ${JSON.stringify(value)}.`);
23
+ }
24
+ if (new URL(value, "https://geistdocs.local").pathname !== value ||
25
+ value.endsWith("/")) {
26
+ throw new Error(`${option} must be a normalized path without "." or ".." segments, characters that need percent-encoding, or a trailing slash. Received ${JSON.stringify(value)}.`);
27
+ }
28
+ return value;
29
+ };
30
+ export const resolveChatShareConfig = (share, basePath) => ({
31
+ endpoint: getPublicPath(resolveAppLocalPath(share.endpoint, "ai.share.endpoint"), basePath),
32
+ path: getPublicPath(resolveAppLocalPath(share.path ?? DEFAULT_SHARE_PATH, "ai.share.path"), basePath),
33
+ });
34
+ export const hasShareableMessages = (messages) => messages.some((message) => message.parts.some((part) => part.type === "text" && part.text.trim().length > 0));
35
+ const getShareSummary = (messages) => {
36
+ const firstQuestion = messages.find((message) => message.role === "user");
37
+ const summary = firstQuestion?.parts
38
+ .filter((part) => part.type === "text")
39
+ .map((part) => part.text)
40
+ .join("\n")
41
+ .trim();
42
+ return summary ? summary.slice(0, MAX_SUMMARY_LENGTH) : undefined;
43
+ };
44
+ const asRecord = (value) => value && typeof value === "object" && !Array.isArray(value)
45
+ ? value
46
+ : undefined;
47
+ const bounded = (value) => {
48
+ const trimmed = value?.trim();
49
+ return trimmed ? trimmed.slice(0, MAX_ERROR_DETAILS_LENGTH) : undefined;
50
+ };
51
+ const responseErrorDetails = async (response) => {
52
+ try {
53
+ const contentType = response.headers.get("content-type") ?? "";
54
+ if (!contentType.includes("application/json")) {
55
+ return bounded(await response.text());
56
+ }
57
+ const body = asRecord(await response.json());
58
+ const error = body?.error;
59
+ if (typeof error === "string") {
60
+ return bounded(error);
61
+ }
62
+ const nested = asRecord(error);
63
+ if (typeof nested?.message === "string") {
64
+ return bounded(nested.message);
65
+ }
66
+ return typeof body?.message === "string"
67
+ ? bounded(body.message)
68
+ : undefined;
69
+ }
70
+ catch {
71
+ return undefined;
72
+ }
73
+ };
74
+ export const createChatShareUrl = async ({ endpoint, hostPath, messages, origin, path, }) => {
75
+ let response;
76
+ try {
77
+ response = await fetch(endpoint, {
78
+ body: JSON.stringify({
79
+ hostPath,
80
+ messages,
81
+ summary: getShareSummary(messages),
82
+ }),
83
+ headers: { "Content-Type": "application/json" },
84
+ method: "POST",
85
+ });
86
+ }
87
+ catch (error) {
88
+ throw new ChatShareError("Share link request failed", {
89
+ details: error instanceof Error ? error.message : undefined,
90
+ });
91
+ }
92
+ if (!response.ok) {
93
+ throw new ChatShareError("Share link request failed", {
94
+ details: await responseErrorDetails(response),
95
+ status: response.status,
96
+ });
97
+ }
98
+ let body;
99
+ try {
100
+ body = await response.json();
101
+ }
102
+ catch (error) {
103
+ throw new ChatShareError("Share link response was invalid", {
104
+ details: error instanceof Error ? error.message : undefined,
105
+ });
106
+ }
107
+ const shareId = asRecord(body)?.shareId;
108
+ if (typeof shareId !== "string" || !shareId) {
109
+ throw new ChatShareError("Share link response did not include a share ID");
110
+ }
111
+ const url = new URL(origin);
112
+ url.pathname = `${path}/${encodeURIComponent(shareId)}`;
113
+ return url.toString();
114
+ };
115
+ export const getChatShareErrorText = (error) => error.status === 429
116
+ ? "Too many attempts. Try again in a minute."
117
+ : "Failed to create chat link. Please try again.";
@@ -1 +1 @@
1
- {"version":3,"file":"shell.d.ts","sourceRoot":"","sources":["../../../src/internal/chat/shell.tsx"],"names":[],"mappings":"AAgfA,eAAO,MAAM,kBAAkB,sDAiE9B,CAAC"}
1
+ {"version":3,"file":"shell.d.ts","sourceRoot":"","sources":["../../../src/internal/chat/shell.tsx"],"names":[],"mappings":"AAkfA,eAAO,MAAM,kBAAkB,sDAiE9B,CAAC"}
@@ -24,6 +24,7 @@ import { MessageMetadata } from "./message-metadata";
24
24
  import { ChatMessagePageChip, ChatPageAttachmentCard } from "./page-attachment";
25
25
  import { ChatPromptInput } from "./prompt-input";
26
26
  import { GeistdocsChatSessionProvider, useChatSession, } from "./session-provider";
27
+ import { ShareChat } from "./share-chat";
27
28
  import { Suggestion, Suggestions } from "./suggestion";
28
29
  import { useChatCommands } from "./use-chat-commands";
29
30
  import { useChatUserAvatar } from "./user-avatar";
@@ -115,7 +116,7 @@ const GeistdocsChatPanel = ({ clearConversation, expandable, session, textareaRe
115
116
  });
116
117
  }
117
118
  };
118
- return (_jsxs("aside", { "aria-label": `${chatTitle} chat`, className: "flex size-full w-full flex-col overflow-hidden whitespace-nowrap bg-background-100", children: [_jsxs("div", { className: cn("sticky top-0 z-10 flex h-16 shrink-0 items-center justify-between bg-background-100 py-2 pr-2 pl-3.5", isExpanded && EXPANDED_COLUMN), children: [_jsx("h2", { className: "font-semibold text-sm", children: chatTitle }), _jsxs("div", { className: "flex items-center gap-0.5", children: [_jsx(CopyChat, { messages: messages }), expandable ? (_jsx(Tooltip, { position: "bottom", text: expandLabel, children: _jsx(Button, { "aria-label": expandLabel, "aria-pressed": isExpanded, className: "text-gray-800! shadow-none", onClick: () => setIsExpanded(!isExpanded), shape: "square", size: "small", svgOnly: true, typeName: "button", variant: "tertiary", children: isExpanded ? (_jsx(IconFullscreenClose, { size: 14 })) : (_jsx(IconFullscreen, { size: 14 })) }) })) : null, _jsx(Tooltip, { position: "bottom", text: "Delete chat", children: _jsx(Button, { "aria-label": "Delete chat", className: "text-gray-800! disabled:bg-gray-alpha-100!", disabled: messages.length === 0 ||
119
+ return (_jsxs("aside", { "aria-label": `${chatTitle} chat`, className: "flex size-full w-full flex-col overflow-hidden whitespace-nowrap bg-background-100", children: [_jsxs("div", { className: cn("sticky top-0 z-10 flex h-16 shrink-0 items-center justify-between bg-background-100 py-2 pr-2 pl-3.5", isExpanded && EXPANDED_COLUMN), children: [_jsx("h2", { className: "font-semibold text-sm", children: chatTitle }), _jsxs("div", { className: "flex items-center gap-0.5", children: [_jsx(CopyChat, { messages: messages }), _jsx(ShareChat, { messages: messages, textareaRef: textareaRef }), expandable ? (_jsx(Tooltip, { position: "bottom", text: expandLabel, children: _jsx(Button, { "aria-label": expandLabel, "aria-pressed": isExpanded, className: "text-gray-800! shadow-none", onClick: () => setIsExpanded(!isExpanded), shape: "square", size: "small", svgOnly: true, typeName: "button", variant: "tertiary", children: isExpanded ? (_jsx(IconFullscreenClose, { size: 14 })) : (_jsx(IconFullscreen, { size: 14 })) }) })) : null, _jsx(Tooltip, { position: "bottom", text: "Delete chat", children: _jsx(Button, { "aria-label": "Delete chat", className: "text-gray-800! disabled:bg-gray-alpha-100!", disabled: messages.length === 0 ||
119
120
  status === "streaming" ||
120
121
  status === "submitted", onClick: handleClearChat, shape: "square", size: "small", svgOnly: true, typeName: "button", variant: "tertiary", children: _jsx(IconTrash, { size: 14 }) }) }), _jsx(Tooltip, { position: "bottom", text: "Close chat", children: _jsx(Button, { "aria-label": "Close chat", className: "text-gray-800! shadow-none", onClick: () => setIsOpen(false), shape: "square", size: "small", svgOnly: true, typeName: "button", variant: "tertiary", children: _jsx(IconChevronDoubleRight, { size: 14 }) }) })] })] }), _jsxs(Conversation, { children: [_jsxs(ConversationContent, { className: cn(isExpanded && EXPANDED_COLUMN), children: [messages.map((message, index) => {
121
122
  const inProgress = isActiveAssistantMessage({
@@ -1,4 +1,7 @@
1
- import { type CreateMixedbreadClientOptions, type MixedbreadClient } from "./mixedbread.js";
1
+ import { type GeistdocsRetrievalProvider } from "../config.js";
2
+ import type { GeistdocsPageFilter } from "../page-visibility.js";
3
+ import type { GeistdocsSourceBundle } from "../source.js";
4
+ import { type GeistdocsMixedbreadOptions } from "./mixedbread-store.js";
2
5
  export interface ChatRetrievalDocument {
3
6
  content: string;
4
7
  description: string;
@@ -12,21 +15,19 @@ export interface ChatRetrievalInput {
12
15
  query: string;
13
16
  }
14
17
  export type ChatDocumentSearch = (input: ChatRetrievalInput) => Promise<ChatRetrievalDocument[]>;
15
- export type ChatMixedbreadOptions = Partial<Pick<CreateMixedbreadClientOptions, "apiBaseUrl" | "apiKey" | "fetchImpl" | "requestTimeoutMs" | "storeId">>;
16
- export declare const createMixedbreadDocumentSearch: ({ client, siteId, }: {
17
- client: MixedbreadClient;
18
- siteId: string;
19
- }) => ChatDocumentSearch;
20
18
  export declare const withChatRetrievalFallback: ({ fallback, onFallback, primary, }: {
21
19
  fallback: ChatDocumentSearch;
22
20
  onFallback?: (error: unknown) => void;
23
21
  primary: ChatDocumentSearch;
24
22
  }) => ChatDocumentSearch;
25
- export declare const createChatDocumentSearch: ({ fallback, mixedbread, onWarning, provider, siteId, }: {
23
+ export declare const createChatDocumentSearch: ({ basePath, fallback, filterPage, mixedbread, onWarning, provider, siteId, sources, }: {
24
+ basePath?: string;
26
25
  fallback: ChatDocumentSearch;
27
- mixedbread?: ChatMixedbreadOptions;
26
+ filterPage?: GeistdocsPageFilter;
27
+ mixedbread?: GeistdocsMixedbreadOptions;
28
28
  onWarning?: (message: string, error?: unknown) => void;
29
- provider?: "local" | "mixedbread";
29
+ provider?: GeistdocsRetrievalProvider;
30
30
  siteId?: string;
31
+ sources: GeistdocsSourceBundle[];
31
32
  }) => ChatDocumentSearch;
32
33
  //# sourceMappingURL=chat-retrieval.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"chat-retrieval.d.ts","sourceRoot":"","sources":["../../src/internal/chat-retrieval.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,6BAA6B,EAElC,KAAK,gBAAgB,EAEtB,MAAM,iBAAiB,CAAC;AAIzB,MAAM,WAAW,qBAAqB;IACpC,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,MAAM,kBAAkB,GAAG,CAC/B,KAAK,EAAE,kBAAkB,KACtB,OAAO,CAAC,qBAAqB,EAAE,CAAC,CAAC;AAEtC,MAAM,MAAM,qBAAqB,GAAG,OAAO,CACzC,IAAI,CACF,6BAA6B,EAC7B,YAAY,GAAG,QAAQ,GAAG,WAAW,GAAG,kBAAkB,GAAG,SAAS,CACvE,CACF,CAAC;AAgBF,eAAO,MAAM,8BAA8B,GACxC,qBAGE;IACD,MAAM,EAAE,gBAAgB,CAAC;IACzB,MAAM,EAAE,MAAM,CAAC;CAChB,KAAG,kBA6CH,CAAC;AAEJ,eAAO,MAAM,yBAAyB,GACnC,oCAIE;IACD,QAAQ,EAAE,kBAAkB,CAAC;IAC7B,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;IACtC,OAAO,EAAE,kBAAkB,CAAC;CAC7B,KAAG,kBAQH,CAAC;AAEJ,eAAO,MAAM,wBAAwB,GAAI,wDAMtC;IACD,QAAQ,EAAE,kBAAkB,CAAC;IAC7B,UAAU,CAAC,EAAE,qBAAqB,CAAC;IACnC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;IACvD,QAAQ,CAAC,EAAE,OAAO,GAAG,YAAY,CAAC;IAClC,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,KAAG,kBA8CH,CAAC"}
1
+ {"version":3,"file":"chat-retrieval.d.ts","sourceRoot":"","sources":["../../src/internal/chat-retrieval.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,0BAA0B,EAAiB,MAAM,cAAc,CAAC;AAC9E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAC1D,OAAO,EAEL,KAAK,0BAA0B,EAGhC,MAAM,uBAAuB,CAAC;AAM/B,MAAM,WAAW,qBAAqB;IACpC,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,MAAM,kBAAkB,GAAG,CAC/B,KAAK,EAAE,kBAAkB,KACtB,OAAO,CAAC,qBAAqB,EAAE,CAAC,CAAC;AAatC,eAAO,MAAM,yBAAyB,GACnC,oCAIE;IACD,QAAQ,EAAE,kBAAkB,CAAC;IAC7B,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;IACtC,OAAO,EAAE,kBAAkB,CAAC;CAC7B,KAAG,kBAQH,CAAC;AAEJ,eAAO,MAAM,wBAAwB,GAAI,uFAStC;IACD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,kBAAkB,CAAC;IAC7B,UAAU,CAAC,EAAE,mBAAmB,CAAC;IACjC,UAAU,CAAC,EAAE,0BAA0B,CAAC;IACxC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;IACvD,QAAQ,CAAC,EAAE,0BAA0B,CAAC;IACtC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,qBAAqB,EAAE,CAAC;CAClC,KAAG,kBA4CH,CAAC"}
@@ -1,50 +1,15 @@
1
- import { createMixedbreadClient, readGeistdocsMixedbreadMetadata, } from "./mixedbread.js";
1
+ import { getPublicPath } from "../config.js";
2
+ import { createStoreReader, resolveMixedbreadConnection, } from "./mixedbread-store.js";
2
3
  const MIXEDBREAD_REQUEST_TIMEOUT_MS = 2000;
3
- const getChunkContent = (chunk) => {
4
- for (const value of [chunk.text, chunk.summary, chunk.context]) {
5
- if (typeof value === "string" && value.trim()) {
6
- return value.trim();
7
- }
8
- }
9
- return "";
10
- };
11
- export const createMixedbreadDocumentSearch = ({ client, siteId, }) => async ({ lang, limit, query }) => {
12
- const chunks = await client.search({
13
- locale: lang,
14
- query,
15
- siteId,
16
- topK: Math.max(limit, limit * 3),
17
- });
18
- const documents = new Map();
19
- for (const chunk of chunks) {
20
- const metadata = readGeistdocsMixedbreadMetadata(chunk.metadata);
21
- const content = getChunkContent(chunk);
22
- if (!metadata ||
23
- metadata.siteId !== siteId ||
24
- metadata.locale !== lang ||
25
- !content) {
26
- continue;
27
- }
28
- const existing = documents.get(metadata.documentId);
29
- if (existing) {
30
- if (!existing.content.includes(content)) {
31
- existing.content = `${existing.content}\n\n${content}`;
32
- }
33
- continue;
34
- }
35
- documents.set(metadata.documentId, {
36
- content,
37
- description: metadata.description,
38
- slug: metadata.sourceUrl,
39
- title: metadata.title,
40
- url: metadata.url,
41
- });
42
- if (documents.size === limit) {
43
- break;
44
- }
45
- }
46
- return Array.from(documents.values());
47
- };
4
+ const CANDIDATE_PAGES_PER_RESULT = 3;
5
+ const CHUNKS_PER_CANDIDATE_PAGE = 3;
6
+ const toChatDocument = ({ chunks, page }, basePath) => ({
7
+ content: chunks.map((chunk) => chunk.text).join("\n\n"),
8
+ description: page.data.description ?? "",
9
+ slug: page.url,
10
+ title: page.data.title ?? page.url,
11
+ url: getPublicPath(page.url, basePath),
12
+ });
48
13
  export const withChatRetrievalFallback = ({ fallback, onFallback, primary, }) => async (input) => {
49
14
  try {
50
15
  return await primary(input);
@@ -54,36 +19,35 @@ export const withChatRetrievalFallback = ({ fallback, onFallback, primary, }) =>
54
19
  return fallback(input);
55
20
  }
56
21
  };
57
- export const createChatDocumentSearch = ({ fallback, mixedbread, onWarning, provider, siteId, }) => {
22
+ export const createChatDocumentSearch = ({ basePath, fallback, filterPage, mixedbread, onWarning, provider, siteId, sources, }) => {
58
23
  if (provider !== "mixedbread") {
59
24
  return fallback;
60
25
  }
61
- const apiKey = mixedbread?.apiKey?.trim();
62
- const storeId = mixedbread?.storeId?.trim();
63
- const normalizedSiteId = siteId?.trim();
64
- const missing = [
65
- !apiKey && "MXBAI_API_KEY",
66
- !storeId && "MXBAI_STORE_ID",
67
- !normalizedSiteId && "config.siteId",
68
- ].filter((value) => Boolean(value));
69
- if (!(apiKey && storeId && normalizedSiteId)) {
70
- onWarning?.(`[Geistdocs chat] Mixedbread retrieval is enabled but ${missing.join(", ")} is missing. Falling back to local search.`);
26
+ const connection = resolveMixedbreadConnection({
27
+ defaultTimeoutMs: MIXEDBREAD_REQUEST_TIMEOUT_MS,
28
+ options: mixedbread,
29
+ siteId,
30
+ });
31
+ if (connection.status === "unconfigured") {
32
+ onWarning?.(`[Geistdocs chat] Mixedbread retrieval is enabled but ${connection.missing.join(", ")} is missing. Falling back to local search.`);
71
33
  return fallback;
72
34
  }
73
- const primary = createMixedbreadDocumentSearch({
74
- client: createMixedbreadClient({
75
- apiBaseUrl: mixedbread?.apiBaseUrl,
76
- apiKey,
77
- fetchImpl: mixedbread?.fetchImpl,
78
- maxRetries: 0,
79
- requestTimeoutMs: mixedbread?.requestTimeoutMs ?? MIXEDBREAD_REQUEST_TIMEOUT_MS,
80
- storeId,
81
- }),
82
- siteId: normalizedSiteId,
35
+ const readStore = createStoreReader({
36
+ connection,
37
+ filterPage,
38
+ sources,
39
+ surface: "chat",
83
40
  });
84
41
  return withChatRetrievalFallback({
85
42
  fallback,
86
- primary,
43
+ primary: async ({ lang, limit, query }) => {
44
+ const hits = await readStore({
45
+ locale: lang,
46
+ query,
47
+ topK: limit * CANDIDATE_PAGES_PER_RESULT * CHUNKS_PER_CANDIDATE_PAGE,
48
+ });
49
+ return hits.slice(0, limit).map((hit) => toChatDocument(hit, basePath));
50
+ },
87
51
  onFallback: (error) => {
88
52
  onWarning?.("[Geistdocs chat] Mixedbread retrieval failed. Falling back to local search.", error);
89
53
  },
@@ -0,0 +1,40 @@
1
+ import { type ReactNode } from "react";
2
+ import { type GeistdocsChatController } from "./chat/context";
3
+ export type { GeistdocsChatController, GeistdocsChatPage, } from "./chat/context";
4
+ /**
5
+ * Control the Ask AI chat from custom components rendered inside
6
+ * `GeistdocsProvider`.
7
+ */
8
+ export declare const useGeistdocsChat: () => GeistdocsChatController;
9
+ interface SearchButtonProps {
10
+ className?: string;
11
+ onClick?: () => void;
12
+ }
13
+ export declare const SearchButton: ({ className, onClick }: SearchButtonProps) => import("react/jsx-runtime").JSX.Element;
14
+ export declare const ThemeToggle: () => import("react/jsx-runtime").JSX.Element;
15
+ interface AskAIButtonProps {
16
+ children?: ReactNode;
17
+ className?: string;
18
+ disabled?: boolean;
19
+ prompt?: string;
20
+ size?: "tiny" | "small" | "medium" | "large" | null;
21
+ variant?: "default" | "secondary" | "tertiary";
22
+ }
23
+ export declare const AskAIButton: ({ children, className, prompt, size, variant, ...props }: AskAIButtonProps) => import("react/jsx-runtime").JSX.Element | null;
24
+ export interface AskAIUserProps {
25
+ /**
26
+ * The reader's avatar. Only `http(s)` URLs and root-relative paths are
27
+ * rendered; other values are ignored. `null` is accepted for auth session
28
+ * fields that may be empty.
29
+ */
30
+ avatarUrl?: string | null;
31
+ /** The reader's name, used as the avatar's alt text. */
32
+ name?: string | null;
33
+ }
34
+ /**
35
+ * Identify the signed-in reader to Ask AI. Renders nothing; while mounted
36
+ * with an `avatarUrl`, the reader's avatar appears beside their chat
37
+ * messages. Unmount it, or pass no `avatarUrl`, to clear the reader.
38
+ */
39
+ export declare const AskAIUser: ({ avatarUrl, name }: AskAIUserProps) => null;
40
+ //# sourceMappingURL=controls-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"controls-client.d.ts","sourceRoot":"","sources":["../../src/internal/controls-client.tsx"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,SAAS,EAAgC,MAAM,OAAO,CAAC;AAMrE,OAAO,EACL,KAAK,uBAAuB,EAE7B,MAAM,gBAAgB,CAAC;AAExB,YAAY,EACV,uBAAuB,EACvB,iBAAiB,GAClB,MAAM,gBAAgB,CAAC;AAExB;;;GAGG;AACH,eAAO,MAAM,gBAAgB,QAAO,uBAwBnC,CAAC;AAEF,UAAU,iBAAiB;IACzB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;CACtB;AAED,eAAO,MAAM,YAAY,GAAI,wBAAwB,iBAAiB,4CAqBrE,CAAC;AAEF,eAAO,MAAM,WAAW,+CA0CvB,CAAC;AAEF,UAAU,gBAAgB;IACxB,QAAQ,CAAC,EAAE,SAAS,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,GAAG,QAAQ,GAAG,OAAO,GAAG,IAAI,CAAC;IACpD,OAAO,CAAC,EAAE,SAAS,GAAG,WAAW,GAAG,UAAU,CAAC;CAChD;AAED,eAAO,MAAM,WAAW,GAAI,0DAOzB,gBAAgB,mDAgClB,CAAC;AAEF,MAAM,WAAW,cAAc;IAC7B;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,wDAAwD;IACxD,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACtB;AAED;;;;GAIG;AACH,eAAO,MAAM,SAAS,GAAI,qBAAqB,cAAc,SAc5D,CAAC"}
@@ -0,0 +1,87 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useSearchContext } from "fumadocs-ui/contexts/search";
4
+ import { useEffect, useMemo, useState } from "react";
5
+ import { IconMoon, IconSun } from "#geistdocs-assets/icons";
6
+ import { Button } from "#geistdocs-ui/components/button";
7
+ import { Kbd } from "#geistdocs-ui/components/kbd";
8
+ import { useTheme } from "#geistdocs-ui/core";
9
+ import { cn } from "#geistdocs-ui/utils";
10
+ import { useGeistdocsChatContext, } from "./chat/context";
11
+ /**
12
+ * Control the Ask AI chat from custom components rendered inside
13
+ * `GeistdocsProvider`.
14
+ */
15
+ export const useGeistdocsChat = () => {
16
+ const { ask, enabled, isOpen, openWithPage, setIsOpen } = useGeistdocsChatContext();
17
+ return useMemo(() => ({
18
+ ask,
19
+ close: () => setIsOpen(false),
20
+ enabled,
21
+ isOpen,
22
+ open: () => {
23
+ if (enabled) {
24
+ setIsOpen(true);
25
+ }
26
+ },
27
+ openWithPage,
28
+ toggle: () => {
29
+ if (enabled) {
30
+ setIsOpen((open) => !open);
31
+ }
32
+ },
33
+ }), [ask, enabled, isOpen, openWithPage, setIsOpen]);
34
+ };
35
+ export const SearchButton = ({ className, onClick }) => {
36
+ const { setOpenSearch } = useSearchContext();
37
+ return (_jsxs("button", { className: cn("flex h-8 cursor-pointer items-center justify-between rounded-md border-0 bg-background-100 py-0 pr-1.5 pl-3.5 font-normal font-sans text-gray-1000 text-sm shadow-[0_0_0_1px_var(--ds-gray-400)] outline-none hover:bg-gray-100 focus-visible:shadow-[var(--ds-focus-ring)]", className), onClick: () => {
38
+ setOpenSearch(true);
39
+ onClick?.();
40
+ }, type: "button", children: [_jsx("span", { className: "pr-6", children: "Search\u2026" }), _jsx(Kbd, { className: "inline-flex items-center justify-center rounded", small: true, children: "\u2318K" })] }));
41
+ };
42
+ export const ThemeToggle = () => {
43
+ const { resolvedTheme, setTheme } = useTheme();
44
+ const [mounted, setMounted] = useState(false);
45
+ useEffect(() => {
46
+ setMounted(true);
47
+ }, []);
48
+ if (!mounted) {
49
+ return (_jsx(Button, { "aria-label": "Toggle Theme", shape: "square", size: "small", svgOnly: true, type: "unstyled", typeName: "button", children: _jsx("div", { className: "size-4" }) }));
50
+ }
51
+ const Icon = resolvedTheme === "dark" ? IconMoon : IconSun;
52
+ return (_jsx(Button, { "aria-label": resolvedTheme === "dark"
53
+ ? "Switch to Light Theme"
54
+ : "Switch to Dark Theme", onClick: () => setTheme(resolvedTheme === "dark" ? "light" : "dark"), shape: "square", size: "small", svgOnly: true, type: "unstyled", typeName: "button", children: _jsx(Icon, { className: "size-4" }) }));
55
+ };
56
+ export const AskAIButton = ({ children, className, prompt, size = "small", variant = "secondary", ...props }) => {
57
+ const { enabled, isOpen, preloadChat, setIsOpen, setPrompt } = useGeistdocsChatContext();
58
+ if (!enabled) {
59
+ return null;
60
+ }
61
+ return (_jsx(Button, { className: cn("shrink-0", className), "data-geistdocs-ask-ai": "", onClick: () => {
62
+ preloadChat();
63
+ if (prompt) {
64
+ setPrompt(prompt);
65
+ setIsOpen(true);
66
+ return;
67
+ }
68
+ setIsOpen(!isOpen);
69
+ }, onFocus: preloadChat, onMouseEnter: preloadChat, size: size, typeName: "button", variant: variant, ...props, children: children ?? _jsx("span", { children: "Ask AI" }) }));
70
+ };
71
+ /**
72
+ * Identify the signed-in reader to Ask AI. Renders nothing; while mounted
73
+ * with an `avatarUrl`, the reader's avatar appears beside their chat
74
+ * messages. Unmount it, or pass no `avatarUrl`, to clear the reader.
75
+ */
76
+ export const AskAIUser = ({ avatarUrl, name }) => {
77
+ const { setUser } = useGeistdocsChatContext();
78
+ useEffect(() => {
79
+ if (!avatarUrl) {
80
+ setUser(null);
81
+ return;
82
+ }
83
+ setUser({ avatarUrl, name: name ?? undefined });
84
+ return () => setUser(null);
85
+ }, [avatarUrl, name, setUser]);
86
+ return null;
87
+ };
@@ -0,0 +1,2 @@
1
+ export declare const LanguageSelector: () => import("react/jsx-runtime").JSX.Element | null;
2
+ //# sourceMappingURL=language-selector.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"language-selector.d.ts","sourceRoot":"","sources":["../../src/internal/language-selector.tsx"],"names":[],"mappings":"AAWA,eAAO,MAAM,gBAAgB,sDA+B5B,CAAC"}
@@ -0,0 +1,12 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useI18n } from "fumadocs-ui/contexts/i18n";
4
+ import { IconCheck, IconLanguages } from "#geistdocs-assets/icons";
5
+ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "./ui/dropdown-menu";
6
+ export const LanguageSelector = () => {
7
+ const { locale, locales, onChange } = useI18n();
8
+ if (!locales) {
9
+ return null;
10
+ }
11
+ return (_jsxs(DropdownMenu, { children: [_jsxs(DropdownMenuTrigger, { "aria-label": "Select Language", className: "flex items-center justify-center rounded-md p-2 hover:bg-gray-alpha-100 focus-visible:shadow-[var(--ds-focus-ring)] focus-visible:outline-none active:bg-gray-alpha-300", children: [_jsx(IconLanguages, { className: "size-4.5" }), _jsx("span", { className: "sr-only", children: "Select Language" })] }), _jsx(DropdownMenuContent, { align: "end", children: locales.map((lang) => (_jsxs(DropdownMenuItem, { className: "flex cursor-pointer items-center justify-between", disabled: locale === lang.locale, onClick: () => onChange?.(lang.locale), children: [lang.name, locale === lang.locale && _jsx(IconCheck, { className: "size-4" })] }, lang.locale))) })] }));
12
+ };
@@ -0,0 +1,53 @@
1
+ import type { GeistdocsConfig, GeistdocsPageSurface, GeistdocsRetrievalProvider } from "../config.js";
2
+ import { type GeistdocsPageFilter } from "../page-visibility.js";
3
+ import { type GeistdocsSourceBundle, type GeistdocsSourcePage } from "../source.js";
4
+ import { type CreateMixedbreadClientOptions, type MixedbreadClient } from "./mixedbread.js";
5
+ export type MixedbreadReaderSurface = Extract<GeistdocsPageSurface, "chat" | "search">;
6
+ type ReaderConfig = Pick<GeistdocsConfig, "ai" | "search">;
7
+ export declare const getReaderProvider: (config: ReaderConfig, surface: MixedbreadReaderSurface) => GeistdocsRetrievalProvider;
8
+ export declare const getMixedbreadReaders: (config: ReaderConfig) => MixedbreadReaderSurface[];
9
+ /**
10
+ * Server-only Mixedbread overrides, one shape for chat and search.
11
+ * `MXBAI_API_KEY` and `MXBAI_STORE_ID` fill omitted credentials.
12
+ * `apiBaseUrl` comes only from this option.
13
+ */
14
+ export type GeistdocsMixedbreadOptions = Partial<Pick<CreateMixedbreadClientOptions, "apiBaseUrl" | "apiKey" | "fetchImpl" | "requestTimeoutMs" | "storeId">>;
15
+ export type MixedbreadConnection = {
16
+ client: MixedbreadClient;
17
+ siteId: string;
18
+ status: "ready";
19
+ } | {
20
+ missing: string[];
21
+ status: "unconfigured";
22
+ };
23
+ export declare const resolveMixedbreadConnection: ({ defaultTimeoutMs, options, siteId, }: {
24
+ defaultTimeoutMs: number;
25
+ options?: GeistdocsMixedbreadOptions;
26
+ siteId: string | undefined;
27
+ }) => MixedbreadConnection;
28
+ export interface StoreChunk {
29
+ headings: string[];
30
+ text: string;
31
+ }
32
+ export interface StorePageHit<Source> {
33
+ chunks: [StoreChunk, ...StoreChunk[]];
34
+ page: GeistdocsSourcePage;
35
+ source: Source;
36
+ }
37
+ export type StoreReader<Source> = (input: {
38
+ locale: string;
39
+ query: string;
40
+ signal?: AbortSignal;
41
+ topK: number;
42
+ }) => Promise<StorePageHit<Source>[]>;
43
+ type StoreSource = GeistdocsSourceBundle | GeistdocsSourceBundle["source"];
44
+ export declare const createStoreReader: <Source extends StoreSource>({ connection, filterPage, sources, surface, }: {
45
+ connection: Extract<MixedbreadConnection, {
46
+ status: "ready";
47
+ }>;
48
+ filterPage?: GeistdocsPageFilter<GeistdocsSourcePage, Source>;
49
+ sources: Source[];
50
+ surface: MixedbreadReaderSurface;
51
+ }) => StoreReader<Source>;
52
+ export {};
53
+ //# sourceMappingURL=mixedbread-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mixedbread-store.d.ts","sourceRoot":"","sources":["../../src/internal/mixedbread-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,eAAe,EACf,oBAAoB,EACpB,0BAA0B,EAC3B,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,KAAK,mBAAmB,EAEzB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,KAAK,qBAAqB,EAC1B,KAAK,mBAAmB,EAEzB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,KAAK,6BAA6B,EAElC,KAAK,gBAAgB,EAGtB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,MAAM,uBAAuB,GAAG,OAAO,CAC3C,oBAAoB,EACpB,MAAM,GAAG,QAAQ,CAClB,CAAC;AAEF,KAAK,YAAY,GAAG,IAAI,CAAC,eAAe,EAAE,IAAI,GAAG,QAAQ,CAAC,CAAC;AAU3D,eAAO,MAAM,iBAAiB,GAC5B,QAAQ,YAAY,EACpB,SAAS,uBAAuB,KAC/B,0BAAyE,CAAC;AAE7E,eAAO,MAAM,oBAAoB,GAC/B,QAAQ,YAAY,KACnB,uBAAuB,EAGvB,CAAC;AAEJ;;;;GAIG;AACH,MAAM,MAAM,0BAA0B,GAAG,OAAO,CAC9C,IAAI,CACF,6BAA6B,EAC7B,YAAY,GAAG,QAAQ,GAAG,WAAW,GAAG,kBAAkB,GAAG,SAAS,CACvE,CACF,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAC5B;IAAE,MAAM,EAAE,gBAAgB,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,OAAO,CAAA;CAAE,GAC7D;IAAE,OAAO,EAAE,MAAM,EAAE,CAAC;IAAC,MAAM,EAAE,cAAc,CAAA;CAAE,CAAC;AAElD,eAAO,MAAM,2BAA2B,GAAI,wCAIzC;IACD,gBAAgB,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,EAAE,0BAA0B,CAAC;IACrC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;CAC5B,KAAG,oBA4BH,CAAC;AAEF,MAAM,WAAW,UAAU;IACzB,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,YAAY,CAAC,MAAM;IAClC,MAAM,EAAE,CAAC,UAAU,EAAE,GAAG,UAAU,EAAE,CAAC,CAAC;IACtC,IAAI,EAAE,mBAAmB,CAAC;IAC1B,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,MAAM,WAAW,CAAC,MAAM,IAAI,CAAC,KAAK,EAAE;IACxC,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,IAAI,EAAE,MAAM,CAAC;CACd,KAAK,OAAO,CAAC,YAAY,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AAEtC,KAAK,WAAW,GAAG,qBAAqB,GAAG,qBAAqB,CAAC,QAAQ,CAAC,CAAC;AAoD3E,eAAO,MAAM,iBAAiB,GAAI,MAAM,SAAS,WAAW,EAAE,+CAK3D;IACD,UAAU,EAAE,OAAO,CAAC,oBAAoB,EAAE;QAAE,MAAM,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;IAC/D,UAAU,CAAC,EAAE,mBAAmB,CAAC,mBAAmB,EAAE,MAAM,CAAC,CAAC;IAC9D,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,OAAO,EAAE,uBAAuB,CAAC;CAClC,KAAG,WAAW,CAAC,MAAM,CAmErB,CAAC"}
@@ -0,0 +1,129 @@
1
+ import { isPageVisibleForSurface, } from "../page-visibility.js";
2
+ import { isGeistdocsSourceBundle, } from "../source.js";
3
+ import { createMixedbreadClient, readGeistdocsMixedbreadMetadata, } from "./mixedbread.js";
4
+ const readerProviders = {
5
+ chat: (config) => config.ai?.retrieval,
6
+ search: (config) => config.search?.provider,
7
+ };
8
+ export const getReaderProvider = (config, surface) => readerProviders[surface](config) ?? "local";
9
+ export const getMixedbreadReaders = (config) => Object.keys(readerProviders).filter((surface) => getReaderProvider(config, surface) === "mixedbread");
10
+ export const resolveMixedbreadConnection = ({ defaultTimeoutMs, options, siteId, }) => {
11
+ const apiKey = (options?.apiKey ?? process.env.MXBAI_API_KEY)?.trim();
12
+ const storeId = (options?.storeId ?? process.env.MXBAI_STORE_ID)?.trim();
13
+ const storeSiteId = siteId?.trim();
14
+ if (!(apiKey && storeId && storeSiteId)) {
15
+ return {
16
+ missing: [
17
+ !apiKey && "MXBAI_API_KEY",
18
+ !storeId && "MXBAI_STORE_ID",
19
+ !storeSiteId && "config.siteId",
20
+ ].filter((name) => Boolean(name)),
21
+ status: "unconfigured",
22
+ };
23
+ }
24
+ return {
25
+ client: createMixedbreadClient({
26
+ apiBaseUrl: options?.apiBaseUrl,
27
+ apiKey,
28
+ fetchImpl: options?.fetchImpl,
29
+ maxRetries: 0,
30
+ requestTimeoutMs: options?.requestTimeoutMs ?? defaultTimeoutMs,
31
+ storeId,
32
+ }),
33
+ siteId: storeSiteId,
34
+ status: "ready",
35
+ };
36
+ };
37
+ const readFirstLineHeading = (text) => {
38
+ const newline = text.indexOf("\n");
39
+ const line = newline === -1 ? text : text.slice(0, newline);
40
+ let hashes = 0;
41
+ while (hashes < line.length && line[hashes] === "#") {
42
+ hashes += 1;
43
+ }
44
+ const separator = line[hashes];
45
+ if (hashes < 1 || hashes > 6 || (separator !== " " && separator !== "\t")) {
46
+ return [];
47
+ }
48
+ const heading = line.slice(hashes + 1).trim();
49
+ return heading ? [heading] : [];
50
+ };
51
+ const isRecord = (value) => typeof value === "object" && value !== null;
52
+ const getChunkText = (chunk) => {
53
+ for (const value of [chunk.text, chunk.summary, chunk.context]) {
54
+ const text = typeof value === "string" ? value.trim() : "";
55
+ if (text) {
56
+ return text;
57
+ }
58
+ }
59
+ };
60
+ const readHeadingTexts = (value) => Array.isArray(value)
61
+ ? value.flatMap((entry) => isRecord(entry) && typeof entry.text === "string" && entry.text.trim()
62
+ ? [entry.text.trim()]
63
+ : [])
64
+ : [];
65
+ const getHeadingCandidates = (generatedMetadata, text) => {
66
+ const metadata = isRecord(generatedMetadata) ? generatedMetadata : {};
67
+ const fromMetadata = [
68
+ ...readHeadingTexts(metadata.chunk_headings),
69
+ ...readHeadingTexts(metadata.heading_context).reverse(),
70
+ ];
71
+ if (fromMetadata.length > 0) {
72
+ return fromMetadata;
73
+ }
74
+ return readFirstLineHeading(text);
75
+ };
76
+ export const createStoreReader = ({ connection, filterPage, sources, surface, }) => {
77
+ const resolveLivePage = (sourceUrl, locale) => {
78
+ for (const [index, source] of sources.entries()) {
79
+ const input = source;
80
+ const loader = isGeistdocsSourceBundle(input) ? input.source : input;
81
+ const page = loader.getPageByHref(sourceUrl, { language: locale })?.page;
82
+ if (page) {
83
+ return { key: `${index}:${page.url}`, page, source };
84
+ }
85
+ }
86
+ };
87
+ return async ({ locale, query, signal, topK }) => {
88
+ const chunks = await connection.client.search({
89
+ locale,
90
+ query,
91
+ signal,
92
+ siteId: connection.siteId,
93
+ topK,
94
+ });
95
+ const hits = new Map();
96
+ for (const chunk of chunks) {
97
+ const metadata = readGeistdocsMixedbreadMetadata(chunk.metadata);
98
+ const text = getChunkText(chunk);
99
+ if (!(metadata && text) ||
100
+ metadata.siteId !== connection.siteId ||
101
+ metadata.locale !== locale) {
102
+ continue;
103
+ }
104
+ const live = resolveLivePage(metadata.sourceUrl, locale);
105
+ if (!(live &&
106
+ isPageVisibleForSurface(live.page, surface) &&
107
+ (filterPage?.(live.page, { lang: locale, source: live.source }) ??
108
+ true))) {
109
+ continue;
110
+ }
111
+ const storeChunk = {
112
+ headings: getHeadingCandidates(chunk.generated_metadata, text),
113
+ text,
114
+ };
115
+ const hit = hits.get(live.key);
116
+ if (!hit) {
117
+ hits.set(live.key, {
118
+ chunks: [storeChunk],
119
+ page: live.page,
120
+ source: live.source,
121
+ });
122
+ }
123
+ else if (!hit.chunks.some((existing) => existing.text === text)) {
124
+ hit.chunks.push(storeChunk);
125
+ }
126
+ }
127
+ return Array.from(hits.values());
128
+ };
129
+ };