Skip to content

Build your personal knowledge base with Trilium Notes

Merge remote-tracking branch 'origin/main' into claude/standalone-shared-notes-ojp5x2

Elian Doran393296ea2625
diff --cc apps/server/package.json
index d378ee9216,656b5d0a6c..7143617141
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@@ -38,8 -38,9 +38,8 @@@
"@anthropic-ai/claude-agent-sdk": "^0.3.207",
"@hyzyla/pdfium": "2.1.13",
"@modelcontextprotocol/sdk": "^1.12.1",
- "ai": "7.0.102",
+ "ai": "7.0.107",
"better-sqlite3": "13.0.3",
- "html-to-text": "10.0.1",
"i18next": "26.4.2",
"ipaddr.js": "^2.4.0",
"js-yaml": "5.4.2",
diff --cc apps/standalone/src/lightweight/browser_routes.ts
index fbeea9bec1,84ec45b176..e807c0e51d
--- a/apps/standalone/src/lightweight/browser_routes.ts
+++ b/apps/standalone/src/lightweight/browser_routes.ts
@@@ -4,10 -4,8 +4,10 @@@
*/
import { BootstrapDefinition } from '@triliumnext/commons';
- import { checkIntegrity, consistency_checks, entity_changes, getContext, getPlatform, getSharedBootstrapItems, getSql, type Request, type Response, routes, sql_init } from '@triliumnext/core';
+ import { checkIntegrity, consistency_checks, entity_changes, getContext, getPlatform, getSharedBootstrapItems, getSql, isScriptingEnabled, type Request, type Response, routes, sql_init } from '@triliumnext/core';
import llmRoute from '@triliumnext/core/src/routes/api/llm.js';
+import type { ShareReply } from '@triliumnext/core/src/share/handlers.js';
+import { SHARE_ROUTE_PATHS, type ShareRoutePath } from '@triliumnext/core/src/share/route_paths.js';
import packageJson from '../../package.json' with { type: 'json' };
import { type BrowserRequest, BrowserRouter } from './browser_router';
@@@ -334,18 -357,8 +359,20 @@@ export function registerRoutes(router:
apiResultHandler
);
+ // Shared notes, served from the same database the app reads. Nobody outside this browser can
+ // reach them — there is no server listening — but a published note renders at its real /share
+ // URL, which is what makes the feature testable here at all. Registered by path alone and
+ // loaded on the first request, so EJS, the share theme and the syntax highlighter stay out of
+ // the worker's startup bundle.
+ for (const path of SHARE_ROUTE_PATHS) {
+ router.get(path, (req) => dispatchShare(path, req));
+ }
+ // The share root is addressed as `/share/`; `/share` answers with the redirect that adds the
+ // slash, which the pattern above cannot match because a parameter needs a segment to fill it.
+ router.get("/share", (req) => dispatchShare("/share/", req));
+
+ registerCustomRoute(router);
+
// Dummy routes for compatibility.
apiRoute("get", "/api/script/widgets", () => []);
apiRoute("get", "/api/script/startup", () => []);
@@@ -395,44 -408,58 +422,96 @@@ function bootstrapRoute(req: { query: R
};
}
+/** Answers one share request, loading the share subsystem the first time one arrives. */
+async function dispatchShare(path: ShareRoutePath, req: BrowserRequest) {
+ const [ share, { registerShareProvider } ] = await Promise.all([
+ import("@triliumnext/core/src/share/index.js"),
+ import("./share_provider.js")
+ ]);
+
+ registerShareProvider();
+
+ /* v8 ignore next -- @preserve: BrowserRouter.dispatch always sets req.headers, so the ?? fallback is unreachable. */
+ const headers = req.headers ?? {};
+ const shareRequest = {
+ path: req.path,
+ params: req.params,
+ query: req.query,
+ // `fetch` lower-cases the header names it sends, which is the form BrowserRouter stores them in.
+ getHeader: (name: string) => headers[name.toLowerCase()]
+ };
+
+ // Shared, and without a transaction: the share routes only read. The imports above are awaited
+ // before the lock is taken, so nothing is held open across them.
+ return dbLock.runShared(() => getContext().init(() => {
+ const reply = share.handleShareRequest(share.getShareRoute(path), shareRequest);
+
+ return toRawShareResponse(reply);
+ }));
+}
+
+/** Marks a share reply as already formatted, so {@link BrowserRouter} sends it rather than re-wrapping it. */
+function toRawShareResponse(reply: ShareReply) {
+ return {
+ [RAW_RESPONSE]: true as const,
+ status: reply.status,
+ headers: reply.redirect ? { ...reply.headers, location: reply.redirect } : reply.headers,
+ body: reply.body
+ };
+}
+
+ /**
+ * Every method a handler script can answer. The server registers its route as an Express `all`,
+ * which covers HEAD and OPTIONS too, so both are registered here to match — `BrowserRouter` matches
+ * on the method, and one left out answers the router's own 404 rather than reaching the handler.
+ */
+ const CUSTOM_HANDLER_METHODS = ["get", "head", "post", "put", "patch", "delete", "options"];
+
+ /**
+ * Serves `/custom/`: the notes labelled `#customRequestHandler` and `#customResourceProvider`.
+ *
+ * Registered here rather than in the shared table because the server answers it from a route of its
+ * own, ahead of the API router and without CSRF, and because it takes any method rather than one.
+ */
+ function registerCustomRoute(router: BrowserRouter) {
+ for (const method of CUSTOM_HANDLER_METHODS) {
+ router.register(method, "/custom/*path", (req: BrowserRequest) => dbLock.runShared(
+ () => getContext().init(async () => {
+ setContextFromHeaders(req);
+ const path = req.params.path;
+ const res = createMockResponse();
+
+ // Handler scripts can await, and a transaction held across that wait would block
+ // every other request on the worker's single SQLite connection.
+ //
+ // Awaited because this runtime sends the response as soon as the handler is done,
+ // where Express holds the connection open past it. A script that answers after an
+ // `await` returns its promise, which has to settle before the body goes out.
+ await routes.handleCustomRequest(path, toCoreRequest(req), res, isScriptingEnabled);
+
+ if (!res._used) {
+ res.setHeader("Content-Type", "text/plain").status(500)
+ .send(`Custom handler for '${path}' did not send a response.`);
+ }
+
+ // A HEAD response carries the status and headers of the GET it stands in for, and
+ // nothing else. Express strips the body itself.
+ return toRawResponse(res, req.method === "HEAD");
+ }) as Promise<unknown>
+ ));
+ }
+ }
+
+ /** Wraps what a handler wrote to its mock response so {@link BrowserRouter} sends it verbatim. */
+ function toRawResponse(res: ReturnType<typeof createMockResponse>, omitBody = false) {
+ return {
+ [RAW_RESPONSE]: true as const,
+ status: res._status,
+ headers: res._headers,
+ body: omitBody ? null : res._body
+ };
+ }
+
/**
* Create and configure a router with all routes registered.
*/
diff --cc apps/standalone/src/sw.spec.ts
index cf284eb6db,301c1bb7c7..af63b2845f
--- a/apps/standalone/src/sw.spec.ts
+++ b/apps/standalone/src/sw.spec.ts
@@@ -135,42 -135,14 +135,48 @@@ describe("fetch routing", () =>
const event = fetchEvent(`${origin}/api/notes`);
handlers.fetch(event);
expect(event._response).toBeDefined();
+
+ // `/custom/` carries custom request handlers and resource providers. Left off this list it
+ // would be fetched as a static asset, over a network this build does not have.
+ const custom = fetchEvent(`${origin}/custom/my-handler`);
+ handlers.fetch(custom);
+ expect(custom._response).toBeDefined();
});
+ it("routes shared-note pages to the client bridge but serves the share theme's assets statically", async () => {
+ const handlers = await loadSw();
+
+ for (const path of [ "/share", "/share/", "/share/my-alias", "/share/api/notes/abc123" ]) {
+ const event = fetchEvent(`${origin}${path}`, { mode: "navigate" });
+ handlers.fetch(event);
+ expect(event._response, path).toBeDefined();
+ }
+
+ // The theme's own files ship with the build, so they take the ordinary static path.
+ vi.mocked(fetch).mockClear();
+ const asset = fetchEvent(`${origin}/share/assets/styles.css`);
+ handlers.fetch(asset);
+ await awaitResponse(asset);
+ expect(fetch).toHaveBeenCalled();
+ });
+
+ it("explains that Trilium must be open when a share page finds no app window", async () => {
+ // A lone pdfjs frame is not an app window: it carries no local bridge to render the page.
+ (self as unknown as SwGlobals).clients = {
+ claim: vi.fn(),
+ matchAll: vi.fn(async () => [{ url: `${origin}/pdfjs/viewer.html`, postMessage: vi.fn() }])
+ };
+ const handlers = await loadSw();
+ const event = fetchEvent(`${origin}/share/my-alias`, { mode: "navigate" });
+ handlers.fetch(event);
+
+ const res = await awaitResponse(event);
+ expect(res.status).toBe(503);
+ expect(await res.text()).toContain("Open Trilium in this browser");
+ // Nothing to forward to, and no server behind it either.
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
it("serves navigations and .html network-first (which bypasses cache in dev)", async () => {
const handlers = await loadSw();
const navEvent = fetchEvent(`${origin}/index.html`, { mode: "navigate" });
diff --cc packages/trilium-core/package.json
index 3608147334,af213f14f7..ea9f01c507
--- a/packages/trilium-core/package.json
+++ b/packages/trilium-core/package.json
@@@ -8,14 -8,13 +8,14 @@@
"update-model-prices": "tsx ./scripts/update-model-prices.ts"
},
"dependencies": {
- "@ai-sdk/anthropic": "4.0.54",
- "@ai-sdk/google": "4.0.72",
- "@ai-sdk/openai": "4.0.67",
+ "@ai-sdk/anthropic": "4.0.58",
+ "@ai-sdk/google": "4.0.76",
+ "@ai-sdk/openai": "4.0.71",
"@braintree/sanitize-url": "7.1.2",
"@triliumnext/commons": "workspace:*",
+ "@triliumnext/highlightjs": "workspace:*",
"@triliumnext/turndown-plugin-gfm": "workspace:*",
- "ai": "7.0.102",
+ "ai": "7.0.107",
"async-mutex": "0.5.0",
"chardet": "2.2.0",
"color": "5.0.3",